blob: a4e65ee76560095b7159cffe1be6865d9b184d74 [file] [log] [blame]
Chris Lattner3d1cee32008-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 McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-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 Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000040#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000041#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000042
43using namespace clang;
44
Chris Lattner8123a952008-04-10 02:22:51 +000045//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
Chris Lattner9e979552008-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 Kramer85b45212009-11-28 19:45:26 +000055 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000056 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000057 Expr *DefaultArg;
58 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 public:
Mike Stump1eb44332009-09-09 15:08:12 +000061 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000062 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000063
Chris Lattner9e979552008-04-12 23:52:44 +000064 bool VisitExpr(Expr *Node);
65 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000066 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000067 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000068 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000069 };
Chris Lattner8123a952008-04-10 02:22:51 +000070
Chris Lattner9e979552008-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 McCall7502c1d2011-02-13 04:07:26 +000074 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000075 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000076 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000077 }
78
Chris Lattner9e979552008-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 Gregor8e9bebd2008-10-21 16:13:35 +000083 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-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 Dunbar96a00142012-03-09 18:35:03 +000093 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000094 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000095 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000096 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000097 // C++ [dcl.fct.default]p7
98 // Local variables shall not be used in default argument
99 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000100 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000101 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000102 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000103 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000104 }
Chris Lattner8123a952008-04-10 02:22:51 +0000105
Douglas Gregor3996f232008-11-04 13:41:56 +0000106 return false;
107 }
Chris Lattner9e979552008-04-12 23:52:44 +0000108
Douglas Gregor796da182008-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 Dunbar96a00142012-03-09 18:35:03 +0000114 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000115 diag::err_param_default_argument_references_this)
116 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000117 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000118
John McCall045d2522013-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 Gregorf0459f82012-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 Lattner8123a952008-04-10 02:22:51 +0000146}
147
Richard Smith0b0ca472013-04-10 06:11:48 +0000148void
149Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
150 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000151 // If we have an MSAny spec already, don't bother.
152 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000153 return;
154
155 const FunctionProtoType *Proto
156 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000157 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
158 if (!Proto)
159 return;
Sean Hunt001cad92011-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 Smithb9d0b762012-07-27 04:22:15 +0000164 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000165 ClearExceptions();
166 ComputedEST = EST;
167 return;
168 }
169
Richard Smith7a614d82011-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
Sean Hunt001cad92011-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 Smithe6975e92012-04-17 00:58:00 +0000191 FunctionProtoType::NoexceptResult NR =
192 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-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 Smithe6975e92012-04-17 00:58:00 +0000216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000217 Exceptions.push_back(*E);
218}
219
Richard Smith7a614d82011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-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 Smith7a614d82011-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 Smithe6975e92012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssoned961f92009-08-25 02:29:20 +0000249bool
John McCall9ae2f072010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-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 Carlssoned961f92009-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 Jahanian745da3a2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000271 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000273
Richard Smith6c3af3d2013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Anders Carlssoned961f92009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Douglas Gregor8cfb7a32010-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 Carlsson9351c172009-08-25 03:18:48 +0000292 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000293}
294
Chris Lattner8123a952008-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 Lattner3d1cee32008-04-08 05:04:30 +0000298void
John McCalld226f652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000302 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCalld226f652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner3d1cee32008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6f526752010-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 Carlsson66e30672009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
John McCall9ae2f072010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000329}
330
Douglas Gregor61366e92008-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 McCalld226f652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCalld226f652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param)
343 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Anders Carlsson5e300d12009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000346}
347
Douglas Gregor72b505b2008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
John McCalld226f652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Anders Carlsson5e300d12009-06-12 16:51:40 +0000356 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Anders Carlsson5e300d12009-06-12 16:51:40 +0000358 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000359}
360
Douglas Gregor6d6eb572008-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 Smith3cdbbdc2013-03-06 01:37:38 +0000374 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000376 DeclaratorChunk &chunk = D.getTypeObject(i);
377 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-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 Lattnerb28317a2009-03-28 19:18:32 +0000385 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
386 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000387 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000388 if (Param->hasUnparsedDefaultArg()) {
389 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000391 << SourceRange((*Toks)[1].getLocation(),
392 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000393 delete Toks;
394 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-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 Gregor6d6eb572008-05-07 04:49:29 +0000399 }
400 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000401 } else if (chunk.Kind != DeclaratorChunk::Paren) {
402 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000403 }
404 }
405}
406
Craig Topper1a6eac82012-09-21 04:33:26 +0000407/// MergeCXXFunctionDecl - Merge two declarations of the same C++
408/// function, once we already know that they have the same
409/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
410/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000411bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
412 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000413 bool Invalid = false;
414
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000416 // For non-template functions, default arguments can be added in
417 // later declarations of a function in the same
418 // scope. Declarations in different scopes have completely
419 // distinct sets of default arguments. That is, declarations in
420 // inner scopes do not acquire default arguments from
421 // declarations in outer scopes, and vice versa. In a given
422 // function declaration, all parameters subsequent to a
423 // parameter with a default argument shall have default
424 // arguments supplied in this or previous declarations. A
425 // default argument shall not be redefined by a later
426 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000427 //
428 // C++ [dcl.fct.default]p6:
429 // Except for member functions of class templates, the default arguments
430 // in a member function definition that appears outside of the class
431 // definition are added to the set of default arguments provided by the
432 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000433 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
434 ParmVarDecl *OldParam = Old->getParamDecl(p);
435 ParmVarDecl *NewParam = New->getParamDecl(p);
436
James Molloy9cda03f2012-03-13 08:55:35 +0000437 bool OldParamHasDfl = OldParam->hasDefaultArg();
438 bool NewParamHasDfl = NewParam->hasDefaultArg();
439
440 NamedDecl *ND = Old;
441 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
442 // Ignore default parameters of old decl if they are not in
443 // the same scope.
444 OldParamHasDfl = false;
445
446 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000447
Francois Pichet8d051e02011-04-10 03:03:52 +0000448 unsigned DiagDefaultParamID =
449 diag::err_param_default_argument_redefinition;
450
451 // MSVC accepts that default parameters be redefined for member functions
452 // of template class. The new default parameter's value is ignored.
453 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000454 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000455 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
456 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000457 // Merge the old default argument into the new parameter.
458 NewParam->setHasInheritedDefaultArg();
459 if (OldParam->hasUninstantiatedDefaultArg())
460 NewParam->setUninstantiatedDefaultArg(
461 OldParam->getUninstantiatedDefaultArg());
462 else
463 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000464 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000465 Invalid = false;
466 }
467 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000468
Francois Pichet8cf90492011-04-10 04:58:30 +0000469 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
470 // hint here. Alternatively, we could walk the type-source information
471 // for NewParam to find the last source location in the type... but it
472 // isn't worth the effort right now. This is the kind of test case that
473 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000474 // int f(int);
475 // void g(int (*fp)(int) = f);
476 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000477 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000478 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000479
480 // Look for the function declaration where the default argument was
481 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000482 for (FunctionDecl *Older = Old->getPreviousDecl();
483 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000484 if (!Older->getParamDecl(p)->hasDefaultArg())
485 break;
486
487 OldParam = Older->getParamDecl(p);
488 }
489
490 Diag(OldParam->getLocation(), diag::note_previous_definition)
491 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000492 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000493 // Merge the old default argument into the new parameter.
494 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000495 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000496 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000497 if (OldParam->hasUninstantiatedDefaultArg())
498 NewParam->setUninstantiatedDefaultArg(
499 OldParam->getUninstantiatedDefaultArg());
500 else
John McCall3d6c1782010-05-04 01:53:42 +0000501 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000502 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000503 if (New->getDescribedFunctionTemplate()) {
504 // Paragraph 4, quoted above, only applies to non-template functions.
505 Diag(NewParam->getLocation(),
506 diag::err_param_default_argument_template_redecl)
507 << NewParam->getDefaultArgRange();
508 Diag(Old->getLocation(), diag::note_template_prev_declaration)
509 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000510 } else if (New->getTemplateSpecializationKind()
511 != TSK_ImplicitInstantiation &&
512 New->getTemplateSpecializationKind() != TSK_Undeclared) {
513 // C++ [temp.expr.spec]p21:
514 // Default function arguments shall not be specified in a declaration
515 // or a definition for one of the following explicit specializations:
516 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000517 // - the explicit specialization of a member function template;
518 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000519 // template where the class template specialization to which the
520 // member function specialization belongs is implicitly
521 // instantiated.
522 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
523 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
524 << New->getDeclName()
525 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000526 } else if (New->getDeclContext()->isDependentContext()) {
527 // C++ [dcl.fct.default]p6 (DR217):
528 // Default arguments for a member function of a class template shall
529 // be specified on the initial declaration of the member function
530 // within the class template.
531 //
532 // Reading the tea leaves a bit in DR217 and its reference to DR205
533 // leads me to the conclusion that one cannot add default function
534 // arguments for an out-of-line definition of a member function of a
535 // dependent type.
536 int WhichKind = 2;
537 if (CXXRecordDecl *Record
538 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
539 if (Record->getDescribedClassTemplate())
540 WhichKind = 0;
541 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
542 WhichKind = 1;
543 else
544 WhichKind = 2;
545 }
546
547 Diag(NewParam->getLocation(),
548 diag::err_param_default_argument_member_template_redecl)
549 << WhichKind
550 << NewParam->getDefaultArgRange();
551 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000552 }
553 }
554
Richard Smithb8abff62012-11-28 03:45:24 +0000555 // DR1344: If a default argument is added outside a class definition and that
556 // default argument makes the function a special member function, the program
557 // is ill-formed. This can only happen for constructors.
558 if (isa<CXXConstructorDecl>(New) &&
559 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
560 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
561 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
562 if (NewSM != OldSM) {
563 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
564 assert(NewParam->hasDefaultArg());
565 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
566 << NewParam->getDefaultArgRange() << NewSM;
567 Diag(Old->getLocation(), diag::note_previous_declaration);
568 }
569 }
570
Richard Smithff234882012-02-20 23:28:05 +0000571 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000572 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000573 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000574 if (New->isConstexpr() != Old->isConstexpr()) {
575 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
576 << New << New->isConstexpr();
577 Diag(Old->getLocation(), diag::note_previous_declaration);
578 Invalid = true;
579 }
580
Douglas Gregore13ad832010-02-12 07:32:17 +0000581 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000582 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000583
Douglas Gregorcda9c672009-02-16 17:45:42 +0000584 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000585}
586
Sebastian Redl60618fa2011-03-12 11:50:43 +0000587/// \brief Merge the exception specifications of two variable declarations.
588///
589/// This is called when there's a redeclaration of a VarDecl. The function
590/// checks if the redeclaration might have an exception specification and
591/// validates compatibility and merges the specs if necessary.
592void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
593 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000594 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000595 return;
596
597 assert(Context.hasSameType(New->getType(), Old->getType()) &&
598 "Should only be called if types are otherwise the same.");
599
600 QualType NewType = New->getType();
601 QualType OldType = Old->getType();
602
603 // We're only interested in pointers and references to functions, as well
604 // as pointers to member functions.
605 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
606 NewType = R->getPointeeType();
607 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
608 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
609 NewType = P->getPointeeType();
610 OldType = OldType->getAs<PointerType>()->getPointeeType();
611 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
612 NewType = M->getPointeeType();
613 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
614 }
615
616 if (!NewType->isFunctionProtoType())
617 return;
618
619 // There's lots of special cases for functions. For function pointers, system
620 // libraries are hopefully not as broken so that we don't need these
621 // workarounds.
622 if (CheckEquivalentExceptionSpec(
623 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
624 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
625 New->setInvalidDecl();
626 }
627}
628
Chris Lattner3d1cee32008-04-08 05:04:30 +0000629/// CheckCXXDefaultArguments - Verify that the default arguments for a
630/// function declaration are well-formed according to C++
631/// [dcl.fct.default].
632void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
633 unsigned NumParams = FD->getNumParams();
634 unsigned p;
635
636 // Find first parameter with a default argument
637 for (p = 0; p < NumParams; ++p) {
638 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000639 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000640 break;
641 }
642
643 // C++ [dcl.fct.default]p4:
644 // In a given function declaration, all parameters
645 // subsequent to a parameter with a default argument shall
646 // have default arguments supplied in this or previous
647 // declarations. A default argument shall not be redefined
648 // by a later declaration (not even to the same value).
649 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000650 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000651 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000652 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000653 if (Param->isInvalidDecl())
654 /* We already complained about this parameter. */;
655 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000656 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000657 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000658 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000659 else
Mike Stump1eb44332009-09-09 15:08:12 +0000660 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000661 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Chris Lattner3d1cee32008-04-08 05:04:30 +0000663 LastMissingDefaultArg = p;
664 }
665 }
666
667 if (LastMissingDefaultArg > 0) {
668 // Some default arguments were missing. Clear out all of the
669 // default arguments up to (and including) the last missing
670 // default argument, so that we leave the function parameters
671 // in a semantically valid state.
672 for (p = 0; p <= LastMissingDefaultArg; ++p) {
673 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000674 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000675 Param->setDefaultArg(0);
676 }
677 }
678 }
679}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000680
Richard Smith9f569cc2011-10-01 02:31:28 +0000681// CheckConstexprParameterTypes - Check whether a function's parameter types
682// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000683// diagnostic and return false.
684static bool CheckConstexprParameterTypes(Sema &SemaRef,
685 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000686 unsigned ArgIndex = 0;
687 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
688 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
689 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
690 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
691 SourceLocation ParamLoc = PD->getLocation();
692 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000693 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000694 diag::err_constexpr_non_literal_param,
695 ArgIndex+1, PD->getSourceRange(),
696 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000697 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000698 }
Joao Matos17d35c32012-08-31 22:18:20 +0000699 return true;
700}
701
702/// \brief Get diagnostic %select index for tag kind for
703/// record diagnostic message.
704/// WARNING: Indexes apply to particular diagnostics only!
705///
706/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000707static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000708 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000709 case TTK_Struct: return 0;
710 case TTK_Interface: return 1;
711 case TTK_Class: return 2;
712 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000713 }
Joao Matos17d35c32012-08-31 22:18:20 +0000714}
715
716// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
717// the requirements of a constexpr function definition or a constexpr
718// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000719// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000720//
Richard Smith86c3ae42012-02-13 03:54:03 +0000721// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
722bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000723 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
724 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000725 // C++11 [dcl.constexpr]p4:
726 // The definition of a constexpr constructor shall satisfy the following
727 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000728 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000729 const CXXRecordDecl *RD = MD->getParent();
730 if (RD->getNumVBases()) {
731 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
732 << isa<CXXConstructorDecl>(NewFD)
733 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
734 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
735 E = RD->vbases_end(); I != E; ++I)
736 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000737 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000738 return false;
739 }
Richard Smith35340502012-01-13 04:54:00 +0000740 }
741
742 if (!isa<CXXConstructorDecl>(NewFD)) {
743 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000744 // The definition of a constexpr function shall satisfy the following
745 // constraints:
746 // - it shall not be virtual;
747 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
748 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000749 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000750
Richard Smith86c3ae42012-02-13 03:54:03 +0000751 // If it's not obvious why this function is virtual, find an overridden
752 // function which uses the 'virtual' keyword.
753 const CXXMethodDecl *WrittenVirtual = Method;
754 while (!WrittenVirtual->isVirtualAsWritten())
755 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
756 if (WrittenVirtual != Method)
757 Diag(WrittenVirtual->getLocation(),
758 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000759 return false;
760 }
761
762 // - its return type shall be a literal type;
763 QualType RT = NewFD->getResultType();
764 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000765 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000766 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000767 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000768 }
769
Richard Smith35340502012-01-13 04:54:00 +0000770 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000771 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000772 return false;
773
Richard Smith9f569cc2011-10-01 02:31:28 +0000774 return true;
775}
776
777/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000778/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000779///
Richard Smitha10b9782013-04-22 15:31:51 +0000780/// \return true if the body is OK (maybe only as an extension), false if we
781/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000782static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000783 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
784 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000785 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
786 // contain only
787 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
788 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
789 switch ((*DclIt)->getKind()) {
790 case Decl::StaticAssert:
791 case Decl::Using:
792 case Decl::UsingShadow:
793 case Decl::UsingDirective:
794 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000795 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000796 // - static_assert-declarations
797 // - using-declarations,
798 // - using-directives,
799 continue;
800
801 case Decl::Typedef:
802 case Decl::TypeAlias: {
803 // - typedef declarations and alias-declarations that do not define
804 // classes or enumerations,
805 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
806 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
807 // Don't allow variably-modified types in constexpr functions.
808 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
809 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
810 << TL.getSourceRange() << TL.getType()
811 << isa<CXXConstructorDecl>(Dcl);
812 return false;
813 }
814 continue;
815 }
816
817 case Decl::Enum:
818 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000819 // C++1y allows types to be defined, not just declared.
820 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
821 SemaRef.Diag(DS->getLocStart(),
822 SemaRef.getLangOpts().CPlusPlus1y
823 ? diag::warn_cxx11_compat_constexpr_type_definition
824 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000825 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000826 continue;
827
Richard Smitha10b9782013-04-22 15:31:51 +0000828 case Decl::EnumConstant:
829 case Decl::IndirectField:
830 case Decl::ParmVar:
831 // These can only appear with other declarations which are banned in
832 // C++11 and permitted in C++1y, so ignore them.
833 continue;
834
835 case Decl::Var: {
836 // C++1y [dcl.constexpr]p3 allows anything except:
837 // a definition of a variable of non-literal type or of static or
838 // thread storage duration or for which no initialization is performed.
839 VarDecl *VD = cast<VarDecl>(*DclIt);
840 if (VD->isThisDeclarationADefinition()) {
841 if (VD->isStaticLocal()) {
842 SemaRef.Diag(VD->getLocation(),
843 diag::err_constexpr_local_var_static)
844 << isa<CXXConstructorDecl>(Dcl)
845 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
846 return false;
847 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000848 if (!VD->getType()->isDependentType() &&
849 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000850 VD->getLocation(), VD->getType(),
851 diag::err_constexpr_local_var_non_literal_type,
852 isa<CXXConstructorDecl>(Dcl)))
853 return false;
854 if (!VD->hasInit()) {
855 SemaRef.Diag(VD->getLocation(),
856 diag::err_constexpr_local_var_no_init)
857 << isa<CXXConstructorDecl>(Dcl);
858 return false;
859 }
860 }
861 SemaRef.Diag(VD->getLocation(),
862 SemaRef.getLangOpts().CPlusPlus1y
863 ? diag::warn_cxx11_compat_constexpr_local_var
864 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000865 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000866 continue;
867 }
868
869 case Decl::NamespaceAlias:
870 case Decl::Function:
871 // These are disallowed in C++11 and permitted in C++1y. Allow them
872 // everywhere as an extension.
873 if (!Cxx1yLoc.isValid())
874 Cxx1yLoc = DS->getLocStart();
875 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000876
877 default:
878 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
879 << isa<CXXConstructorDecl>(Dcl);
880 return false;
881 }
882 }
883
884 return true;
885}
886
887/// Check that the given field is initialized within a constexpr constructor.
888///
889/// \param Dcl The constexpr constructor being checked.
890/// \param Field The field being checked. This may be a member of an anonymous
891/// struct or union nested within the class being checked.
892/// \param Inits All declarations, including anonymous struct/union members and
893/// indirect members, for which any initialization was provided.
894/// \param Diagnosed Set to true if an error is produced.
895static void CheckConstexprCtorInitializer(Sema &SemaRef,
896 const FunctionDecl *Dcl,
897 FieldDecl *Field,
898 llvm::SmallSet<Decl*, 16> &Inits,
899 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000900 if (Field->isUnnamedBitfield())
901 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000902
903 if (Field->isAnonymousStructOrUnion() &&
904 Field->getType()->getAsCXXRecordDecl()->isEmpty())
905 return;
906
Richard Smith9f569cc2011-10-01 02:31:28 +0000907 if (!Inits.count(Field)) {
908 if (!Diagnosed) {
909 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
910 Diagnosed = true;
911 }
912 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
913 } else if (Field->isAnonymousStructOrUnion()) {
914 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
915 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
916 I != E; ++I)
917 // If an anonymous union contains an anonymous struct of which any member
918 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000919 if (!RD->isUnion() || Inits.count(*I))
920 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000921 }
922}
923
Richard Smitha10b9782013-04-22 15:31:51 +0000924/// Check the provided statement is allowed in a constexpr function
925/// definition.
926static bool
927CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
928 llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
929 SourceLocation &Cxx1yLoc) {
930 // - its function-body shall be [...] a compound-statement that contains only
931 switch (S->getStmtClass()) {
932 case Stmt::NullStmtClass:
933 // - null statements,
934 return true;
935
936 case Stmt::DeclStmtClass:
937 // - static_assert-declarations
938 // - using-declarations,
939 // - using-directives,
940 // - typedef declarations and alias-declarations that do not define
941 // classes or enumerations,
942 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
943 return false;
944 return true;
945
946 case Stmt::ReturnStmtClass:
947 // - and exactly one return statement;
948 if (isa<CXXConstructorDecl>(Dcl)) {
949 // C++1y allows return statements in constexpr constructors.
950 if (!Cxx1yLoc.isValid())
951 Cxx1yLoc = S->getLocStart();
952 return true;
953 }
954
955 ReturnStmts.push_back(S->getLocStart());
956 return true;
957
958 case Stmt::CompoundStmtClass: {
959 // C++1y allows compound-statements.
960 if (!Cxx1yLoc.isValid())
961 Cxx1yLoc = S->getLocStart();
962
963 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
964 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
965 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
966 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
967 Cxx1yLoc))
968 return false;
969 }
970 return true;
971 }
972
973 case Stmt::AttributedStmtClass:
974 if (!Cxx1yLoc.isValid())
975 Cxx1yLoc = S->getLocStart();
976 return true;
977
978 case Stmt::IfStmtClass: {
979 // C++1y allows if-statements.
980 if (!Cxx1yLoc.isValid())
981 Cxx1yLoc = S->getLocStart();
982
983 IfStmt *If = cast<IfStmt>(S);
984 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
985 Cxx1yLoc))
986 return false;
987 if (If->getElse() &&
988 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
989 Cxx1yLoc))
990 return false;
991 return true;
992 }
993
994 case Stmt::WhileStmtClass:
995 case Stmt::DoStmtClass:
996 case Stmt::ForStmtClass:
997 case Stmt::CXXForRangeStmtClass:
998 case Stmt::ContinueStmtClass:
999 // C++1y allows all of these. We don't allow them as extensions in C++11,
1000 // because they don't make sense without variable mutation.
1001 if (!SemaRef.getLangOpts().CPlusPlus1y)
1002 break;
1003 if (!Cxx1yLoc.isValid())
1004 Cxx1yLoc = S->getLocStart();
1005 for (Stmt::child_range Children = S->children(); Children; ++Children)
1006 if (*Children &&
1007 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1008 Cxx1yLoc))
1009 return false;
1010 return true;
1011
1012 case Stmt::SwitchStmtClass:
1013 case Stmt::CaseStmtClass:
1014 case Stmt::DefaultStmtClass:
1015 case Stmt::BreakStmtClass:
1016 // C++1y allows switch-statements, and since they don't need variable
1017 // mutation, we can reasonably allow them in C++11 as an extension.
1018 if (!Cxx1yLoc.isValid())
1019 Cxx1yLoc = S->getLocStart();
1020 for (Stmt::child_range Children = S->children(); Children; ++Children)
1021 if (*Children &&
1022 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1023 Cxx1yLoc))
1024 return false;
1025 return true;
1026
1027 default:
1028 if (!isa<Expr>(S))
1029 break;
1030
1031 // C++1y allows expression-statements.
1032 if (!Cxx1yLoc.isValid())
1033 Cxx1yLoc = S->getLocStart();
1034 return true;
1035 }
1036
1037 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1038 << isa<CXXConstructorDecl>(Dcl);
1039 return false;
1040}
1041
Richard Smith9f569cc2011-10-01 02:31:28 +00001042/// Check the body for the given constexpr function declaration only contains
1043/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1044///
1045/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001046bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001047 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001048 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001049 // The definition of a constexpr function shall satisfy the following
1050 // constraints: [...]
1051 // - its function-body shall be = delete, = default, or a
1052 // compound-statement
1053 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001054 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001055 // In the definition of a constexpr constructor, [...]
1056 // - its function-body shall not be a function-try-block;
1057 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1058 << isa<CXXConstructorDecl>(Dcl);
1059 return false;
1060 }
1061
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001062 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001063
1064 // - its function-body shall be [...] a compound-statement that contains only
1065 // [... list of cases ...]
1066 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1067 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001068 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1069 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001070 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1071 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001072 }
1073
Richard Smitha10b9782013-04-22 15:31:51 +00001074 if (Cxx1yLoc.isValid())
1075 Diag(Cxx1yLoc,
1076 getLangOpts().CPlusPlus1y
1077 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1078 : diag::ext_constexpr_body_invalid_stmt)
1079 << isa<CXXConstructorDecl>(Dcl);
1080
Richard Smith9f569cc2011-10-01 02:31:28 +00001081 if (const CXXConstructorDecl *Constructor
1082 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1083 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001084 // DR1359:
1085 // - every non-variant non-static data member and base class sub-object
1086 // shall be initialized;
1087 // - if the class is a non-empty union, or for each non-empty anonymous
1088 // union member of a non-union class, exactly one non-static data member
1089 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001090 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001091 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001092 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1093 return false;
1094 }
Richard Smith6e433752011-10-10 16:38:04 +00001095 } else if (!Constructor->isDependentContext() &&
1096 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001097 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1098
1099 // Skip detailed checking if we have enough initializers, and we would
1100 // allow at most one initializer per member.
1101 bool AnyAnonStructUnionMembers = false;
1102 unsigned Fields = 0;
1103 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1104 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001105 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001106 AnyAnonStructUnionMembers = true;
1107 break;
1108 }
1109 }
1110 if (AnyAnonStructUnionMembers ||
1111 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1112 // Check initialization of non-static data members. Base classes are
1113 // always initialized so do not need to be checked. Dependent bases
1114 // might not have initializers in the member initializer list.
1115 llvm::SmallSet<Decl*, 16> Inits;
1116 for (CXXConstructorDecl::init_const_iterator
1117 I = Constructor->init_begin(), E = Constructor->init_end();
1118 I != E; ++I) {
1119 if (FieldDecl *FD = (*I)->getMember())
1120 Inits.insert(FD);
1121 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1122 Inits.insert(ID->chain_begin(), ID->chain_end());
1123 }
1124
1125 bool Diagnosed = false;
1126 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1127 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001128 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001129 if (Diagnosed)
1130 return false;
1131 }
1132 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001133 } else {
1134 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001135 // C++1y doesn't require constexpr functions to contain a 'return'
1136 // statement. We still do, unless the return type is void, because
1137 // otherwise if there's no return statement, the function cannot
1138 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001139 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001140 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001141 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1142 : diag::err_constexpr_body_no_return);
1143 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001144 }
1145 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001146 Diag(ReturnStmts.back(),
1147 getLangOpts().CPlusPlus1y
1148 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1149 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001150 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1151 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001152 }
1153 }
1154
Richard Smith5ba73e12012-02-04 00:33:54 +00001155 // C++11 [dcl.constexpr]p5:
1156 // if no function argument values exist such that the function invocation
1157 // substitution would produce a constant expression, the program is
1158 // ill-formed; no diagnostic required.
1159 // C++11 [dcl.constexpr]p3:
1160 // - every constructor call and implicit conversion used in initializing the
1161 // return value shall be one of those allowed in a constant expression.
1162 // C++11 [dcl.constexpr]p4:
1163 // - every constructor involved in initializing non-static data members and
1164 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001165 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001166 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001167 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001168 << isa<CXXConstructorDecl>(Dcl);
1169 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1170 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001171 // Don't return false here: we allow this for compatibility in
1172 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001173 }
1174
Richard Smith9f569cc2011-10-01 02:31:28 +00001175 return true;
1176}
1177
Douglas Gregorb48fe382008-10-31 09:07:45 +00001178/// isCurrentClassName - Determine whether the identifier II is the
1179/// name of the class type currently being defined. In the case of
1180/// nested classes, this will only return true if II is the name of
1181/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001182bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1183 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001184 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001185
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001186 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001187 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001188 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001189 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1190 } else
1191 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1192
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001193 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001194 return &II == CurDecl->getIdentifier();
1195 else
1196 return false;
1197}
1198
Douglas Gregor229d47a2012-11-10 07:24:09 +00001199/// \brief Determine whether the given class is a base class of the given
1200/// class, including looking at dependent bases.
1201static bool findCircularInheritance(const CXXRecordDecl *Class,
1202 const CXXRecordDecl *Current) {
1203 SmallVector<const CXXRecordDecl*, 8> Queue;
1204
1205 Class = Class->getCanonicalDecl();
1206 while (true) {
1207 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1208 E = Current->bases_end();
1209 I != E; ++I) {
1210 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1211 if (!Base)
1212 continue;
1213
1214 Base = Base->getDefinition();
1215 if (!Base)
1216 continue;
1217
1218 if (Base->getCanonicalDecl() == Class)
1219 return true;
1220
1221 Queue.push_back(Base);
1222 }
1223
1224 if (Queue.empty())
1225 return false;
1226
1227 Current = Queue.back();
1228 Queue.pop_back();
1229 }
1230
1231 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001232}
1233
Mike Stump1eb44332009-09-09 15:08:12 +00001234/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001235///
1236/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1237/// and returns NULL otherwise.
1238CXXBaseSpecifier *
1239Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1240 SourceRange SpecifierRange,
1241 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001242 TypeSourceInfo *TInfo,
1243 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001244 QualType BaseType = TInfo->getType();
1245
Douglas Gregor2943aed2009-03-03 04:44:36 +00001246 // C++ [class.union]p1:
1247 // A union shall not have base classes.
1248 if (Class->isUnion()) {
1249 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1250 << SpecifierRange;
1251 return 0;
1252 }
1253
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001254 if (EllipsisLoc.isValid() &&
1255 !TInfo->getType()->containsUnexpandedParameterPack()) {
1256 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1257 << TInfo->getTypeLoc().getSourceRange();
1258 EllipsisLoc = SourceLocation();
1259 }
Douglas Gregord777e282012-11-10 01:18:17 +00001260
1261 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1262
1263 if (BaseType->isDependentType()) {
1264 // Make sure that we don't have circular inheritance among our dependent
1265 // bases. For non-dependent bases, the check for completeness below handles
1266 // this.
1267 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1268 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1269 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001270 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001271 Diag(BaseLoc, diag::err_circular_inheritance)
1272 << BaseType << Context.getTypeDeclType(Class);
1273
1274 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1275 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1276 << BaseType;
1277
1278 return 0;
1279 }
1280 }
1281
Mike Stump1eb44332009-09-09 15:08:12 +00001282 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001283 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001284 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001285 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001286
1287 // Base specifiers must be record types.
1288 if (!BaseType->isRecordType()) {
1289 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1290 return 0;
1291 }
1292
1293 // C++ [class.union]p1:
1294 // A union shall not be used as a base class.
1295 if (BaseType->isUnionType()) {
1296 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1297 return 0;
1298 }
1299
1300 // C++ [class.derived]p2:
1301 // The class-name in a base-specifier shall not be an incompletely
1302 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001303 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001304 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001305 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001306 return 0;
John McCall572fc622010-08-17 07:23:57 +00001307 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001308
Eli Friedman1d954f62009-08-15 21:55:26 +00001309 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001310 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001311 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001312 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001313 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001314 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1315 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001316
Anders Carlsson1d209272011-03-25 14:55:14 +00001317 // C++ [class]p3:
1318 // If a class is marked final and it appears as a base-type-specifier in
1319 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001320 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001321 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1322 << CXXBaseDecl->getDeclName();
1323 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1324 << CXXBaseDecl->getDeclName();
1325 return 0;
1326 }
1327
John McCall572fc622010-08-17 07:23:57 +00001328 if (BaseDecl->isInvalidDecl())
1329 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001330
1331 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001332 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001333 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001334 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001335}
1336
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001337/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1338/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001339/// example:
1340/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001341/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001342BaseResult
John McCalld226f652010-08-21 09:40:31 +00001343Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001344 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001345 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001346 ParsedType basetype, SourceLocation BaseLoc,
1347 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001348 if (!classdecl)
1349 return true;
1350
Douglas Gregor40808ce2009-03-09 23:48:35 +00001351 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001352 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001353 if (!Class)
1354 return true;
1355
Richard Smith05321402013-02-19 23:47:15 +00001356 // We do not support any C++11 attributes on base-specifiers yet.
1357 // Diagnose any attributes we see.
1358 if (!Attributes.empty()) {
1359 for (AttributeList *Attr = Attributes.getList(); Attr;
1360 Attr = Attr->getNext()) {
1361 if (Attr->isInvalid() ||
1362 Attr->getKind() == AttributeList::IgnoredAttribute)
1363 continue;
1364 Diag(Attr->getLoc(),
1365 Attr->getKind() == AttributeList::UnknownAttribute
1366 ? diag::warn_unknown_attribute_ignored
1367 : diag::err_base_specifier_attribute)
1368 << Attr->getName();
1369 }
1370 }
1371
Nick Lewycky56062202010-07-26 16:56:01 +00001372 TypeSourceInfo *TInfo = 0;
1373 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001374
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001375 if (EllipsisLoc.isInvalid() &&
1376 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001377 UPPC_BaseType))
1378 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001379
Douglas Gregor2943aed2009-03-03 04:44:36 +00001380 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001381 Virtual, Access, TInfo,
1382 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001383 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001384 else
1385 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Douglas Gregor2943aed2009-03-03 04:44:36 +00001387 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001388}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001389
Douglas Gregor2943aed2009-03-03 04:44:36 +00001390/// \brief Performs the actual work of attaching the given base class
1391/// specifiers to a C++ class.
1392bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1393 unsigned NumBases) {
1394 if (NumBases == 0)
1395 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001396
1397 // Used to keep track of which base types we have already seen, so
1398 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001399 // that the key is always the unqualified canonical type of the base
1400 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001401 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1402
1403 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001404 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001405 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001406 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001407 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001408 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001409 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001410
1411 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1412 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001413 // C++ [class.mi]p3:
1414 // A class shall not be specified as a direct base class of a
1415 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001416 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001417 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001418 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001419 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001420
1421 // Delete the duplicate base class specifier; we're going to
1422 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001423 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001424
1425 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001426 } else {
1427 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001428 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001429 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001430 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1431 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1432 if (Class->isInterface() &&
1433 (!RD->isInterface() ||
1434 KnownBase->getAccessSpecifier() != AS_public)) {
1435 // The Microsoft extension __interface does not permit bases that
1436 // are not themselves public interfaces.
1437 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1438 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1439 << RD->getSourceRange();
1440 Invalid = true;
1441 }
1442 if (RD->hasAttr<WeakAttr>())
1443 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1444 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001445 }
1446 }
1447
1448 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001449 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001450
1451 // Delete the remaining (good) base class specifiers, since their
1452 // data has been copied into the CXXRecordDecl.
1453 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001454 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001455
1456 return Invalid;
1457}
1458
1459/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1460/// class, after checking whether there are any duplicate base
1461/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001462void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001463 unsigned NumBases) {
1464 if (!ClassDecl || !Bases || !NumBases)
1465 return;
1466
1467 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001468 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001469 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001470}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001471
Douglas Gregora8f32e02009-10-06 17:59:45 +00001472/// \brief Determine whether the type \p Derived is a C++ class that is
1473/// derived from the type \p Base.
1474bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001475 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001476 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001477
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001478 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001479 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001480 return false;
1481
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001482 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001483 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001484 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001485
1486 // If either the base or the derived type is invalid, don't try to
1487 // check whether one is derived from the other.
1488 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1489 return false;
1490
John McCall86ff3082010-02-04 22:26:26 +00001491 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1492 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001493}
1494
1495/// \brief Determine whether the type \p Derived is a C++ class that is
1496/// derived from the type \p Base.
1497bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001498 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001499 return false;
1500
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001501 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001502 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001503 return false;
1504
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001505 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001506 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001507 return false;
1508
Douglas Gregora8f32e02009-10-06 17:59:45 +00001509 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1510}
1511
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001512void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001513 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001514 assert(BasePathArray.empty() && "Base path array must be empty!");
1515 assert(Paths.isRecordingPaths() && "Must record paths!");
1516
1517 const CXXBasePath &Path = Paths.front();
1518
1519 // We first go backward and check if we have a virtual base.
1520 // FIXME: It would be better if CXXBasePath had the base specifier for
1521 // the nearest virtual base.
1522 unsigned Start = 0;
1523 for (unsigned I = Path.size(); I != 0; --I) {
1524 if (Path[I - 1].Base->isVirtual()) {
1525 Start = I - 1;
1526 break;
1527 }
1528 }
1529
1530 // Now add all bases.
1531 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001532 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001533}
1534
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001535/// \brief Determine whether the given base path includes a virtual
1536/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001537bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1538 for (CXXCastPath::const_iterator B = BasePath.begin(),
1539 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001540 B != BEnd; ++B)
1541 if ((*B)->isVirtual())
1542 return true;
1543
1544 return false;
1545}
1546
Douglas Gregora8f32e02009-10-06 17:59:45 +00001547/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1548/// conversion (where Derived and Base are class types) is
1549/// well-formed, meaning that the conversion is unambiguous (and
1550/// that all of the base classes are accessible). Returns true
1551/// and emits a diagnostic if the code is ill-formed, returns false
1552/// otherwise. Loc is the location where this routine should point to
1553/// if there is an error, and Range is the source range to highlight
1554/// if there is an error.
1555bool
1556Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001557 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001558 unsigned AmbigiousBaseConvID,
1559 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001560 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001561 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001562 // First, determine whether the path from Derived to Base is
1563 // ambiguous. This is slightly more expensive than checking whether
1564 // the Derived to Base conversion exists, because here we need to
1565 // explore multiple paths to determine if there is an ambiguity.
1566 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1567 /*DetectVirtual=*/false);
1568 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1569 assert(DerivationOkay &&
1570 "Can only be used with a derived-to-base conversion");
1571 (void)DerivationOkay;
1572
1573 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001574 if (InaccessibleBaseID) {
1575 // Check that the base class can be accessed.
1576 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1577 InaccessibleBaseID)) {
1578 case AR_inaccessible:
1579 return true;
1580 case AR_accessible:
1581 case AR_dependent:
1582 case AR_delayed:
1583 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001584 }
John McCall6b2accb2010-02-10 09:31:12 +00001585 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001586
1587 // Build a base path if necessary.
1588 if (BasePath)
1589 BuildBasePathArray(Paths, *BasePath);
1590 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001591 }
1592
1593 // We know that the derived-to-base conversion is ambiguous, and
1594 // we're going to produce a diagnostic. Perform the derived-to-base
1595 // search just one more time to compute all of the possible paths so
1596 // that we can print them out. This is more expensive than any of
1597 // the previous derived-to-base checks we've done, but at this point
1598 // performance isn't as much of an issue.
1599 Paths.clear();
1600 Paths.setRecordingPaths(true);
1601 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1602 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1603 (void)StillOkay;
1604
1605 // Build up a textual representation of the ambiguous paths, e.g.,
1606 // D -> B -> A, that will be used to illustrate the ambiguous
1607 // conversions in the diagnostic. We only print one of the paths
1608 // to each base class subobject.
1609 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1610
1611 Diag(Loc, AmbigiousBaseConvID)
1612 << Derived << Base << PathDisplayStr << Range << Name;
1613 return true;
1614}
1615
1616bool
1617Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001618 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001619 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001620 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001621 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001622 IgnoreAccess ? 0
1623 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001624 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001625 Loc, Range, DeclarationName(),
1626 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001627}
1628
1629
1630/// @brief Builds a string representing ambiguous paths from a
1631/// specific derived class to different subobjects of the same base
1632/// class.
1633///
1634/// This function builds a string that can be used in error messages
1635/// to show the different paths that one can take through the
1636/// inheritance hierarchy to go from the derived class to different
1637/// subobjects of a base class. The result looks something like this:
1638/// @code
1639/// struct D -> struct B -> struct A
1640/// struct D -> struct C -> struct A
1641/// @endcode
1642std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1643 std::string PathDisplayStr;
1644 std::set<unsigned> DisplayedPaths;
1645 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1646 Path != Paths.end(); ++Path) {
1647 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1648 // We haven't displayed a path to this particular base
1649 // class subobject yet.
1650 PathDisplayStr += "\n ";
1651 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1652 for (CXXBasePath::const_iterator Element = Path->begin();
1653 Element != Path->end(); ++Element)
1654 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1655 }
1656 }
1657
1658 return PathDisplayStr;
1659}
1660
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001661//===----------------------------------------------------------------------===//
1662// C++ class member Handling
1663//===----------------------------------------------------------------------===//
1664
Abramo Bagnara6206d532010-06-05 05:09:32 +00001665/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001666bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1667 SourceLocation ASLoc,
1668 SourceLocation ColonLoc,
1669 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001670 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001671 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001672 ASLoc, ColonLoc);
1673 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001674 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001675}
1676
Richard Smitha4b39652012-08-06 03:25:17 +00001677/// CheckOverrideControl - Check C++11 override control semantics.
1678void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001679 if (D->isInvalidDecl())
1680 return;
1681
Chris Lattner5f9e2722011-07-23 10:55:15 +00001682 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001683
Richard Smitha4b39652012-08-06 03:25:17 +00001684 // Do we know which functions this declaration might be overriding?
1685 bool OverridesAreKnown = !MD ||
1686 (!MD->getParent()->hasAnyDependentBases() &&
1687 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001688
Richard Smitha4b39652012-08-06 03:25:17 +00001689 if (!MD || !MD->isVirtual()) {
1690 if (OverridesAreKnown) {
1691 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1692 Diag(OA->getLocation(),
1693 diag::override_keyword_only_allowed_on_virtual_member_functions)
1694 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1695 D->dropAttr<OverrideAttr>();
1696 }
1697 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1698 Diag(FA->getLocation(),
1699 diag::override_keyword_only_allowed_on_virtual_member_functions)
1700 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1701 D->dropAttr<FinalAttr>();
1702 }
1703 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001704 return;
1705 }
Richard Smitha4b39652012-08-06 03:25:17 +00001706
1707 if (!OverridesAreKnown)
1708 return;
1709
1710 // C++11 [class.virtual]p5:
1711 // If a virtual function is marked with the virt-specifier override and
1712 // does not override a member function of a base class, the program is
1713 // ill-formed.
1714 bool HasOverriddenMethods =
1715 MD->begin_overridden_methods() != MD->end_overridden_methods();
1716 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1717 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1718 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001719}
1720
Richard Smitha4b39652012-08-06 03:25:17 +00001721/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001722/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001723/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001724bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1725 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001726 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001727 return false;
1728
1729 Diag(New->getLocation(), diag::err_final_function_overridden)
1730 << New->getDeclName();
1731 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1732 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001733}
1734
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001735static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001736 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1737 // FIXME: Destruction of ObjC lifetime types has side-effects.
1738 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1739 return !RD->isCompleteDefinition() ||
1740 !RD->hasTrivialDefaultConstructor() ||
1741 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001742 return false;
1743}
1744
John McCall76da55d2013-04-16 07:28:30 +00001745static AttributeList *getMSPropertyAttr(AttributeList *list) {
1746 for (AttributeList* it = list; it != 0; it = it->getNext())
1747 if (it->isDeclspecPropertyAttribute())
1748 return it;
1749 return 0;
1750}
1751
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001752/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1753/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001754/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001755/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1756/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001757NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001758Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001759 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001760 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001761 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001762 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001763 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1764 DeclarationName Name = NameInfo.getName();
1765 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001766
1767 // For anonymous bitfields, the location should point to the type.
1768 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001769 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001770
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001771 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001772
John McCall4bde1e12010-06-04 08:34:12 +00001773 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001774 assert(!DS.isFriendSpecified());
1775
Richard Smith1ab0d902011-06-25 02:28:38 +00001776 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001777
John McCalle402e722012-09-25 07:32:39 +00001778 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1779 // The Microsoft extension __interface only permits public member functions
1780 // and prohibits constructors, destructors, operators, non-public member
1781 // functions, static methods and data members.
1782 unsigned InvalidDecl;
1783 bool ShowDeclName = true;
1784 if (!isFunc)
1785 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1786 else if (AS != AS_public)
1787 InvalidDecl = 2;
1788 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1789 InvalidDecl = 3;
1790 else switch (Name.getNameKind()) {
1791 case DeclarationName::CXXConstructorName:
1792 InvalidDecl = 4;
1793 ShowDeclName = false;
1794 break;
1795
1796 case DeclarationName::CXXDestructorName:
1797 InvalidDecl = 5;
1798 ShowDeclName = false;
1799 break;
1800
1801 case DeclarationName::CXXOperatorName:
1802 case DeclarationName::CXXConversionFunctionName:
1803 InvalidDecl = 6;
1804 break;
1805
1806 default:
1807 InvalidDecl = 0;
1808 break;
1809 }
1810
1811 if (InvalidDecl) {
1812 if (ShowDeclName)
1813 Diag(Loc, diag::err_invalid_member_in_interface)
1814 << (InvalidDecl-1) << Name;
1815 else
1816 Diag(Loc, diag::err_invalid_member_in_interface)
1817 << (InvalidDecl-1) << "";
1818 return 0;
1819 }
1820 }
1821
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001822 // C++ 9.2p6: A member shall not be declared to have automatic storage
1823 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001824 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1825 // data members and cannot be applied to names declared const or static,
1826 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001827 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001828 case DeclSpec::SCS_unspecified:
1829 case DeclSpec::SCS_typedef:
1830 case DeclSpec::SCS_static:
1831 break;
1832 case DeclSpec::SCS_mutable:
1833 if (isFunc) {
1834 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001835
Richard Smithec642442013-04-12 22:46:28 +00001836 // FIXME: It would be nicer if the keyword was ignored only for this
1837 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001838 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001839 }
1840 break;
1841 default:
1842 Diag(DS.getStorageClassSpecLoc(),
1843 diag::err_storageclass_invalid_for_member);
1844 D.getMutableDeclSpec().ClearStorageClassSpecs();
1845 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001846 }
1847
Sebastian Redl669d5d72008-11-14 23:42:31 +00001848 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1849 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001850 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001851
David Blaikie1d87fba2013-01-30 01:22:18 +00001852 if (DS.isConstexprSpecified() && isInstField) {
1853 SemaDiagnosticBuilder B =
1854 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1855 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1856 if (InitStyle == ICIS_NoInit) {
1857 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1858 D.getMutableDeclSpec().ClearConstexprSpec();
1859 const char *PrevSpec;
1860 unsigned DiagID;
1861 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1862 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001863 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001864 assert(!Failed && "Making a constexpr member const shouldn't fail");
1865 } else {
1866 B << 1;
1867 const char *PrevSpec;
1868 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001869 if (D.getMutableDeclSpec().SetStorageClassSpec(
1870 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001871 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001872 "This is the only DeclSpec that should fail to be applied");
1873 B << 1;
1874 } else {
1875 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1876 isInstField = false;
1877 }
1878 }
1879 }
1880
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001881 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001882 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001883 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001884
1885 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001886 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001887 Diag(Loc, diag::err_bad_variable_name)
1888 << Name;
1889 return 0;
1890 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001891
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001892 IdentifierInfo *II = Name.getAsIdentifierInfo();
1893
Douglas Gregorf2503652011-09-21 14:40:46 +00001894 // Member field could not be with "template" keyword.
1895 // So TemplateParameterLists should be empty in this case.
1896 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001897 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001898 if (TemplateParams->size()) {
1899 // There is no such thing as a member field template.
1900 Diag(D.getIdentifierLoc(), diag::err_template_member)
1901 << II
1902 << SourceRange(TemplateParams->getTemplateLoc(),
1903 TemplateParams->getRAngleLoc());
1904 } else {
1905 // There is an extraneous 'template<>' for this member.
1906 Diag(TemplateParams->getTemplateLoc(),
1907 diag::err_template_member_noparams)
1908 << II
1909 << SourceRange(TemplateParams->getTemplateLoc(),
1910 TemplateParams->getRAngleLoc());
1911 }
1912 return 0;
1913 }
1914
Douglas Gregor922fff22010-10-13 22:19:53 +00001915 if (SS.isSet() && !SS.isInvalid()) {
1916 // The user provided a superfluous scope specifier inside a class
1917 // definition:
1918 //
1919 // class X {
1920 // int X::member;
1921 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001922 if (DeclContext *DC = computeDeclContext(SS, false))
1923 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001924 else
1925 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1926 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001927
Douglas Gregor922fff22010-10-13 22:19:53 +00001928 SS.clear();
1929 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001930
John McCall76da55d2013-04-16 07:28:30 +00001931 AttributeList *MSPropertyAttr =
1932 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1933 if (MSPropertyAttr) {
1934 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1935 BitWidth, InitStyle, AS, MSPropertyAttr);
1936 isInstField = false;
1937 } else {
1938 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1939 BitWidth, InitStyle, AS);
1940 }
Chris Lattner6f8ce142009-03-05 23:03:49 +00001941 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001942 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001943 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001944
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001945 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001946 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001947 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001948 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001949
1950 // Non-instance-fields can't have a bitfield.
1951 if (BitWidth) {
1952 if (Member->isInvalidDecl()) {
1953 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001954 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001955 // C++ 9.6p3: A bit-field shall not be a static member.
1956 // "static member 'A' cannot be a bit-field"
1957 Diag(Loc, diag::err_static_not_bitfield)
1958 << Name << BitWidth->getSourceRange();
1959 } else if (isa<TypedefDecl>(Member)) {
1960 // "typedef member 'x' cannot be a bit-field"
1961 Diag(Loc, diag::err_typedef_not_bitfield)
1962 << Name << BitWidth->getSourceRange();
1963 } else {
1964 // A function typedef ("typedef int f(); f a;").
1965 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1966 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001967 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001968 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001969 }
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Chris Lattner8b963ef2009-03-05 23:01:03 +00001971 BitWidth = 0;
1972 Member->setInvalidDecl();
1973 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001974
1975 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Douglas Gregor37b372b2009-08-20 22:52:58 +00001977 // If we have declared a member function template, set the access of the
1978 // templated declaration as well.
1979 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1980 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001981 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001982
Richard Smitha4b39652012-08-06 03:25:17 +00001983 if (VS.isOverrideSpecified())
1984 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1985 if (VS.isFinalSpecified())
1986 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001987
Douglas Gregorf5251602011-03-08 17:10:18 +00001988 if (VS.getLastLocation().isValid()) {
1989 // Update the end location of a method that has a virt-specifiers.
1990 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1991 MD->setRangeEnd(VS.getLastLocation());
1992 }
Richard Smitha4b39652012-08-06 03:25:17 +00001993
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001994 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001995
Douglas Gregor10bd3682008-11-17 22:58:34 +00001996 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001997
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001998 if (isInstField) {
1999 FieldDecl *FD = cast<FieldDecl>(Member);
2000 FieldCollector->Add(FD);
2001
2002 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2003 FD->getLocation())
2004 != DiagnosticsEngine::Ignored) {
2005 // Remember all explicit private FieldDecls that have a name, no side
2006 // effects and are not part of a dependent type declaration.
2007 if (!FD->isImplicit() && FD->getDeclName() &&
2008 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002009 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002010 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002011 !InitializationHasSideEffects(*FD))
2012 UnusedPrivateFields.insert(FD);
2013 }
2014 }
2015
John McCalld226f652010-08-21 09:40:31 +00002016 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002017}
2018
Hans Wennborg471f9852012-09-18 15:58:06 +00002019namespace {
2020 class UninitializedFieldVisitor
2021 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2022 Sema &S;
2023 ValueDecl *VD;
2024 public:
2025 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2026 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002027 S(S) {
2028 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2029 this->VD = IFD->getAnonField();
2030 else
2031 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002032 }
2033
2034 void HandleExpr(Expr *E) {
2035 if (!E) return;
2036
2037 // Expressions like x(x) sometimes lack the surrounding expressions
2038 // but need to be checked anyways.
2039 HandleValue(E);
2040 Visit(E);
2041 }
2042
2043 void HandleValue(Expr *E) {
2044 E = E->IgnoreParens();
2045
2046 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2047 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002048 return;
2049
2050 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2051 // or union.
2052 MemberExpr *FieldME = ME;
2053
Hans Wennborg471f9852012-09-18 15:58:06 +00002054 Expr *Base = E;
2055 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002056 ME = cast<MemberExpr>(Base);
2057
2058 if (isa<VarDecl>(ME->getMemberDecl()))
2059 return;
2060
2061 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2062 if (!FD->isAnonymousStructOrUnion())
2063 FieldME = ME;
2064
Hans Wennborg471f9852012-09-18 15:58:06 +00002065 Base = ME->getBase();
2066 }
2067
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002068 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00002069 unsigned diag = VD->getType()->isReferenceType()
2070 ? diag::warn_reference_field_is_uninit
2071 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002072 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002073 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002074 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002075 }
2076
2077 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2078 HandleValue(CO->getTrueExpr());
2079 HandleValue(CO->getFalseExpr());
2080 return;
2081 }
2082
2083 if (BinaryConditionalOperator *BCO =
2084 dyn_cast<BinaryConditionalOperator>(E)) {
2085 HandleValue(BCO->getCommon());
2086 HandleValue(BCO->getFalseExpr());
2087 return;
2088 }
2089
2090 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2091 switch (BO->getOpcode()) {
2092 default:
2093 return;
2094 case(BO_PtrMemD):
2095 case(BO_PtrMemI):
2096 HandleValue(BO->getLHS());
2097 return;
2098 case(BO_Comma):
2099 HandleValue(BO->getRHS());
2100 return;
2101 }
2102 }
2103 }
2104
2105 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2106 if (E->getCastKind() == CK_LValueToRValue)
2107 HandleValue(E->getSubExpr());
2108
2109 Inherited::VisitImplicitCastExpr(E);
2110 }
2111
2112 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2113 Expr *Callee = E->getCallee();
2114 if (isa<MemberExpr>(Callee))
2115 HandleValue(Callee);
2116
2117 Inherited::VisitCXXMemberCallExpr(E);
2118 }
2119 };
2120 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2121 ValueDecl *VD) {
2122 UninitializedFieldVisitor(S, VD).HandleExpr(E);
2123 }
2124} // namespace
2125
Richard Smith7a614d82011-06-11 17:19:42 +00002126/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002127/// in-class initializer for a non-static C++ class member, and after
2128/// instantiating an in-class initializer in a class template. Such actions
2129/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002130void
Richard Smithca523302012-06-10 03:12:00 +00002131Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002132 Expr *InitExpr) {
2133 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002134 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2135 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002136
2137 if (!InitExpr) {
2138 FD->setInvalidDecl();
2139 FD->removeInClassInitializer();
2140 return;
2141 }
2142
Peter Collingbournefef21892011-10-23 18:59:44 +00002143 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2144 FD->setInvalidDecl();
2145 FD->removeInClassInitializer();
2146 return;
2147 }
2148
Hans Wennborg471f9852012-09-18 15:58:06 +00002149 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2150 != DiagnosticsEngine::Ignored) {
2151 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2152 }
2153
Richard Smith7a614d82011-06-11 17:19:42 +00002154 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002155 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00002156 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002157 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00002158 << /*at end of ctor*/1 << InitExpr->getSourceRange();
2159 }
Sebastian Redl33deb352012-02-22 10:50:08 +00002160 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002161 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002162 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002163 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002164 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2165 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002166 if (Init.isInvalid()) {
2167 FD->setInvalidDecl();
2168 return;
2169 }
Richard Smith7a614d82011-06-11 17:19:42 +00002170 }
2171
Richard Smith41956372013-01-14 22:39:08 +00002172 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002173 // The initialization of each base and member constitutes a
2174 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002175 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002176 if (Init.isInvalid()) {
2177 FD->setInvalidDecl();
2178 return;
2179 }
2180
2181 InitExpr = Init.release();
2182
2183 FD->setInClassInitializer(InitExpr);
2184}
2185
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002186/// \brief Find the direct and/or virtual base specifiers that
2187/// correspond to the given base type, for use in base initialization
2188/// within a constructor.
2189static bool FindBaseInitializer(Sema &SemaRef,
2190 CXXRecordDecl *ClassDecl,
2191 QualType BaseType,
2192 const CXXBaseSpecifier *&DirectBaseSpec,
2193 const CXXBaseSpecifier *&VirtualBaseSpec) {
2194 // First, check for a direct base class.
2195 DirectBaseSpec = 0;
2196 for (CXXRecordDecl::base_class_const_iterator Base
2197 = ClassDecl->bases_begin();
2198 Base != ClassDecl->bases_end(); ++Base) {
2199 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2200 // We found a direct base of this type. That's what we're
2201 // initializing.
2202 DirectBaseSpec = &*Base;
2203 break;
2204 }
2205 }
2206
2207 // Check for a virtual base class.
2208 // FIXME: We might be able to short-circuit this if we know in advance that
2209 // there are no virtual bases.
2210 VirtualBaseSpec = 0;
2211 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2212 // We haven't found a base yet; search the class hierarchy for a
2213 // virtual base class.
2214 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2215 /*DetectVirtual=*/false);
2216 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2217 BaseType, Paths)) {
2218 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2219 Path != Paths.end(); ++Path) {
2220 if (Path->back().Base->isVirtual()) {
2221 VirtualBaseSpec = Path->back().Base;
2222 break;
2223 }
2224 }
2225 }
2226 }
2227
2228 return DirectBaseSpec || VirtualBaseSpec;
2229}
2230
Sebastian Redl6df65482011-09-24 17:48:25 +00002231/// \brief Handle a C++ member initializer using braced-init-list syntax.
2232MemInitResult
2233Sema::ActOnMemInitializer(Decl *ConstructorD,
2234 Scope *S,
2235 CXXScopeSpec &SS,
2236 IdentifierInfo *MemberOrBase,
2237 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002238 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002239 SourceLocation IdLoc,
2240 Expr *InitList,
2241 SourceLocation EllipsisLoc) {
2242 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002243 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002244 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002245}
2246
2247/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002248MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002249Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002250 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002251 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002252 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002253 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002254 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002255 SourceLocation IdLoc,
2256 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002257 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002258 SourceLocation RParenLoc,
2259 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002260 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2261 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002262 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002263 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002264 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002265}
2266
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002267namespace {
2268
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002269// Callback to only accept typo corrections that can be a valid C++ member
2270// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002271class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2272 public:
2273 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2274 : ClassDecl(ClassDecl) {}
2275
2276 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2277 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2278 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2279 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2280 else
2281 return isa<TypeDecl>(ND);
2282 }
2283 return false;
2284 }
2285
2286 private:
2287 CXXRecordDecl *ClassDecl;
2288};
2289
2290}
2291
Sebastian Redl6df65482011-09-24 17:48:25 +00002292/// \brief Handle a C++ member initializer.
2293MemInitResult
2294Sema::BuildMemInitializer(Decl *ConstructorD,
2295 Scope *S,
2296 CXXScopeSpec &SS,
2297 IdentifierInfo *MemberOrBase,
2298 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002299 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002300 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002301 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002302 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002303 if (!ConstructorD)
2304 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002305
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002306 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002307
2308 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002309 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002310 if (!Constructor) {
2311 // The user wrote a constructor initializer on a function that is
2312 // not a C++ constructor. Ignore the error for now, because we may
2313 // have more member initializers coming; we'll diagnose it just
2314 // once in ActOnMemInitializers.
2315 return true;
2316 }
2317
2318 CXXRecordDecl *ClassDecl = Constructor->getParent();
2319
2320 // C++ [class.base.init]p2:
2321 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002322 // constructor's class and, if not found in that scope, are looked
2323 // up in the scope containing the constructor's definition.
2324 // [Note: if the constructor's class contains a member with the
2325 // same name as a direct or virtual base class of the class, a
2326 // mem-initializer-id naming the member or base class and composed
2327 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002328 // mem-initializer-id for the hidden base class may be specified
2329 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002330 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002331 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002332 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002333 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002334 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002335 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002336 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2337 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002338 if (EllipsisLoc.isValid())
2339 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002340 << MemberOrBase
2341 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002342
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002343 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002344 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002345 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002346 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002347 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002348 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002349 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002350
2351 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002352 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002353 } else if (DS.getTypeSpecType() == TST_decltype) {
2354 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002355 } else {
2356 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2357 LookupParsedName(R, S, &SS);
2358
2359 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2360 if (!TyD) {
2361 if (R.isAmbiguous()) return true;
2362
John McCallfd225442010-04-09 19:01:14 +00002363 // We don't want access-control diagnostics here.
2364 R.suppressDiagnostics();
2365
Douglas Gregor7a886e12010-01-19 06:46:48 +00002366 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2367 bool NotUnknownSpecialization = false;
2368 DeclContext *DC = computeDeclContext(SS, false);
2369 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2370 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2371
2372 if (!NotUnknownSpecialization) {
2373 // When the scope specifier can refer to a member of an unknown
2374 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002375 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2376 SS.getWithLocInContext(Context),
2377 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002378 if (BaseType.isNull())
2379 return true;
2380
Douglas Gregor7a886e12010-01-19 06:46:48 +00002381 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002382 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002383 }
2384 }
2385
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002386 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002387 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002388 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002389 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002390 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002391 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002392 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2393 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002394 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002395 // We have found a non-static data member with a similar
2396 // name to what was typed; complain and initialize that
2397 // member.
2398 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2399 << MemberOrBase << true << CorrectedQuotedStr
2400 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2401 Diag(Member->getLocation(), diag::note_previous_decl)
2402 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002403
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002404 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002405 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002406 const CXXBaseSpecifier *DirectBaseSpec;
2407 const CXXBaseSpecifier *VirtualBaseSpec;
2408 if (FindBaseInitializer(*this, ClassDecl,
2409 Context.getTypeDeclType(Type),
2410 DirectBaseSpec, VirtualBaseSpec)) {
2411 // We have found a direct or virtual base class with a
2412 // similar name to what was typed; complain and initialize
2413 // that base class.
2414 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002415 << MemberOrBase << false << CorrectedQuotedStr
2416 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002417
2418 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2419 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002420 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002421 diag::note_base_class_specified_here)
2422 << BaseSpec->getType()
2423 << BaseSpec->getSourceRange();
2424
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002425 TyD = Type;
2426 }
2427 }
2428 }
2429
Douglas Gregor7a886e12010-01-19 06:46:48 +00002430 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002431 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002432 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002433 return true;
2434 }
John McCall2b194412009-12-21 10:41:20 +00002435 }
2436
Douglas Gregor7a886e12010-01-19 06:46:48 +00002437 if (BaseType.isNull()) {
2438 BaseType = Context.getTypeDeclType(TyD);
2439 if (SS.isSet()) {
2440 NestedNameSpecifier *Qualifier =
2441 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002442
Douglas Gregor7a886e12010-01-19 06:46:48 +00002443 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002444 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002445 }
John McCall2b194412009-12-21 10:41:20 +00002446 }
2447 }
Mike Stump1eb44332009-09-09 15:08:12 +00002448
John McCalla93c9342009-12-07 02:54:59 +00002449 if (!TInfo)
2450 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002451
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002452 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002453}
2454
Chandler Carruth81c64772011-09-03 01:14:15 +00002455/// Checks a member initializer expression for cases where reference (or
2456/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002457static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2458 Expr *Init,
2459 SourceLocation IdLoc) {
2460 QualType MemberTy = Member->getType();
2461
2462 // We only handle pointers and references currently.
2463 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2464 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2465 return;
2466
2467 const bool IsPointer = MemberTy->isPointerType();
2468 if (IsPointer) {
2469 if (const UnaryOperator *Op
2470 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2471 // The only case we're worried about with pointers requires taking the
2472 // address.
2473 if (Op->getOpcode() != UO_AddrOf)
2474 return;
2475
2476 Init = Op->getSubExpr();
2477 } else {
2478 // We only handle address-of expression initializers for pointers.
2479 return;
2480 }
2481 }
2482
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002483 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2484 // Taking the address of a temporary will be diagnosed as a hard error.
2485 if (IsPointer)
2486 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002487
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002488 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2489 << Member << Init->getSourceRange();
2490 } else if (const DeclRefExpr *DRE
2491 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2492 // We only warn when referring to a non-reference parameter declaration.
2493 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2494 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002495 return;
2496
2497 S.Diag(Init->getExprLoc(),
2498 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2499 : diag::warn_bind_ref_member_to_parameter)
2500 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002501 } else {
2502 // Other initializers are fine.
2503 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002504 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002505
2506 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2507 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002508}
2509
John McCallf312b1e2010-08-26 23:41:50 +00002510MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002511Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002512 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002513 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2514 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2515 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002516 "Member must be a FieldDecl or IndirectFieldDecl");
2517
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002518 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002519 return true;
2520
Douglas Gregor464b2f02010-11-05 22:21:31 +00002521 if (Member->isInvalidDecl())
2522 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002523
John McCallb4190042009-11-04 23:02:40 +00002524 // Diagnose value-uses of fields to initialize themselves, e.g.
2525 // foo(foo)
2526 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002527 // TODO: implement -Wuninitialized and fold this into that framework.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002528 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002529 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002530 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002531 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002532 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002533 } else {
2534 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002535 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002536 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002537
Richard Trieude5e75c2012-06-14 23:11:34 +00002538 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2539 != DiagnosticsEngine::Ignored)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002540 for (unsigned i = 0, e = Args.size(); i != e; ++i)
Richard Trieude5e75c2012-06-14 23:11:34 +00002541 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002542 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002543 // initializing the i'th field, throw a warning if any of the >= i'th
2544 // fields are used, as they are not yet initialized.
2545 // Right now we are only handling the case where the i'th field uses
2546 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002547 // Also need to take into account that some fields may be initialized by
2548 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002549 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002550
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002551 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002552
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002553 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002554 // Can't check initialization for a member of dependent type or when
2555 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002556 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002557 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002558 bool InitList = false;
2559 if (isa<InitListExpr>(Init)) {
2560 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002561 Args = Init;
Sebastian Redl772291a2012-02-19 16:31:05 +00002562
2563 if (isStdInitializerList(Member->getType(), 0)) {
2564 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2565 << /*at end of ctor*/1 << InitRange;
2566 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002567 }
2568
Chandler Carruth894aed92010-12-06 09:23:57 +00002569 // Initialize the member.
2570 InitializedEntity MemberEntity =
2571 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2572 : InitializedEntity::InitializeMember(IndirectMember, 0);
2573 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002574 InitList ? InitializationKind::CreateDirectList(IdLoc)
2575 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2576 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002577
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002578 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2579 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002580 if (MemberInit.isInvalid())
2581 return true;
2582
Richard Smith41956372013-01-14 22:39:08 +00002583 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002584 // The initialization of each base and member constitutes a
2585 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002586 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002587 if (MemberInit.isInvalid())
2588 return true;
2589
Richard Smithc83c2302012-12-19 01:39:02 +00002590 Init = MemberInit.get();
2591 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002592 }
2593
Chandler Carruth894aed92010-12-06 09:23:57 +00002594 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002595 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2596 InitRange.getBegin(), Init,
2597 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002598 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002599 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2600 InitRange.getBegin(), Init,
2601 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002602 }
Eli Friedman59c04372009-07-29 19:44:27 +00002603}
2604
John McCallf312b1e2010-08-26 23:41:50 +00002605MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002606Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002607 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002608 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002609 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002610 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002611 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002612 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002613
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002614 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002615 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002616 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2617 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002618 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002619 }
2620
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002621 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002622 // Initialize the object.
2623 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2624 QualType(ClassDecl->getTypeForDecl(), 0));
2625 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002626 InitList ? InitializationKind::CreateDirectList(NameLoc)
2627 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2628 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002629 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002630 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002631 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002632 if (DelegationInit.isInvalid())
2633 return true;
2634
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002635 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2636 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002637
Richard Smith41956372013-01-14 22:39:08 +00002638 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002639 // The initialization of each base and member constitutes a
2640 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002641 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2642 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002643 if (DelegationInit.isInvalid())
2644 return true;
2645
Eli Friedmand21016f2012-05-19 23:35:23 +00002646 // If we are in a dependent context, template instantiation will
2647 // perform this type-checking again. Just save the arguments that we
2648 // received in a ParenListExpr.
2649 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2650 // of the information that we have about the base
2651 // initializer. However, deconstructing the ASTs is a dicey process,
2652 // and this approach is far more likely to get the corner cases right.
2653 if (CurContext->isDependentContext())
2654 DelegationInit = Owned(Init);
2655
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002656 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002657 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002658 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002659}
2660
2661MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002662Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002663 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002664 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002665 SourceLocation BaseLoc
2666 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002667
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002668 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2669 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2670 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2671
2672 // C++ [class.base.init]p2:
2673 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002674 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002675 // of that class, the mem-initializer is ill-formed. A
2676 // mem-initializer-list can initialize a base class using any
2677 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002678 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002679
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002680 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002681 if (EllipsisLoc.isValid()) {
2682 // This is a pack expansion.
2683 if (!BaseType->containsUnexpandedParameterPack()) {
2684 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002685 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002686
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002687 EllipsisLoc = SourceLocation();
2688 }
2689 } else {
2690 // Check for any unexpanded parameter packs.
2691 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2692 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002693
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002694 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002695 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002696 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002697
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002698 // Check for direct and virtual base classes.
2699 const CXXBaseSpecifier *DirectBaseSpec = 0;
2700 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2701 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002702 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2703 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002704 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002705
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002706 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2707 VirtualBaseSpec);
2708
2709 // C++ [base.class.init]p2:
2710 // Unless the mem-initializer-id names a nonstatic data member of the
2711 // constructor's class or a direct or virtual base of that class, the
2712 // mem-initializer is ill-formed.
2713 if (!DirectBaseSpec && !VirtualBaseSpec) {
2714 // If the class has any dependent bases, then it's possible that
2715 // one of those types will resolve to the same type as
2716 // BaseType. Therefore, just treat this as a dependent base
2717 // class initialization. FIXME: Should we try to check the
2718 // initialization anyway? It seems odd.
2719 if (ClassDecl->hasAnyDependentBases())
2720 Dependent = true;
2721 else
2722 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2723 << BaseType << Context.getTypeDeclType(ClassDecl)
2724 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2725 }
2726 }
2727
2728 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002729 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002730
Sebastian Redl6df65482011-09-24 17:48:25 +00002731 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2732 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002733 InitRange.getBegin(), Init,
2734 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002735 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002736
2737 // C++ [base.class.init]p2:
2738 // If a mem-initializer-id is ambiguous because it designates both
2739 // a direct non-virtual base class and an inherited virtual base
2740 // class, the mem-initializer is ill-formed.
2741 if (DirectBaseSpec && VirtualBaseSpec)
2742 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002743 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002744
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002745 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002746 if (!BaseSpec)
2747 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2748
2749 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002750 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002751 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002752 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002753 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002754 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002755 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002756
2757 InitializedEntity BaseEntity =
2758 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2759 InitializationKind Kind =
2760 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2761 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2762 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002763 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2764 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002765 if (BaseInit.isInvalid())
2766 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002767
Richard Smith41956372013-01-14 22:39:08 +00002768 // C++11 [class.base.init]p7:
2769 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002770 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002771 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002772 if (BaseInit.isInvalid())
2773 return true;
2774
2775 // If we are in a dependent context, template instantiation will
2776 // perform this type-checking again. Just save the arguments that we
2777 // received in a ParenListExpr.
2778 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2779 // of the information that we have about the base
2780 // initializer. However, deconstructing the ASTs is a dicey process,
2781 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002782 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002783 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002784
Sean Huntcbb67482011-01-08 20:30:50 +00002785 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002786 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002787 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002788 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002789 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002790}
2791
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002792// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002793static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2794 if (T.isNull()) T = E->getType();
2795 QualType TargetType = SemaRef.BuildReferenceType(
2796 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002797 SourceLocation ExprLoc = E->getLocStart();
2798 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2799 TargetType, ExprLoc);
2800
2801 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2802 SourceRange(ExprLoc, ExprLoc),
2803 E->getSourceRange()).take();
2804}
2805
Anders Carlssone5ef7402010-04-23 03:10:23 +00002806/// ImplicitInitializerKind - How an implicit base or member initializer should
2807/// initialize its base or member.
2808enum ImplicitInitializerKind {
2809 IIK_Default,
2810 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002811 IIK_Move,
2812 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002813};
2814
Anders Carlssondefefd22010-04-23 02:00:02 +00002815static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002816BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002817 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002818 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002819 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002820 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002821 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002822 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2823 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002824
John McCall60d7b3a2010-08-24 06:29:42 +00002825 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002826
2827 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002828 case IIK_Inherit: {
2829 const CXXRecordDecl *Inherited =
2830 Constructor->getInheritedConstructor()->getParent();
2831 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2832 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2833 // C++11 [class.inhctor]p8:
2834 // Each expression in the expression-list is of the form
2835 // static_cast<T&&>(p), where p is the name of the corresponding
2836 // constructor parameter and T is the declared type of p.
2837 SmallVector<Expr*, 16> Args;
2838 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2839 ParmVarDecl *PD = Constructor->getParamDecl(I);
2840 ExprResult ArgExpr =
2841 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2842 VK_LValue, SourceLocation());
2843 if (ArgExpr.isInvalid())
2844 return true;
2845 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2846 }
2847
2848 InitializationKind InitKind = InitializationKind::CreateDirect(
2849 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002850 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002851 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2852 break;
2853 }
2854 }
2855 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002856 case IIK_Default: {
2857 InitializationKind InitKind
2858 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002859 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2860 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002861 break;
2862 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002863
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002864 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002865 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002866 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002867 ParmVarDecl *Param = Constructor->getParamDecl(0);
2868 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002869
Anders Carlssone5ef7402010-04-23 03:10:23 +00002870 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002871 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002872 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002873 Constructor->getLocation(), ParamType,
2874 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002875
Eli Friedman5f2987c2012-02-02 03:46:19 +00002876 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2877
Anders Carlssonc7957502010-04-24 22:02:54 +00002878 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002879 QualType ArgTy =
2880 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2881 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002882
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002883 if (Moving) {
2884 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2885 }
2886
John McCallf871d0c2010-08-07 06:22:56 +00002887 CXXCastPath BasePath;
2888 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002889 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2890 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002891 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002892 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002893
Anders Carlssone5ef7402010-04-23 03:10:23 +00002894 InitializationKind InitKind
2895 = InitializationKind::CreateDirect(Constructor->getLocation(),
2896 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002897 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2898 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002899 break;
2900 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002901 }
John McCall9ae2f072010-08-23 23:25:46 +00002902
Douglas Gregor53c374f2010-12-07 00:41:46 +00002903 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002904 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002905 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002906
Anders Carlssondefefd22010-04-23 02:00:02 +00002907 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002908 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002909 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2910 SourceLocation()),
2911 BaseSpec->isVirtual(),
2912 SourceLocation(),
2913 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002914 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002915 SourceLocation());
2916
Anders Carlssondefefd22010-04-23 02:00:02 +00002917 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002918}
2919
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002920static bool RefersToRValueRef(Expr *MemRef) {
2921 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2922 return Referenced->getType()->isRValueReferenceType();
2923}
2924
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002925static bool
2926BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002927 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002928 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002929 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002930 if (Field->isInvalidDecl())
2931 return true;
2932
Chandler Carruthf186b542010-06-29 23:50:44 +00002933 SourceLocation Loc = Constructor->getLocation();
2934
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002935 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2936 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002937 ParmVarDecl *Param = Constructor->getParamDecl(0);
2938 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002939
2940 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002941 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2942 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002943
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002944 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002945 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002946 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002947 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002948
Eli Friedman5f2987c2012-02-02 03:46:19 +00002949 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2950
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002951 if (Moving) {
2952 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2953 }
2954
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002955 // Build a reference to this field within the parameter.
2956 CXXScopeSpec SS;
2957 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2958 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002959 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2960 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002961 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002962 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002963 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002964 ParamType, Loc,
2965 /*IsArrow=*/false,
2966 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002967 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002968 /*FirstQualifierInScope=*/0,
2969 MemberLookup,
2970 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002971 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002972 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002973
2974 // C++11 [class.copy]p15:
2975 // - if a member m has rvalue reference type T&&, it is direct-initialized
2976 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002977 if (RefersToRValueRef(CtorArg.get())) {
2978 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002979 }
2980
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002981 // When the field we are copying is an array, create index variables for
2982 // each dimension of the array. We use these index variables to subscript
2983 // the source array, and other clients (e.g., CodeGen) will perform the
2984 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002985 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002986 QualType BaseType = Field->getType();
2987 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002988 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002989 while (const ConstantArrayType *Array
2990 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002991 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002992 // Create the iteration variable for this array index.
2993 IdentifierInfo *IterationVarName = 0;
2994 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002995 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002996 llvm::raw_svector_ostream OS(Str);
2997 OS << "__i" << IndexVariables.size();
2998 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2999 }
3000 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003001 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003002 IterationVarName, SizeType,
3003 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003004 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003005 IndexVariables.push_back(IterationVar);
3006
3007 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003008 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003009 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003010 assert(!IterationVarRef.isInvalid() &&
3011 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003012 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3013 assert(!IterationVarRef.isInvalid() &&
3014 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003015
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003016 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003017 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003018 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003019 Loc);
3020 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003021 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003022
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003023 BaseType = Array->getElementType();
3024 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003025
3026 // The array subscript expression is an lvalue, which is wrong for moving.
3027 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003028 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003029
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003030 // Construct the entity that we will be initializing. For an array, this
3031 // will be first element in the array, which may require several levels
3032 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003033 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003034 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003035 if (Indirect)
3036 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3037 else
3038 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003039 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3040 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3041 0,
3042 Entities.back()));
3043
3044 // Direct-initialize to use the copy constructor.
3045 InitializationKind InitKind =
3046 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3047
Sebastian Redl74e611a2011-09-04 18:14:28 +00003048 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003049 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003050
John McCall60d7b3a2010-08-24 06:29:42 +00003051 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003052 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003053 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003054 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003055 if (MemberInit.isInvalid())
3056 return true;
3057
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003058 if (Indirect) {
3059 assert(IndexVariables.size() == 0 &&
3060 "Indirect field improperly initialized");
3061 CXXMemberInit
3062 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3063 Loc, Loc,
3064 MemberInit.takeAs<Expr>(),
3065 Loc);
3066 } else
3067 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3068 Loc, MemberInit.takeAs<Expr>(),
3069 Loc,
3070 IndexVariables.data(),
3071 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003072 return false;
3073 }
3074
Richard Smith07b0fdc2013-03-18 21:12:30 +00003075 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3076 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003077
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003078 QualType FieldBaseElementType =
3079 SemaRef.Context.getBaseElementType(Field->getType());
3080
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003081 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003082 InitializedEntity InitEntity
3083 = Indirect? InitializedEntity::InitializeMember(Indirect)
3084 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003085 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003086 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003087
3088 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3089 ExprResult MemberInit =
3090 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003091
Douglas Gregor53c374f2010-12-07 00:41:46 +00003092 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003093 if (MemberInit.isInvalid())
3094 return true;
3095
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003096 if (Indirect)
3097 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3098 Indirect, Loc,
3099 Loc,
3100 MemberInit.get(),
3101 Loc);
3102 else
3103 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3104 Field, Loc, Loc,
3105 MemberInit.get(),
3106 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003107 return false;
3108 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003109
Sean Hunt1f2f3842011-05-17 00:19:05 +00003110 if (!Field->getParent()->isUnion()) {
3111 if (FieldBaseElementType->isReferenceType()) {
3112 SemaRef.Diag(Constructor->getLocation(),
3113 diag::err_uninitialized_member_in_ctor)
3114 << (int)Constructor->isImplicit()
3115 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3116 << 0 << Field->getDeclName();
3117 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3118 return true;
3119 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003120
Sean Hunt1f2f3842011-05-17 00:19:05 +00003121 if (FieldBaseElementType.isConstQualified()) {
3122 SemaRef.Diag(Constructor->getLocation(),
3123 diag::err_uninitialized_member_in_ctor)
3124 << (int)Constructor->isImplicit()
3125 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3126 << 1 << Field->getDeclName();
3127 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3128 return true;
3129 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003130 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003131
David Blaikie4e4d0842012-03-11 07:00:24 +00003132 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003133 FieldBaseElementType->isObjCRetainableType() &&
3134 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3135 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003136 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003137 // Default-initialize Objective-C pointers to NULL.
3138 CXXMemberInit
3139 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3140 Loc, Loc,
3141 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3142 Loc);
3143 return false;
3144 }
3145
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003146 // Nothing to initialize.
3147 CXXMemberInit = 0;
3148 return false;
3149}
John McCallf1860e52010-05-20 23:23:51 +00003150
3151namespace {
3152struct BaseAndFieldInfo {
3153 Sema &S;
3154 CXXConstructorDecl *Ctor;
3155 bool AnyErrorsInInits;
3156 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003157 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003158 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003159
3160 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3161 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003162 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3163 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003164 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003165 else if (Generated && Ctor->isMoveConstructor())
3166 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003167 else if (Ctor->getInheritedConstructor())
3168 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003169 else
3170 IIK = IIK_Default;
3171 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003172
3173 bool isImplicitCopyOrMove() const {
3174 switch (IIK) {
3175 case IIK_Copy:
3176 case IIK_Move:
3177 return true;
3178
3179 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003180 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003181 return false;
3182 }
David Blaikie30263482012-01-20 21:50:17 +00003183
3184 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003185 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003186
3187 bool addFieldInitializer(CXXCtorInitializer *Init) {
3188 AllToInit.push_back(Init);
3189
3190 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003191 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003192 S.UnusedPrivateFields.remove(Init->getAnyMember());
3193
3194 return false;
3195 }
John McCallf1860e52010-05-20 23:23:51 +00003196};
3197}
3198
Richard Smitha4950662011-09-19 13:34:43 +00003199/// \brief Determine whether the given indirect field declaration is somewhere
3200/// within an anonymous union.
3201static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3202 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3203 CEnd = F->chain_end();
3204 C != CEnd; ++C)
3205 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3206 if (Record->isUnion())
3207 return true;
3208
3209 return false;
3210}
3211
Douglas Gregorddb21472011-11-02 23:04:16 +00003212/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3213/// array type.
3214static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3215 if (T->isIncompleteArrayType())
3216 return true;
3217
3218 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3219 if (!ArrayT->getSize())
3220 return true;
3221
3222 T = ArrayT->getElementType();
3223 }
3224
3225 return false;
3226}
3227
Richard Smith7a614d82011-06-11 17:19:42 +00003228static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003229 FieldDecl *Field,
3230 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003231
Chandler Carruthe861c602010-06-30 02:59:29 +00003232 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003233 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3234 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003235
Richard Smith0b8220a2012-08-07 21:30:42 +00003236 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003237 // has a brace-or-equal-initializer, the entity is initialized as specified
3238 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003239 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003240 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3241 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003242 CXXCtorInitializer *Init;
3243 if (Indirect)
3244 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3245 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003246 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003247 SourceLocation());
3248 else
3249 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3250 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003251 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003252 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003253 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003254 }
3255
Richard Smithc115f632011-09-18 11:14:50 +00003256 // Don't build an implicit initializer for union members if none was
3257 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003258 if (Field->getParent()->isUnion() ||
3259 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003260 return false;
3261
Douglas Gregorddb21472011-11-02 23:04:16 +00003262 // Don't initialize incomplete or zero-length arrays.
3263 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3264 return false;
3265
John McCallf1860e52010-05-20 23:23:51 +00003266 // Don't try to build an implicit initializer if there were semantic
3267 // errors in any of the initializers (and therefore we might be
3268 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003269 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003270 return false;
3271
Sean Huntcbb67482011-01-08 20:30:50 +00003272 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003273 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3274 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003275 return true;
John McCallf1860e52010-05-20 23:23:51 +00003276
Richard Smith0b8220a2012-08-07 21:30:42 +00003277 if (!Init)
3278 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003279
Richard Smith0b8220a2012-08-07 21:30:42 +00003280 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003281}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003282
3283bool
3284Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3285 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003286 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003287 Constructor->setNumCtorInitializers(1);
3288 CXXCtorInitializer **initializer =
3289 new (Context) CXXCtorInitializer*[1];
3290 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3291 Constructor->setCtorInitializers(initializer);
3292
Sean Huntb76af9c2011-05-03 23:05:34 +00003293 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003294 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003295 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3296 }
3297
Sean Huntc1598702011-05-05 00:05:47 +00003298 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003299
Sean Hunt059ce0d2011-05-01 07:04:31 +00003300 return false;
3301}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003302
David Blaikie93c86172013-01-17 05:26:25 +00003303bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3304 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003305 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003306 // Just store the initializers as written, they will be checked during
3307 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003308 if (!Initializers.empty()) {
3309 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003310 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003311 new (Context) CXXCtorInitializer*[Initializers.size()];
3312 memcpy(baseOrMemberInitializers, Initializers.data(),
3313 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003314 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003315 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003316
3317 // Let template instantiation know whether we had errors.
3318 if (AnyErrors)
3319 Constructor->setInvalidDecl();
3320
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003321 return false;
3322 }
3323
John McCallf1860e52010-05-20 23:23:51 +00003324 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003325
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003326 // We need to build the initializer AST according to order of construction
3327 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003328 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003329 if (!ClassDecl)
3330 return true;
3331
Eli Friedman80c30da2009-11-09 19:20:36 +00003332 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003333
David Blaikie93c86172013-01-17 05:26:25 +00003334 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003335 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003336
3337 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003338 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003339 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003340 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003341 }
3342
Anders Carlsson711f34a2010-04-21 19:52:01 +00003343 // Keep track of the direct virtual bases.
3344 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3345 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3346 E = ClassDecl->bases_end(); I != E; ++I) {
3347 if (I->isVirtual())
3348 DirectVBases.insert(I);
3349 }
3350
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003351 // Push virtual bases before others.
3352 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3353 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3354
Sean Huntcbb67482011-01-08 20:30:50 +00003355 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003356 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3357 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003358 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003359 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003360 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003361 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003362 VBase, IsInheritedVirtualBase,
3363 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003364 HadError = true;
3365 continue;
3366 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003367
John McCallf1860e52010-05-20 23:23:51 +00003368 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003369 }
3370 }
Mike Stump1eb44332009-09-09 15:08:12 +00003371
John McCallf1860e52010-05-20 23:23:51 +00003372 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003373 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3374 E = ClassDecl->bases_end(); Base != E; ++Base) {
3375 // Virtuals are in the virtual base list and already constructed.
3376 if (Base->isVirtual())
3377 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003378
Sean Huntcbb67482011-01-08 20:30:50 +00003379 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003380 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3381 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003382 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003383 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003384 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003385 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003386 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003387 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003388 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003389 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003390
John McCallf1860e52010-05-20 23:23:51 +00003391 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003392 }
3393 }
Mike Stump1eb44332009-09-09 15:08:12 +00003394
John McCallf1860e52010-05-20 23:23:51 +00003395 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003396 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3397 MemEnd = ClassDecl->decls_end();
3398 Mem != MemEnd; ++Mem) {
3399 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003400 // C++ [class.bit]p2:
3401 // A declaration for a bit-field that omits the identifier declares an
3402 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3403 // initialized.
3404 if (F->isUnnamedBitfield())
3405 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003406
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003407 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003408 // handle anonymous struct/union fields based on their individual
3409 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003410 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003411 continue;
3412
3413 if (CollectFieldInitializer(*this, Info, F))
3414 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003415 continue;
3416 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003417
3418 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003419 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003420 continue;
3421
3422 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3423 if (F->getType()->isIncompleteArrayType()) {
3424 assert(ClassDecl->hasFlexibleArrayMember() &&
3425 "Incomplete array type is not valid");
3426 continue;
3427 }
3428
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003429 // Initialize each field of an anonymous struct individually.
3430 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3431 HadError = true;
3432
3433 continue;
3434 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003435 }
Mike Stump1eb44332009-09-09 15:08:12 +00003436
David Blaikie93c86172013-01-17 05:26:25 +00003437 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003438 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003439 Constructor->setNumCtorInitializers(NumInitializers);
3440 CXXCtorInitializer **baseOrMemberInitializers =
3441 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003442 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003443 NumInitializers * sizeof(CXXCtorInitializer*));
3444 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003445
John McCallef027fe2010-03-16 21:39:52 +00003446 // Constructors implicitly reference the base and member
3447 // destructors.
3448 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3449 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003450 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003451
3452 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003453}
3454
David Blaikieee000bb2013-01-17 08:49:22 +00003455static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003456 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003457 const RecordDecl *RD = RT->getDecl();
3458 if (RD->isAnonymousStructOrUnion()) {
3459 for (RecordDecl::field_iterator Field = RD->field_begin(),
3460 E = RD->field_end(); Field != E; ++Field)
3461 PopulateKeysForFields(*Field, IdealInits);
3462 return;
3463 }
Eli Friedman6347f422009-07-21 19:28:10 +00003464 }
David Blaikieee000bb2013-01-17 08:49:22 +00003465 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003466}
3467
Anders Carlssonea356fb2010-04-02 05:42:15 +00003468static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003469 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003470}
3471
Anders Carlssonea356fb2010-04-02 05:42:15 +00003472static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003473 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003474 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003475 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003476
David Blaikieee000bb2013-01-17 08:49:22 +00003477 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003478}
3479
David Blaikie93c86172013-01-17 05:26:25 +00003480static void DiagnoseBaseOrMemInitializerOrder(
3481 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3482 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003483 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003484 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003485
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003486 // Don't check initializers order unless the warning is enabled at the
3487 // location of at least one initializer.
3488 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003489 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003490 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003491 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3492 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003493 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003494 ShouldCheckOrder = true;
3495 break;
3496 }
3497 }
3498 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003499 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003500
John McCalld6ca8da2010-04-10 07:37:23 +00003501 // Build the list of bases and members in the order that they'll
3502 // actually be initialized. The explicit initializers should be in
3503 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003504 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003505
Anders Carlsson071d6102010-04-02 03:38:04 +00003506 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3507
John McCalld6ca8da2010-04-10 07:37:23 +00003508 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003509 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003510 ClassDecl->vbases_begin(),
3511 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003512 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003513
John McCalld6ca8da2010-04-10 07:37:23 +00003514 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003515 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003516 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003517 if (Base->isVirtual())
3518 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003519 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003520 }
Mike Stump1eb44332009-09-09 15:08:12 +00003521
John McCalld6ca8da2010-04-10 07:37:23 +00003522 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003523 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003524 E = ClassDecl->field_end(); Field != E; ++Field) {
3525 if (Field->isUnnamedBitfield())
3526 continue;
3527
David Blaikieee000bb2013-01-17 08:49:22 +00003528 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003529 }
3530
John McCalld6ca8da2010-04-10 07:37:23 +00003531 unsigned NumIdealInits = IdealInitKeys.size();
3532 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003533
Sean Huntcbb67482011-01-08 20:30:50 +00003534 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003535 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003536 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003537 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003538
3539 // Scan forward to try to find this initializer in the idealized
3540 // initializers list.
3541 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3542 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003543 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003544
3545 // If we didn't find this initializer, it must be because we
3546 // scanned past it on a previous iteration. That can only
3547 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003548 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003549 Sema::SemaDiagnosticBuilder D =
3550 SemaRef.Diag(PrevInit->getSourceLocation(),
3551 diag::warn_initializer_out_of_order);
3552
Francois Pichet00eb3f92010-12-04 09:14:42 +00003553 if (PrevInit->isAnyMemberInitializer())
3554 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003555 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003556 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003557
Francois Pichet00eb3f92010-12-04 09:14:42 +00003558 if (Init->isAnyMemberInitializer())
3559 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003560 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003561 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003562
3563 // Move back to the initializer's location in the ideal list.
3564 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3565 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003566 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003567
3568 assert(IdealIndex != NumIdealInits &&
3569 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003570 }
John McCalld6ca8da2010-04-10 07:37:23 +00003571
3572 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003573 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003574}
3575
John McCall3c3ccdb2010-04-10 09:28:51 +00003576namespace {
3577bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003578 CXXCtorInitializer *Init,
3579 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003580 if (!PrevInit) {
3581 PrevInit = Init;
3582 return false;
3583 }
3584
Douglas Gregordc392c12013-03-25 23:28:23 +00003585 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003586 S.Diag(Init->getSourceLocation(),
3587 diag::err_multiple_mem_initialization)
3588 << Field->getDeclName()
3589 << Init->getSourceRange();
3590 else {
John McCallf4c73712011-01-19 06:33:43 +00003591 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003592 assert(BaseClass && "neither field nor base");
3593 S.Diag(Init->getSourceLocation(),
3594 diag::err_multiple_base_initialization)
3595 << QualType(BaseClass, 0)
3596 << Init->getSourceRange();
3597 }
3598 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3599 << 0 << PrevInit->getSourceRange();
3600
3601 return true;
3602}
3603
Sean Huntcbb67482011-01-08 20:30:50 +00003604typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003605typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3606
3607bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003608 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003609 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003610 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003611 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003612 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003613
3614 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003615 if (Parent->isUnion()) {
3616 UnionEntry &En = Unions[Parent];
3617 if (En.first && En.first != Child) {
3618 S.Diag(Init->getSourceLocation(),
3619 diag::err_multiple_mem_union_initialization)
3620 << Field->getDeclName()
3621 << Init->getSourceRange();
3622 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3623 << 0 << En.second->getSourceRange();
3624 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003625 }
3626 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003627 En.first = Child;
3628 En.second = Init;
3629 }
David Blaikie6fe29652011-11-17 06:01:57 +00003630 if (!Parent->isAnonymousStructOrUnion())
3631 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003632 }
3633
3634 Child = Parent;
3635 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003636 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003637
3638 return false;
3639}
3640}
3641
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003642/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003643void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003644 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003645 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003646 bool AnyErrors) {
3647 if (!ConstructorDecl)
3648 return;
3649
3650 AdjustDeclIfTemplate(ConstructorDecl);
3651
3652 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003653 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003654
3655 if (!Constructor) {
3656 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3657 return;
3658 }
3659
John McCall3c3ccdb2010-04-10 09:28:51 +00003660 // Mapping for the duplicate initializers check.
3661 // For member initializers, this is keyed with a FieldDecl*.
3662 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003663 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003664
3665 // Mapping for the inconsistent anonymous-union initializers check.
3666 RedundantUnionMap MemberUnions;
3667
Anders Carlssonea356fb2010-04-02 05:42:15 +00003668 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003669 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003670 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003671
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003672 // Set the source order index.
3673 Init->setSourceOrder(i);
3674
Francois Pichet00eb3f92010-12-04 09:14:42 +00003675 if (Init->isAnyMemberInitializer()) {
3676 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003677 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3678 CheckRedundantUnionInit(*this, Init, MemberUnions))
3679 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003680 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003681 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3682 if (CheckRedundantInit(*this, Init, Members[Key]))
3683 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003684 } else {
3685 assert(Init->isDelegatingInitializer());
3686 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003687 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003688 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003689 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003690 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003691 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003692 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003693 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003694 // Return immediately as the initializer is set.
3695 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003696 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003697 }
3698
Anders Carlssonea356fb2010-04-02 05:42:15 +00003699 if (HadError)
3700 return;
3701
David Blaikie93c86172013-01-17 05:26:25 +00003702 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003703
David Blaikie93c86172013-01-17 05:26:25 +00003704 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003705}
3706
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003707void
John McCallef027fe2010-03-16 21:39:52 +00003708Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3709 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003710 // Ignore dependent contexts. Also ignore unions, since their members never
3711 // have destructors implicitly called.
3712 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003713 return;
John McCall58e6f342010-03-16 05:22:47 +00003714
3715 // FIXME: all the access-control diagnostics are positioned on the
3716 // field/base declaration. That's probably good; that said, the
3717 // user might reasonably want to know why the destructor is being
3718 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003719
Anders Carlsson9f853df2009-11-17 04:44:12 +00003720 // Non-static data members.
3721 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3722 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003723 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003724 if (Field->isInvalidDecl())
3725 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003726
3727 // Don't destroy incomplete or zero-length arrays.
3728 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3729 continue;
3730
Anders Carlsson9f853df2009-11-17 04:44:12 +00003731 QualType FieldType = Context.getBaseElementType(Field->getType());
3732
3733 const RecordType* RT = FieldType->getAs<RecordType>();
3734 if (!RT)
3735 continue;
3736
3737 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003738 if (FieldClassDecl->isInvalidDecl())
3739 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003740 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003741 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003742 // The destructor for an implicit anonymous union member is never invoked.
3743 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3744 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003745
Douglas Gregordb89f282010-07-01 22:47:18 +00003746 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003747 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003748 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003749 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003750 << Field->getDeclName()
3751 << FieldType);
3752
Eli Friedman5f2987c2012-02-02 03:46:19 +00003753 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003754 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003755 }
3756
John McCall58e6f342010-03-16 05:22:47 +00003757 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3758
Anders Carlsson9f853df2009-11-17 04:44:12 +00003759 // Bases.
3760 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3761 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003762 // Bases are always records in a well-formed non-dependent class.
3763 const RecordType *RT = Base->getType()->getAs<RecordType>();
3764
3765 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003766 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003767 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003768
John McCall58e6f342010-03-16 05:22:47 +00003769 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003770 // If our base class is invalid, we probably can't get its dtor anyway.
3771 if (BaseClassDecl->isInvalidDecl())
3772 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003773 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003774 continue;
John McCall58e6f342010-03-16 05:22:47 +00003775
Douglas Gregordb89f282010-07-01 22:47:18 +00003776 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003777 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003778
3779 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003780 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003781 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003782 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003783 << Base->getSourceRange(),
3784 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003785
Eli Friedman5f2987c2012-02-02 03:46:19 +00003786 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003787 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003788 }
3789
3790 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003791 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3792 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003793
3794 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003795 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003796
3797 // Ignore direct virtual bases.
3798 if (DirectVirtualBases.count(RT))
3799 continue;
3800
John McCall58e6f342010-03-16 05:22:47 +00003801 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003802 // If our base class is invalid, we probably can't get its dtor anyway.
3803 if (BaseClassDecl->isInvalidDecl())
3804 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003805 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003806 continue;
John McCall58e6f342010-03-16 05:22:47 +00003807
Douglas Gregordb89f282010-07-01 22:47:18 +00003808 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003809 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003810 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003811 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003812 << VBase->getType(),
3813 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003814
Eli Friedman5f2987c2012-02-02 03:46:19 +00003815 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003816 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003817 }
3818}
3819
John McCalld226f652010-08-21 09:40:31 +00003820void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003821 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003822 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003823
Mike Stump1eb44332009-09-09 15:08:12 +00003824 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003825 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003826 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003827}
3828
Mike Stump1eb44332009-09-09 15:08:12 +00003829bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003830 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003831 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3832 unsigned DiagID;
3833 AbstractDiagSelID SelID;
3834
3835 public:
3836 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3837 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3838
3839 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003840 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003841 if (SelID == -1)
3842 S.Diag(Loc, DiagID) << T;
3843 else
3844 S.Diag(Loc, DiagID) << SelID << T;
3845 }
3846 } Diagnoser(DiagID, SelID);
3847
3848 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003849}
3850
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003851bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003852 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003853 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003854 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003855
Anders Carlsson11f21a02009-03-23 19:10:31 +00003856 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003857 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003858
Ted Kremenek6217b802009-07-29 21:53:49 +00003859 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003860 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003861 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003862 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003863
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003864 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003865 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003866 }
Mike Stump1eb44332009-09-09 15:08:12 +00003867
Ted Kremenek6217b802009-07-29 21:53:49 +00003868 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003869 if (!RT)
3870 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003871
John McCall86ff3082010-02-04 22:26:26 +00003872 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003873
John McCall94c3b562010-08-18 09:41:07 +00003874 // We can't answer whether something is abstract until it has a
3875 // definition. If it's currently being defined, we'll walk back
3876 // over all the declarations when we have a full definition.
3877 const CXXRecordDecl *Def = RD->getDefinition();
3878 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003879 return false;
3880
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003881 if (!RD->isAbstract())
3882 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003883
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003884 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003885 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003886
John McCall94c3b562010-08-18 09:41:07 +00003887 return true;
3888}
3889
3890void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3891 // Check if we've already emitted the list of pure virtual functions
3892 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003893 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003894 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003895
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003896 CXXFinalOverriderMap FinalOverriders;
3897 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003898
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003899 // Keep a set of seen pure methods so we won't diagnose the same method
3900 // more than once.
3901 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3902
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003903 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3904 MEnd = FinalOverriders.end();
3905 M != MEnd;
3906 ++M) {
3907 for (OverridingMethods::iterator SO = M->second.begin(),
3908 SOEnd = M->second.end();
3909 SO != SOEnd; ++SO) {
3910 // C++ [class.abstract]p4:
3911 // A class is abstract if it contains or inherits at least one
3912 // pure virtual function for which the final overrider is pure
3913 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003914
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003915 //
3916 if (SO->second.size() != 1)
3917 continue;
3918
3919 if (!SO->second.front().Method->isPure())
3920 continue;
3921
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003922 if (!SeenPureMethods.insert(SO->second.front().Method))
3923 continue;
3924
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003925 Diag(SO->second.front().Method->getLocation(),
3926 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003927 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003928 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003929 }
3930
3931 if (!PureVirtualClassDiagSet)
3932 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3933 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003934}
3935
Anders Carlsson8211eff2009-03-24 01:19:16 +00003936namespace {
John McCall94c3b562010-08-18 09:41:07 +00003937struct AbstractUsageInfo {
3938 Sema &S;
3939 CXXRecordDecl *Record;
3940 CanQualType AbstractType;
3941 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003942
John McCall94c3b562010-08-18 09:41:07 +00003943 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3944 : S(S), Record(Record),
3945 AbstractType(S.Context.getCanonicalType(
3946 S.Context.getTypeDeclType(Record))),
3947 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003948
John McCall94c3b562010-08-18 09:41:07 +00003949 void DiagnoseAbstractType() {
3950 if (Invalid) return;
3951 S.DiagnoseAbstractType(Record);
3952 Invalid = true;
3953 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003954
John McCall94c3b562010-08-18 09:41:07 +00003955 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3956};
3957
3958struct CheckAbstractUsage {
3959 AbstractUsageInfo &Info;
3960 const NamedDecl *Ctx;
3961
3962 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3963 : Info(Info), Ctx(Ctx) {}
3964
3965 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3966 switch (TL.getTypeLocClass()) {
3967#define ABSTRACT_TYPELOC(CLASS, PARENT)
3968#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003969 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003970#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003971 }
John McCall94c3b562010-08-18 09:41:07 +00003972 }
Mike Stump1eb44332009-09-09 15:08:12 +00003973
John McCall94c3b562010-08-18 09:41:07 +00003974 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3975 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3976 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003977 if (!TL.getArg(I))
3978 continue;
3979
John McCall94c3b562010-08-18 09:41:07 +00003980 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3981 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003982 }
John McCall94c3b562010-08-18 09:41:07 +00003983 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003984
John McCall94c3b562010-08-18 09:41:07 +00003985 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3986 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3987 }
Mike Stump1eb44332009-09-09 15:08:12 +00003988
John McCall94c3b562010-08-18 09:41:07 +00003989 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3990 // Visit the type parameters from a permissive context.
3991 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3992 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3993 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3994 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3995 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3996 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003997 }
John McCall94c3b562010-08-18 09:41:07 +00003998 }
Mike Stump1eb44332009-09-09 15:08:12 +00003999
John McCall94c3b562010-08-18 09:41:07 +00004000 // Visit pointee types from a permissive context.
4001#define CheckPolymorphic(Type) \
4002 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4003 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4004 }
4005 CheckPolymorphic(PointerTypeLoc)
4006 CheckPolymorphic(ReferenceTypeLoc)
4007 CheckPolymorphic(MemberPointerTypeLoc)
4008 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004009 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004010
John McCall94c3b562010-08-18 09:41:07 +00004011 /// Handle all the types we haven't given a more specific
4012 /// implementation for above.
4013 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4014 // Every other kind of type that we haven't called out already
4015 // that has an inner type is either (1) sugar or (2) contains that
4016 // inner type in some way as a subobject.
4017 if (TypeLoc Next = TL.getNextTypeLoc())
4018 return Visit(Next, Sel);
4019
4020 // If there's no inner type and we're in a permissive context,
4021 // don't diagnose.
4022 if (Sel == Sema::AbstractNone) return;
4023
4024 // Check whether the type matches the abstract type.
4025 QualType T = TL.getType();
4026 if (T->isArrayType()) {
4027 Sel = Sema::AbstractArrayType;
4028 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004029 }
John McCall94c3b562010-08-18 09:41:07 +00004030 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4031 if (CT != Info.AbstractType) return;
4032
4033 // It matched; do some magic.
4034 if (Sel == Sema::AbstractArrayType) {
4035 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4036 << T << TL.getSourceRange();
4037 } else {
4038 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4039 << Sel << T << TL.getSourceRange();
4040 }
4041 Info.DiagnoseAbstractType();
4042 }
4043};
4044
4045void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4046 Sema::AbstractDiagSelID Sel) {
4047 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4048}
4049
4050}
4051
4052/// Check for invalid uses of an abstract type in a method declaration.
4053static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4054 CXXMethodDecl *MD) {
4055 // No need to do the check on definitions, which require that
4056 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004057 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004058 return;
4059
4060 // For safety's sake, just ignore it if we don't have type source
4061 // information. This should never happen for non-implicit methods,
4062 // but...
4063 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4064 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4065}
4066
4067/// Check for invalid uses of an abstract type within a class definition.
4068static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4069 CXXRecordDecl *RD) {
4070 for (CXXRecordDecl::decl_iterator
4071 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4072 Decl *D = *I;
4073 if (D->isImplicit()) continue;
4074
4075 // Methods and method templates.
4076 if (isa<CXXMethodDecl>(D)) {
4077 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4078 } else if (isa<FunctionTemplateDecl>(D)) {
4079 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4080 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4081
4082 // Fields and static variables.
4083 } else if (isa<FieldDecl>(D)) {
4084 FieldDecl *FD = cast<FieldDecl>(D);
4085 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4086 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4087 } else if (isa<VarDecl>(D)) {
4088 VarDecl *VD = cast<VarDecl>(D);
4089 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4090 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4091
4092 // Nested classes and class templates.
4093 } else if (isa<CXXRecordDecl>(D)) {
4094 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4095 } else if (isa<ClassTemplateDecl>(D)) {
4096 CheckAbstractClassUsage(Info,
4097 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4098 }
4099 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004100}
4101
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004102/// \brief Perform semantic checks on a class definition that has been
4103/// completing, introducing implicitly-declared members, checking for
4104/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004105void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004106 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004107 return;
4108
John McCall94c3b562010-08-18 09:41:07 +00004109 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4110 AbstractUsageInfo Info(*this, Record);
4111 CheckAbstractClassUsage(Info, Record);
4112 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004113
4114 // If this is not an aggregate type and has no user-declared constructor,
4115 // complain about any non-static data members of reference or const scalar
4116 // type, since they will never get initializers.
4117 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004118 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4119 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004120 bool Complained = false;
4121 for (RecordDecl::field_iterator F = Record->field_begin(),
4122 FEnd = Record->field_end();
4123 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004124 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004125 continue;
4126
Douglas Gregor325e5932010-04-15 00:00:53 +00004127 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004128 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004129 if (!Complained) {
4130 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4131 << Record->getTagKind() << Record;
4132 Complained = true;
4133 }
4134
4135 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4136 << F->getType()->isReferenceType()
4137 << F->getDeclName();
4138 }
4139 }
4140 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004141
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004142 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004143 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004144
4145 if (Record->getIdentifier()) {
4146 // C++ [class.mem]p13:
4147 // If T is the name of a class, then each of the following shall have a
4148 // name different from T:
4149 // - every member of every anonymous union that is a member of class T.
4150 //
4151 // C++ [class.mem]p14:
4152 // In addition, if class T has a user-declared constructor (12.1), every
4153 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004154 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4155 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4156 ++I) {
4157 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004158 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4159 isa<IndirectFieldDecl>(D)) {
4160 Diag(D->getLocation(), diag::err_member_name_of_class)
4161 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004162 break;
4163 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004164 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004165 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004166
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004167 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004168 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004169 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004170 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004171 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4172 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4173 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004174
David Blaikieb6b5b972012-09-21 03:21:07 +00004175 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4176 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4177 DiagnoseAbstractType(Record);
4178 }
4179
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004180 if (!Record->isDependentType()) {
4181 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4182 MEnd = Record->method_end();
4183 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004184 // See if a method overloads virtual methods in a base
4185 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004186 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004187 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004188
4189 // Check whether the explicitly-defaulted special members are valid.
4190 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4191 CheckExplicitlyDefaultedSpecialMember(*M);
4192
4193 // For an explicitly defaulted or deleted special member, we defer
4194 // determining triviality until the class is complete. That time is now!
4195 if (!M->isImplicit() && !M->isUserProvided()) {
4196 CXXSpecialMember CSM = getSpecialMember(*M);
4197 if (CSM != CXXInvalid) {
4198 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4199
4200 // Inform the class that we've finished declaring this member.
4201 Record->finishedDefaultedOrDeletedMember(*M);
4202 }
4203 }
4204 }
4205 }
4206
4207 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4208 // function that is not a constructor declares that member function to be
4209 // const. [...] The class of which that function is a member shall be
4210 // a literal type.
4211 //
4212 // If the class has virtual bases, any constexpr members will already have
4213 // been diagnosed by the checks performed on the member declaration, so
4214 // suppress this (less useful) diagnostic.
4215 //
4216 // We delay this until we know whether an explicitly-defaulted (or deleted)
4217 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004218 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004219 !Record->isLiteral() && !Record->getNumVBases()) {
4220 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4221 MEnd = Record->method_end();
4222 M != MEnd; ++M) {
4223 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4224 switch (Record->getTemplateSpecializationKind()) {
4225 case TSK_ImplicitInstantiation:
4226 case TSK_ExplicitInstantiationDeclaration:
4227 case TSK_ExplicitInstantiationDefinition:
4228 // If a template instantiates to a non-literal type, but its members
4229 // instantiate to constexpr functions, the template is technically
4230 // ill-formed, but we allow it for sanity.
4231 continue;
4232
4233 case TSK_Undeclared:
4234 case TSK_ExplicitSpecialization:
4235 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4236 diag::err_constexpr_method_non_literal);
4237 break;
4238 }
4239
4240 // Only produce one error per class.
4241 break;
4242 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004243 }
4244 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004245
Richard Smith07b0fdc2013-03-18 21:12:30 +00004246 // Declare inheriting constructors. We do this eagerly here because:
4247 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004248 // constructors from different classes.
4249 // - The lazy declaration of the other implicit constructors is so as to not
4250 // waste space and performance on classes that are not meant to be
4251 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004252 // have inheriting constructors.
4253 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004254}
4255
Richard Smith7756afa2012-06-10 05:43:50 +00004256/// Is the special member function which would be selected to perform the
4257/// specified operation on the specified class type a constexpr constructor?
4258static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4259 Sema::CXXSpecialMember CSM,
4260 bool ConstArg) {
4261 Sema::SpecialMemberOverloadResult *SMOR =
4262 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4263 false, false, false, false);
4264 if (!SMOR || !SMOR->getMethod())
4265 // A constructor we wouldn't select can't be "involved in initializing"
4266 // anything.
4267 return true;
4268 return SMOR->getMethod()->isConstexpr();
4269}
4270
4271/// Determine whether the specified special member function would be constexpr
4272/// if it were implicitly defined.
4273static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4274 Sema::CXXSpecialMember CSM,
4275 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004276 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004277 return false;
4278
4279 // C++11 [dcl.constexpr]p4:
4280 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004281 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004282 switch (CSM) {
4283 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004284 // Since default constructor lookup is essentially trivial (and cannot
4285 // involve, for instance, template instantiation), we compute whether a
4286 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4287 //
4288 // This is important for performance; we need to know whether the default
4289 // constructor is constexpr to determine whether the type is a literal type.
4290 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4291
Richard Smith7756afa2012-06-10 05:43:50 +00004292 case Sema::CXXCopyConstructor:
4293 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004294 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004295 break;
4296
4297 case Sema::CXXCopyAssignment:
4298 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004299 if (!S.getLangOpts().CPlusPlus1y)
4300 return false;
4301 // In C++1y, we need to perform overload resolution.
4302 Ctor = false;
4303 break;
4304
Richard Smith7756afa2012-06-10 05:43:50 +00004305 case Sema::CXXDestructor:
4306 case Sema::CXXInvalid:
4307 return false;
4308 }
4309
4310 // -- if the class is a non-empty union, or for each non-empty anonymous
4311 // union member of a non-union class, exactly one non-static data member
4312 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004313 //
4314 // If we squint, this is guaranteed, since exactly one non-static data member
4315 // will be initialized (if the constructor isn't deleted), we just don't know
4316 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004317 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004318 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004319
4320 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004321 if (Ctor && ClassDecl->getNumVBases())
4322 return false;
4323
4324 // C++1y [class.copy]p26:
4325 // -- [the class] is a literal type, and
4326 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004327 return false;
4328
4329 // -- every constructor involved in initializing [...] base class
4330 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004331 // -- the assignment operator selected to copy/move each direct base
4332 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004333 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4334 BEnd = ClassDecl->bases_end();
4335 B != BEnd; ++B) {
4336 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4337 if (!BaseType) continue;
4338
4339 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4340 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4341 return false;
4342 }
4343
4344 // -- every constructor involved in initializing non-static data members
4345 // [...] shall be a constexpr constructor;
4346 // -- every non-static data member and base class sub-object shall be
4347 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004348 // -- for each non-stastic data member of X that is of class type (or array
4349 // thereof), the assignment operator selected to copy/move that member is
4350 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004351 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4352 FEnd = ClassDecl->field_end();
4353 F != FEnd; ++F) {
4354 if (F->isInvalidDecl())
4355 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004356 if (const RecordType *RecordTy =
4357 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004358 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4359 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4360 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004361 }
4362 }
4363
4364 // All OK, it's constexpr!
4365 return true;
4366}
4367
Richard Smithb9d0b762012-07-27 04:22:15 +00004368static Sema::ImplicitExceptionSpecification
4369computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4370 switch (S.getSpecialMember(MD)) {
4371 case Sema::CXXDefaultConstructor:
4372 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4373 case Sema::CXXCopyConstructor:
4374 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4375 case Sema::CXXCopyAssignment:
4376 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4377 case Sema::CXXMoveConstructor:
4378 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4379 case Sema::CXXMoveAssignment:
4380 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4381 case Sema::CXXDestructor:
4382 return S.ComputeDefaultedDtorExceptionSpec(MD);
4383 case Sema::CXXInvalid:
4384 break;
4385 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004386 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4387 "only special members have implicit exception specs");
4388 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004389}
4390
Richard Smithdd25e802012-07-30 23:48:14 +00004391static void
4392updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4393 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4394 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4395 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004396 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4397 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004398}
4399
Richard Smithb9d0b762012-07-27 04:22:15 +00004400void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4401 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4402 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4403 return;
4404
Richard Smithdd25e802012-07-30 23:48:14 +00004405 // Evaluate the exception specification.
4406 ImplicitExceptionSpecification ExceptSpec =
4407 computeImplicitExceptionSpec(*this, Loc, MD);
4408
4409 // Update the type of the special member to use it.
4410 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4411
4412 // A user-provided destructor can be defined outside the class. When that
4413 // happens, be sure to update the exception specification on both
4414 // declarations.
4415 const FunctionProtoType *CanonicalFPT =
4416 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4417 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4418 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4419 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004420}
4421
Richard Smith3003e1d2012-05-15 04:39:51 +00004422void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4423 CXXRecordDecl *RD = MD->getParent();
4424 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004425
Richard Smith3003e1d2012-05-15 04:39:51 +00004426 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4427 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004428
4429 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004430 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004431 bool First = MD == MD->getCanonicalDecl();
4432
4433 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004434
4435 // C++11 [dcl.fct.def.default]p1:
4436 // A function that is explicitly defaulted shall
4437 // -- be a special member function (checked elsewhere),
4438 // -- have the same type (except for ref-qualifiers, and except that a
4439 // copy operation can take a non-const reference) as an implicit
4440 // declaration, and
4441 // -- not have default arguments.
4442 unsigned ExpectedParams = 1;
4443 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4444 ExpectedParams = 0;
4445 if (MD->getNumParams() != ExpectedParams) {
4446 // This also checks for default arguments: a copy or move constructor with a
4447 // default argument is classified as a default constructor, and assignment
4448 // operations and destructors can't have default arguments.
4449 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4450 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004451 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004452 } else if (MD->isVariadic()) {
4453 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4454 << CSM << MD->getSourceRange();
4455 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004456 }
4457
Richard Smith3003e1d2012-05-15 04:39:51 +00004458 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004459
Richard Smith7756afa2012-06-10 05:43:50 +00004460 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004461 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004462 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004463 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004464 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004465
Richard Smith3003e1d2012-05-15 04:39:51 +00004466 QualType ReturnType = Context.VoidTy;
4467 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4468 // Check for return type matching.
4469 ReturnType = Type->getResultType();
4470 QualType ExpectedReturnType =
4471 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4472 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4473 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4474 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4475 HadError = true;
4476 }
4477
4478 // A defaulted special member cannot have cv-qualifiers.
4479 if (Type->getTypeQuals()) {
4480 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004481 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004482 HadError = true;
4483 }
4484 }
4485
4486 // Check for parameter type matching.
4487 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004488 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004489 if (ExpectedParams && ArgType->isReferenceType()) {
4490 // Argument must be reference to possibly-const T.
4491 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004492 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004493
4494 if (ReferentType.isVolatileQualified()) {
4495 Diag(MD->getLocation(),
4496 diag::err_defaulted_special_member_volatile_param) << CSM;
4497 HadError = true;
4498 }
4499
Richard Smith7756afa2012-06-10 05:43:50 +00004500 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004501 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4502 Diag(MD->getLocation(),
4503 diag::err_defaulted_special_member_copy_const_param)
4504 << (CSM == CXXCopyAssignment);
4505 // FIXME: Explain why this special member can't be const.
4506 } else {
4507 Diag(MD->getLocation(),
4508 diag::err_defaulted_special_member_move_const_param)
4509 << (CSM == CXXMoveAssignment);
4510 }
4511 HadError = true;
4512 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004513 } else if (ExpectedParams) {
4514 // A copy assignment operator can take its argument by value, but a
4515 // defaulted one cannot.
4516 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004517 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004518 HadError = true;
4519 }
Sean Huntbe631222011-05-17 20:44:43 +00004520
Richard Smith61802452011-12-22 02:22:31 +00004521 // C++11 [dcl.fct.def.default]p2:
4522 // An explicitly-defaulted function may be declared constexpr only if it
4523 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004524 // Do not apply this rule to members of class templates, since core issue 1358
4525 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004526 // functions which cannot be constexpr (for non-constructors in C++11 and for
4527 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004528 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4529 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004530 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4531 : isa<CXXConstructorDecl>(MD)) &&
4532 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004533 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4534 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004535 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004536 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004537 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004538
Richard Smith61802452011-12-22 02:22:31 +00004539 // and may have an explicit exception-specification only if it is compatible
4540 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004541 if (Type->hasExceptionSpec()) {
4542 // Delay the check if this is the first declaration of the special member,
4543 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004544 if (First) {
4545 // If the exception specification needs to be instantiated, do so now,
4546 // before we clobber it with an EST_Unevaluated specification below.
4547 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4548 InstantiateExceptionSpec(MD->getLocStart(), MD);
4549 Type = MD->getType()->getAs<FunctionProtoType>();
4550 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004551 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004552 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004553 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4554 }
Richard Smith61802452011-12-22 02:22:31 +00004555
4556 // If a function is explicitly defaulted on its first declaration,
4557 if (First) {
4558 // -- it is implicitly considered to be constexpr if the implicit
4559 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004560 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004561
Richard Smith3003e1d2012-05-15 04:39:51 +00004562 // -- it is implicitly considered to have the same exception-specification
4563 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004564 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4565 EPI.ExceptionSpecType = EST_Unevaluated;
4566 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004567 MD->setType(Context.getFunctionType(ReturnType,
4568 ArrayRef<QualType>(&ArgType,
4569 ExpectedParams),
4570 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004571 }
4572
Richard Smith3003e1d2012-05-15 04:39:51 +00004573 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004574 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004575 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004576 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004577 // C++11 [dcl.fct.def.default]p4:
4578 // [For a] user-provided explicitly-defaulted function [...] if such a
4579 // function is implicitly defined as deleted, the program is ill-formed.
4580 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4581 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004582 }
4583 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004584
Richard Smith3003e1d2012-05-15 04:39:51 +00004585 if (HadError)
4586 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004587}
4588
Richard Smith1d28caf2012-12-11 01:14:52 +00004589/// Check whether the exception specification provided for an
4590/// explicitly-defaulted special member matches the exception specification
4591/// that would have been generated for an implicit special member, per
4592/// C++11 [dcl.fct.def.default]p2.
4593void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4594 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4595 // Compute the implicit exception specification.
4596 FunctionProtoType::ExtProtoInfo EPI;
4597 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4598 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004599 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004600
4601 // Ensure that it matches.
4602 CheckEquivalentExceptionSpec(
4603 PDiag(diag::err_incorrect_defaulted_exception_spec)
4604 << getSpecialMember(MD), PDiag(),
4605 ImplicitType, SourceLocation(),
4606 SpecifiedType, MD->getLocation());
4607}
4608
4609void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4610 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4611 I != N; ++I)
4612 CheckExplicitlyDefaultedMemberExceptionSpec(
4613 DelayedDefaultedMemberExceptionSpecs[I].first,
4614 DelayedDefaultedMemberExceptionSpecs[I].second);
4615
4616 DelayedDefaultedMemberExceptionSpecs.clear();
4617}
4618
Richard Smith7d5088a2012-02-18 02:02:13 +00004619namespace {
4620struct SpecialMemberDeletionInfo {
4621 Sema &S;
4622 CXXMethodDecl *MD;
4623 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004624 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004625
4626 // Properties of the special member, computed for convenience.
4627 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4628 SourceLocation Loc;
4629
4630 bool AllFieldsAreConst;
4631
4632 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004633 Sema::CXXSpecialMember CSM, bool Diagnose)
4634 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004635 IsConstructor(false), IsAssignment(false), IsMove(false),
4636 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4637 AllFieldsAreConst(true) {
4638 switch (CSM) {
4639 case Sema::CXXDefaultConstructor:
4640 case Sema::CXXCopyConstructor:
4641 IsConstructor = true;
4642 break;
4643 case Sema::CXXMoveConstructor:
4644 IsConstructor = true;
4645 IsMove = true;
4646 break;
4647 case Sema::CXXCopyAssignment:
4648 IsAssignment = true;
4649 break;
4650 case Sema::CXXMoveAssignment:
4651 IsAssignment = true;
4652 IsMove = true;
4653 break;
4654 case Sema::CXXDestructor:
4655 break;
4656 case Sema::CXXInvalid:
4657 llvm_unreachable("invalid special member kind");
4658 }
4659
4660 if (MD->getNumParams()) {
4661 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4662 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4663 }
4664 }
4665
4666 bool inUnion() const { return MD->getParent()->isUnion(); }
4667
4668 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004669 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4670 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004671 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004672 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4673 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4674 Quals = 0;
4675 return S.LookupSpecialMember(Class, CSM,
4676 ConstArg || (Quals & Qualifiers::Const),
4677 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004678 MD->getRefQualifier() == RQ_RValue,
4679 TQ & Qualifiers::Const,
4680 TQ & Qualifiers::Volatile);
4681 }
4682
Richard Smith6c4c36c2012-03-30 20:53:28 +00004683 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004684
Richard Smith6c4c36c2012-03-30 20:53:28 +00004685 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004686 bool shouldDeleteForField(FieldDecl *FD);
4687 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004688
Richard Smith517bb842012-07-18 03:51:16 +00004689 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4690 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004691 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4692 Sema::SpecialMemberOverloadResult *SMOR,
4693 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004694
4695 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004696};
4697}
4698
John McCall12d8d802012-04-09 20:53:23 +00004699/// Is the given special member inaccessible when used on the given
4700/// sub-object.
4701bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4702 CXXMethodDecl *target) {
4703 /// If we're operating on a base class, the object type is the
4704 /// type of this special member.
4705 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004706 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004707 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4708 objectTy = S.Context.getTypeDeclType(MD->getParent());
4709 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4710
4711 // If we're operating on a field, the object type is the type of the field.
4712 } else {
4713 objectTy = S.Context.getTypeDeclType(target->getParent());
4714 }
4715
4716 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4717}
4718
Richard Smith6c4c36c2012-03-30 20:53:28 +00004719/// Check whether we should delete a special member due to the implicit
4720/// definition containing a call to a special member of a subobject.
4721bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4722 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4723 bool IsDtorCallInCtor) {
4724 CXXMethodDecl *Decl = SMOR->getMethod();
4725 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4726
4727 int DiagKind = -1;
4728
4729 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4730 DiagKind = !Decl ? 0 : 1;
4731 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4732 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004733 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004734 DiagKind = 3;
4735 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4736 !Decl->isTrivial()) {
4737 // A member of a union must have a trivial corresponding special member.
4738 // As a weird special case, a destructor call from a union's constructor
4739 // must be accessible and non-deleted, but need not be trivial. Such a
4740 // destructor is never actually called, but is semantically checked as
4741 // if it were.
4742 DiagKind = 4;
4743 }
4744
4745 if (DiagKind == -1)
4746 return false;
4747
4748 if (Diagnose) {
4749 if (Field) {
4750 S.Diag(Field->getLocation(),
4751 diag::note_deleted_special_member_class_subobject)
4752 << CSM << MD->getParent() << /*IsField*/true
4753 << Field << DiagKind << IsDtorCallInCtor;
4754 } else {
4755 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4756 S.Diag(Base->getLocStart(),
4757 diag::note_deleted_special_member_class_subobject)
4758 << CSM << MD->getParent() << /*IsField*/false
4759 << Base->getType() << DiagKind << IsDtorCallInCtor;
4760 }
4761
4762 if (DiagKind == 1)
4763 S.NoteDeletedFunction(Decl);
4764 // FIXME: Explain inaccessibility if DiagKind == 3.
4765 }
4766
4767 return true;
4768}
4769
Richard Smith9a561d52012-02-26 09:11:52 +00004770/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004771/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004772bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004773 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004774 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004775
4776 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004777 // -- any direct or virtual base class, or non-static data member with no
4778 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004779 // either M has no default constructor or overload resolution as applied
4780 // to M's default constructor results in an ambiguity or in a function
4781 // that is deleted or inaccessible
4782 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4783 // -- a direct or virtual base class B that cannot be copied/moved because
4784 // overload resolution, as applied to B's corresponding special member,
4785 // results in an ambiguity or a function that is deleted or inaccessible
4786 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004787 // C++11 [class.dtor]p5:
4788 // -- any direct or virtual base class [...] has a type with a destructor
4789 // that is deleted or inaccessible
4790 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004791 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004792 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004793 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004794
Richard Smith6c4c36c2012-03-30 20:53:28 +00004795 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4796 // -- any direct or virtual base class or non-static data member has a
4797 // type with a destructor that is deleted or inaccessible
4798 if (IsConstructor) {
4799 Sema::SpecialMemberOverloadResult *SMOR =
4800 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4801 false, false, false, false, false);
4802 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4803 return true;
4804 }
4805
Richard Smith9a561d52012-02-26 09:11:52 +00004806 return false;
4807}
4808
4809/// Check whether we should delete a special member function due to the class
4810/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004811bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004812 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004813 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004814}
4815
4816/// Check whether we should delete a special member function due to the class
4817/// having a particular non-static data member.
4818bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4819 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4820 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4821
4822 if (CSM == Sema::CXXDefaultConstructor) {
4823 // For a default constructor, all references must be initialized in-class
4824 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004825 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4826 if (Diagnose)
4827 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4828 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004829 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004830 }
Richard Smith79363f52012-02-27 06:07:25 +00004831 // C++11 [class.ctor]p5: any non-variant non-static data member of
4832 // const-qualified type (or array thereof) with no
4833 // brace-or-equal-initializer does not have a user-provided default
4834 // constructor.
4835 if (!inUnion() && FieldType.isConstQualified() &&
4836 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004837 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4838 if (Diagnose)
4839 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004840 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004841 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004842 }
4843
4844 if (inUnion() && !FieldType.isConstQualified())
4845 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004846 } else if (CSM == Sema::CXXCopyConstructor) {
4847 // For a copy constructor, data members must not be of rvalue reference
4848 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004849 if (FieldType->isRValueReferenceType()) {
4850 if (Diagnose)
4851 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4852 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004853 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004854 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004855 } else if (IsAssignment) {
4856 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004857 if (FieldType->isReferenceType()) {
4858 if (Diagnose)
4859 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4860 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004861 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004862 }
4863 if (!FieldRecord && FieldType.isConstQualified()) {
4864 // C++11 [class.copy]p23:
4865 // -- a non-static data member of const non-class type (or array thereof)
4866 if (Diagnose)
4867 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004868 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004869 return true;
4870 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004871 }
4872
4873 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004874 // Some additional restrictions exist on the variant members.
4875 if (!inUnion() && FieldRecord->isUnion() &&
4876 FieldRecord->isAnonymousStructOrUnion()) {
4877 bool AllVariantFieldsAreConst = true;
4878
Richard Smithdf8dc862012-03-29 19:00:10 +00004879 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004880 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4881 UE = FieldRecord->field_end();
4882 UI != UE; ++UI) {
4883 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004884
4885 if (!UnionFieldType.isConstQualified())
4886 AllVariantFieldsAreConst = false;
4887
Richard Smith9a561d52012-02-26 09:11:52 +00004888 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4889 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004890 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4891 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004892 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004893 }
4894
4895 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004896 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004897 FieldRecord->field_begin() != FieldRecord->field_end()) {
4898 if (Diagnose)
4899 S.Diag(FieldRecord->getLocation(),
4900 diag::note_deleted_default_ctor_all_const)
4901 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004902 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004903 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004904
Richard Smithdf8dc862012-03-29 19:00:10 +00004905 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004906 // This is technically non-conformant, but sanity demands it.
4907 return false;
4908 }
4909
Richard Smith517bb842012-07-18 03:51:16 +00004910 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4911 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004912 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004913 }
4914
4915 return false;
4916}
4917
4918/// C++11 [class.ctor] p5:
4919/// A defaulted default constructor for a class X is defined as deleted if
4920/// X is a union and all of its variant members are of const-qualified type.
4921bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004922 // This is a silly definition, because it gives an empty union a deleted
4923 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004924 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4925 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4926 if (Diagnose)
4927 S.Diag(MD->getParent()->getLocation(),
4928 diag::note_deleted_default_ctor_all_const)
4929 << MD->getParent() << /*not anonymous union*/0;
4930 return true;
4931 }
4932 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004933}
4934
4935/// Determine whether a defaulted special member function should be defined as
4936/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4937/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004938bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4939 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004940 if (MD->isInvalidDecl())
4941 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004942 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004943 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004944 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004945 return false;
4946
Richard Smith7d5088a2012-02-18 02:02:13 +00004947 // C++11 [expr.lambda.prim]p19:
4948 // The closure type associated with a lambda-expression has a
4949 // deleted (8.4.3) default constructor and a deleted copy
4950 // assignment operator.
4951 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004952 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4953 if (Diagnose)
4954 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004955 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004956 }
4957
Richard Smith5bdaac52012-04-02 20:59:25 +00004958 // For an anonymous struct or union, the copy and assignment special members
4959 // will never be used, so skip the check. For an anonymous union declared at
4960 // namespace scope, the constructor and destructor are used.
4961 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4962 RD->isAnonymousStructOrUnion())
4963 return false;
4964
Richard Smith6c4c36c2012-03-30 20:53:28 +00004965 // C++11 [class.copy]p7, p18:
4966 // If the class definition declares a move constructor or move assignment
4967 // operator, an implicitly declared copy constructor or copy assignment
4968 // operator is defined as deleted.
4969 if (MD->isImplicit() &&
4970 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4971 CXXMethodDecl *UserDeclaredMove = 0;
4972
4973 // In Microsoft mode, a user-declared move only causes the deletion of the
4974 // corresponding copy operation, not both copy operations.
4975 if (RD->hasUserDeclaredMoveConstructor() &&
4976 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4977 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004978
4979 // Find any user-declared move constructor.
4980 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4981 E = RD->ctor_end(); I != E; ++I) {
4982 if (I->isMoveConstructor()) {
4983 UserDeclaredMove = *I;
4984 break;
4985 }
4986 }
Richard Smith1c931be2012-04-02 18:40:40 +00004987 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004988 } else if (RD->hasUserDeclaredMoveAssignment() &&
4989 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4990 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004991
4992 // Find any user-declared move assignment operator.
4993 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4994 E = RD->method_end(); I != E; ++I) {
4995 if (I->isMoveAssignmentOperator()) {
4996 UserDeclaredMove = *I;
4997 break;
4998 }
4999 }
Richard Smith1c931be2012-04-02 18:40:40 +00005000 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005001 }
5002
5003 if (UserDeclaredMove) {
5004 Diag(UserDeclaredMove->getLocation(),
5005 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005006 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005007 << UserDeclaredMove->isMoveAssignmentOperator();
5008 return true;
5009 }
5010 }
Sean Hunte16da072011-10-10 06:18:57 +00005011
Richard Smith5bdaac52012-04-02 20:59:25 +00005012 // Do access control from the special member function
5013 ContextRAII MethodContext(*this, MD);
5014
Richard Smith9a561d52012-02-26 09:11:52 +00005015 // C++11 [class.dtor]p5:
5016 // -- for a virtual destructor, lookup of the non-array deallocation function
5017 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005018 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005019 FunctionDecl *OperatorDelete = 0;
5020 DeclarationName Name =
5021 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5022 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005023 OperatorDelete, false)) {
5024 if (Diagnose)
5025 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005026 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005027 }
Richard Smith9a561d52012-02-26 09:11:52 +00005028 }
5029
Richard Smith6c4c36c2012-03-30 20:53:28 +00005030 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005031
Sean Huntcdee3fe2011-05-11 22:34:38 +00005032 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005033 BE = RD->bases_end(); BI != BE; ++BI)
5034 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005035 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005036 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005037
5038 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005039 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00005040 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005041 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005042
5043 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005044 FE = RD->field_end(); FI != FE; ++FI)
5045 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005046 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005047 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005048
Richard Smith7d5088a2012-02-18 02:02:13 +00005049 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005050 return true;
5051
5052 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005053}
5054
Richard Smithac713512012-12-08 02:53:02 +00005055/// Perform lookup for a special member of the specified kind, and determine
5056/// whether it is trivial. If the triviality can be determined without the
5057/// lookup, skip it. This is intended for use when determining whether a
5058/// special member of a containing object is trivial, and thus does not ever
5059/// perform overload resolution for default constructors.
5060///
5061/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5062/// member that was most likely to be intended to be trivial, if any.
5063static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5064 Sema::CXXSpecialMember CSM, unsigned Quals,
5065 CXXMethodDecl **Selected) {
5066 if (Selected)
5067 *Selected = 0;
5068
5069 switch (CSM) {
5070 case Sema::CXXInvalid:
5071 llvm_unreachable("not a special member");
5072
5073 case Sema::CXXDefaultConstructor:
5074 // C++11 [class.ctor]p5:
5075 // A default constructor is trivial if:
5076 // - all the [direct subobjects] have trivial default constructors
5077 //
5078 // Note, no overload resolution is performed in this case.
5079 if (RD->hasTrivialDefaultConstructor())
5080 return true;
5081
5082 if (Selected) {
5083 // If there's a default constructor which could have been trivial, dig it
5084 // out. Otherwise, if there's any user-provided default constructor, point
5085 // to that as an example of why there's not a trivial one.
5086 CXXConstructorDecl *DefCtor = 0;
5087 if (RD->needsImplicitDefaultConstructor())
5088 S.DeclareImplicitDefaultConstructor(RD);
5089 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5090 CE = RD->ctor_end(); CI != CE; ++CI) {
5091 if (!CI->isDefaultConstructor())
5092 continue;
5093 DefCtor = *CI;
5094 if (!DefCtor->isUserProvided())
5095 break;
5096 }
5097
5098 *Selected = DefCtor;
5099 }
5100
5101 return false;
5102
5103 case Sema::CXXDestructor:
5104 // C++11 [class.dtor]p5:
5105 // A destructor is trivial if:
5106 // - all the direct [subobjects] have trivial destructors
5107 if (RD->hasTrivialDestructor())
5108 return true;
5109
5110 if (Selected) {
5111 if (RD->needsImplicitDestructor())
5112 S.DeclareImplicitDestructor(RD);
5113 *Selected = RD->getDestructor();
5114 }
5115
5116 return false;
5117
5118 case Sema::CXXCopyConstructor:
5119 // C++11 [class.copy]p12:
5120 // A copy constructor is trivial if:
5121 // - the constructor selected to copy each direct [subobject] is trivial
5122 if (RD->hasTrivialCopyConstructor()) {
5123 if (Quals == Qualifiers::Const)
5124 // We must either select the trivial copy constructor or reach an
5125 // ambiguity; no need to actually perform overload resolution.
5126 return true;
5127 } else if (!Selected) {
5128 return false;
5129 }
5130 // In C++98, we are not supposed to perform overload resolution here, but we
5131 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5132 // cases like B as having a non-trivial copy constructor:
5133 // struct A { template<typename T> A(T&); };
5134 // struct B { mutable A a; };
5135 goto NeedOverloadResolution;
5136
5137 case Sema::CXXCopyAssignment:
5138 // C++11 [class.copy]p25:
5139 // A copy assignment operator is trivial if:
5140 // - the assignment operator selected to copy each direct [subobject] is
5141 // trivial
5142 if (RD->hasTrivialCopyAssignment()) {
5143 if (Quals == Qualifiers::Const)
5144 return true;
5145 } else if (!Selected) {
5146 return false;
5147 }
5148 // In C++98, we are not supposed to perform overload resolution here, but we
5149 // treat that as a language defect.
5150 goto NeedOverloadResolution;
5151
5152 case Sema::CXXMoveConstructor:
5153 case Sema::CXXMoveAssignment:
5154 NeedOverloadResolution:
5155 Sema::SpecialMemberOverloadResult *SMOR =
5156 S.LookupSpecialMember(RD, CSM,
5157 Quals & Qualifiers::Const,
5158 Quals & Qualifiers::Volatile,
5159 /*RValueThis*/false, /*ConstThis*/false,
5160 /*VolatileThis*/false);
5161
5162 // The standard doesn't describe how to behave if the lookup is ambiguous.
5163 // We treat it as not making the member non-trivial, just like the standard
5164 // mandates for the default constructor. This should rarely matter, because
5165 // the member will also be deleted.
5166 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5167 return true;
5168
5169 if (!SMOR->getMethod()) {
5170 assert(SMOR->getKind() ==
5171 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5172 return false;
5173 }
5174
5175 // We deliberately don't check if we found a deleted special member. We're
5176 // not supposed to!
5177 if (Selected)
5178 *Selected = SMOR->getMethod();
5179 return SMOR->getMethod()->isTrivial();
5180 }
5181
5182 llvm_unreachable("unknown special method kind");
5183}
5184
Benjamin Kramera574c892013-02-15 12:30:38 +00005185static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005186 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5187 CI != CE; ++CI)
5188 if (!CI->isImplicit())
5189 return *CI;
5190
5191 // Look for constructor templates.
5192 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5193 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5194 if (CXXConstructorDecl *CD =
5195 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5196 return CD;
5197 }
5198
5199 return 0;
5200}
5201
5202/// The kind of subobject we are checking for triviality. The values of this
5203/// enumeration are used in diagnostics.
5204enum TrivialSubobjectKind {
5205 /// The subobject is a base class.
5206 TSK_BaseClass,
5207 /// The subobject is a non-static data member.
5208 TSK_Field,
5209 /// The object is actually the complete object.
5210 TSK_CompleteObject
5211};
5212
5213/// Check whether the special member selected for a given type would be trivial.
5214static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5215 QualType SubType,
5216 Sema::CXXSpecialMember CSM,
5217 TrivialSubobjectKind Kind,
5218 bool Diagnose) {
5219 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5220 if (!SubRD)
5221 return true;
5222
5223 CXXMethodDecl *Selected;
5224 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5225 Diagnose ? &Selected : 0))
5226 return true;
5227
5228 if (Diagnose) {
5229 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5230 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5231 << Kind << SubType.getUnqualifiedType();
5232 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5233 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5234 } else if (!Selected)
5235 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5236 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5237 else if (Selected->isUserProvided()) {
5238 if (Kind == TSK_CompleteObject)
5239 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5240 << Kind << SubType.getUnqualifiedType() << CSM;
5241 else {
5242 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5243 << Kind << SubType.getUnqualifiedType() << CSM;
5244 S.Diag(Selected->getLocation(), diag::note_declared_at);
5245 }
5246 } else {
5247 if (Kind != TSK_CompleteObject)
5248 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5249 << Kind << SubType.getUnqualifiedType() << CSM;
5250
5251 // Explain why the defaulted or deleted special member isn't trivial.
5252 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5253 }
5254 }
5255
5256 return false;
5257}
5258
5259/// Check whether the members of a class type allow a special member to be
5260/// trivial.
5261static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5262 Sema::CXXSpecialMember CSM,
5263 bool ConstArg, bool Diagnose) {
5264 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5265 FE = RD->field_end(); FI != FE; ++FI) {
5266 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5267 continue;
5268
5269 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5270
5271 // Pretend anonymous struct or union members are members of this class.
5272 if (FI->isAnonymousStructOrUnion()) {
5273 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5274 CSM, ConstArg, Diagnose))
5275 return false;
5276 continue;
5277 }
5278
5279 // C++11 [class.ctor]p5:
5280 // A default constructor is trivial if [...]
5281 // -- no non-static data member of its class has a
5282 // brace-or-equal-initializer
5283 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5284 if (Diagnose)
5285 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5286 return false;
5287 }
5288
5289 // Objective C ARC 4.3.5:
5290 // [...] nontrivally ownership-qualified types are [...] not trivially
5291 // default constructible, copy constructible, move constructible, copy
5292 // assignable, move assignable, or destructible [...]
5293 if (S.getLangOpts().ObjCAutoRefCount &&
5294 FieldType.hasNonTrivialObjCLifetime()) {
5295 if (Diagnose)
5296 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5297 << RD << FieldType.getObjCLifetime();
5298 return false;
5299 }
5300
5301 if (ConstArg && !FI->isMutable())
5302 FieldType.addConst();
5303 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5304 TSK_Field, Diagnose))
5305 return false;
5306 }
5307
5308 return true;
5309}
5310
5311/// Diagnose why the specified class does not have a trivial special member of
5312/// the given kind.
5313void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5314 QualType Ty = Context.getRecordType(RD);
5315 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5316 Ty.addConst();
5317
5318 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5319 TSK_CompleteObject, /*Diagnose*/true);
5320}
5321
5322/// Determine whether a defaulted or deleted special member function is trivial,
5323/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5324/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5325bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5326 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005327 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5328
5329 CXXRecordDecl *RD = MD->getParent();
5330
5331 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005332
5333 // C++11 [class.copy]p12, p25:
5334 // A [special member] is trivial if its declared parameter type is the same
5335 // as if it had been implicitly declared [...]
5336 switch (CSM) {
5337 case CXXDefaultConstructor:
5338 case CXXDestructor:
5339 // Trivial default constructors and destructors cannot have parameters.
5340 break;
5341
5342 case CXXCopyConstructor:
5343 case CXXCopyAssignment: {
5344 // Trivial copy operations always have const, non-volatile parameter types.
5345 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005346 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005347 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5348 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5349 if (Diagnose)
5350 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5351 << Param0->getSourceRange() << Param0->getType()
5352 << Context.getLValueReferenceType(
5353 Context.getRecordType(RD).withConst());
5354 return false;
5355 }
5356 break;
5357 }
5358
5359 case CXXMoveConstructor:
5360 case CXXMoveAssignment: {
5361 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005362 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005363 const RValueReferenceType *RT =
5364 Param0->getType()->getAs<RValueReferenceType>();
5365 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5366 if (Diagnose)
5367 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5368 << Param0->getSourceRange() << Param0->getType()
5369 << Context.getRValueReferenceType(Context.getRecordType(RD));
5370 return false;
5371 }
5372 break;
5373 }
5374
5375 case CXXInvalid:
5376 llvm_unreachable("not a special member");
5377 }
5378
5379 // FIXME: We require that the parameter-declaration-clause is equivalent to
5380 // that of an implicit declaration, not just that the declared parameter type
5381 // matches, in order to prevent absuridities like a function simultaneously
5382 // being a trivial copy constructor and a non-trivial default constructor.
5383 // This issue has not yet been assigned a core issue number.
5384 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5385 if (Diagnose)
5386 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5387 diag::note_nontrivial_default_arg)
5388 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5389 return false;
5390 }
5391 if (MD->isVariadic()) {
5392 if (Diagnose)
5393 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5394 return false;
5395 }
5396
5397 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5398 // A copy/move [constructor or assignment operator] is trivial if
5399 // -- the [member] selected to copy/move each direct base class subobject
5400 // is trivial
5401 //
5402 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5403 // A [default constructor or destructor] is trivial if
5404 // -- all the direct base classes have trivial [default constructors or
5405 // destructors]
5406 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5407 BE = RD->bases_end(); BI != BE; ++BI)
5408 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5409 ConstArg ? BI->getType().withConst()
5410 : BI->getType(),
5411 CSM, TSK_BaseClass, Diagnose))
5412 return false;
5413
5414 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5415 // A copy/move [constructor or assignment operator] for a class X is
5416 // trivial if
5417 // -- for each non-static data member of X that is of class type (or array
5418 // thereof), the constructor selected to copy/move that member is
5419 // trivial
5420 //
5421 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5422 // A [default constructor or destructor] is trivial if
5423 // -- for all of the non-static data members of its class that are of class
5424 // type (or array thereof), each such class has a trivial [default
5425 // constructor or destructor]
5426 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5427 return false;
5428
5429 // C++11 [class.dtor]p5:
5430 // A destructor is trivial if [...]
5431 // -- the destructor is not virtual
5432 if (CSM == CXXDestructor && MD->isVirtual()) {
5433 if (Diagnose)
5434 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5435 return false;
5436 }
5437
5438 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5439 // A [special member] for class X is trivial if [...]
5440 // -- class X has no virtual functions and no virtual base classes
5441 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5442 if (!Diagnose)
5443 return false;
5444
5445 if (RD->getNumVBases()) {
5446 // Check for virtual bases. We already know that the corresponding
5447 // member in all bases is trivial, so vbases must all be direct.
5448 CXXBaseSpecifier &BS = *RD->vbases_begin();
5449 assert(BS.isVirtual());
5450 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5451 return false;
5452 }
5453
5454 // Must have a virtual method.
5455 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5456 ME = RD->method_end(); MI != ME; ++MI) {
5457 if (MI->isVirtual()) {
5458 SourceLocation MLoc = MI->getLocStart();
5459 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5460 return false;
5461 }
5462 }
5463
5464 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5465 }
5466
5467 // Looks like it's trivial!
5468 return true;
5469}
5470
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005471/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005472namespace {
5473 struct FindHiddenVirtualMethodData {
5474 Sema *S;
5475 CXXMethodDecl *Method;
5476 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005477 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005478 };
5479}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005480
David Blaikie5f750682012-10-19 00:53:08 +00005481/// \brief Check whether any most overriden method from MD in Methods
5482static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5483 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5484 if (MD->size_overridden_methods() == 0)
5485 return Methods.count(MD->getCanonicalDecl());
5486 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5487 E = MD->end_overridden_methods();
5488 I != E; ++I)
5489 if (CheckMostOverridenMethods(*I, Methods))
5490 return true;
5491 return false;
5492}
5493
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005494/// \brief Member lookup function that determines whether a given C++
5495/// method overloads virtual methods in a base class without overriding any,
5496/// to be used with CXXRecordDecl::lookupInBases().
5497static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5498 CXXBasePath &Path,
5499 void *UserData) {
5500 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5501
5502 FindHiddenVirtualMethodData &Data
5503 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5504
5505 DeclarationName Name = Data.Method->getDeclName();
5506 assert(Name.getNameKind() == DeclarationName::Identifier);
5507
5508 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005509 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005510 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005511 !Path.Decls.empty();
5512 Path.Decls = Path.Decls.slice(1)) {
5513 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005514 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005515 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005516 foundSameNameMethod = true;
5517 // Interested only in hidden virtual methods.
5518 if (!MD->isVirtual())
5519 continue;
5520 // If the method we are checking overrides a method from its base
5521 // don't warn about the other overloaded methods.
5522 if (!Data.S->IsOverload(Data.Method, MD, false))
5523 return true;
5524 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005525 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005526 overloadedMethods.push_back(MD);
5527 }
5528 }
5529
5530 if (foundSameNameMethod)
5531 Data.OverloadedMethods.append(overloadedMethods.begin(),
5532 overloadedMethods.end());
5533 return foundSameNameMethod;
5534}
5535
David Blaikie5f750682012-10-19 00:53:08 +00005536/// \brief Add the most overriden methods from MD to Methods
5537static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5538 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5539 if (MD->size_overridden_methods() == 0)
5540 Methods.insert(MD->getCanonicalDecl());
5541 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5542 E = MD->end_overridden_methods();
5543 I != E; ++I)
5544 AddMostOverridenMethods(*I, Methods);
5545}
5546
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005547/// \brief See if a method overloads virtual methods in a base class without
5548/// overriding any.
5549void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5550 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005551 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005552 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005553 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005554 return;
5555
5556 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5557 /*bool RecordPaths=*/false,
5558 /*bool DetectVirtual=*/false);
5559 FindHiddenVirtualMethodData Data;
5560 Data.Method = MD;
5561 Data.S = this;
5562
5563 // Keep the base methods that were overriden or introduced in the subclass
5564 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005565 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5566 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5567 NamedDecl *ND = *I;
5568 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005569 ND = shad->getTargetDecl();
5570 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5571 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005572 }
5573
5574 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5575 !Data.OverloadedMethods.empty()) {
5576 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5577 << MD << (Data.OverloadedMethods.size() > 1);
5578
5579 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5580 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005581 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005582 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005583 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5584 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005585 }
5586 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005587}
5588
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005589void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005590 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005591 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005592 SourceLocation RBrac,
5593 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005594 if (!TagDecl)
5595 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005596
Douglas Gregor42af25f2009-05-11 19:58:34 +00005597 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005598
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005599 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5600 if (l->getKind() != AttributeList::AT_Visibility)
5601 continue;
5602 l->setInvalid();
5603 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5604 l->getName();
5605 }
5606
David Blaikie77b6de02011-09-22 02:58:26 +00005607 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005608 // strict aliasing violation!
5609 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005610 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005611
Douglas Gregor23c94db2010-07-02 17:43:08 +00005612 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005613 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005614}
5615
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005616/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5617/// special functions, such as the default constructor, copy
5618/// constructor, or destructor, to the given C++ class (C++
5619/// [special]p1). This routine can only be executed just before the
5620/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005621void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005622 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005623 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005624
Richard Smithbc2a35d2012-12-08 08:32:28 +00005625 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005626 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005627
Richard Smithbc2a35d2012-12-08 08:32:28 +00005628 // If the properties or semantics of the copy constructor couldn't be
5629 // determined while the class was being declared, force a declaration
5630 // of it now.
5631 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5632 DeclareImplicitCopyConstructor(ClassDecl);
5633 }
5634
Richard Smith80ad52f2013-01-02 11:42:31 +00005635 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005636 ++ASTContext::NumImplicitMoveConstructors;
5637
Richard Smithbc2a35d2012-12-08 08:32:28 +00005638 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5639 DeclareImplicitMoveConstructor(ClassDecl);
5640 }
5641
Douglas Gregora376d102010-07-02 21:50:04 +00005642 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5643 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005644
5645 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005646 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005647 // it shows up in the right place in the vtable and that we diagnose
5648 // problems with the implicit exception specification.
5649 if (ClassDecl->isDynamicClass() ||
5650 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005651 DeclareImplicitCopyAssignment(ClassDecl);
5652 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005653
Richard Smith80ad52f2013-01-02 11:42:31 +00005654 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005655 ++ASTContext::NumImplicitMoveAssignmentOperators;
5656
5657 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005658 if (ClassDecl->isDynamicClass() ||
5659 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005660 DeclareImplicitMoveAssignment(ClassDecl);
5661 }
5662
Douglas Gregor4923aa22010-07-02 20:37:36 +00005663 if (!ClassDecl->hasUserDeclaredDestructor()) {
5664 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005665
5666 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005667 // have to declare the destructor immediately. This ensures that, e.g., it
5668 // shows up in the right place in the vtable and that we diagnose problems
5669 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005670 if (ClassDecl->isDynamicClass() ||
5671 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005672 DeclareImplicitDestructor(ClassDecl);
5673 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005674}
5675
Francois Pichet8387e2a2011-04-22 22:18:13 +00005676void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5677 if (!D)
5678 return;
5679
5680 int NumParamList = D->getNumTemplateParameterLists();
5681 for (int i = 0; i < NumParamList; i++) {
5682 TemplateParameterList* Params = D->getTemplateParameterList(i);
5683 for (TemplateParameterList::iterator Param = Params->begin(),
5684 ParamEnd = Params->end();
5685 Param != ParamEnd; ++Param) {
5686 NamedDecl *Named = cast<NamedDecl>(*Param);
5687 if (Named->getDeclName()) {
5688 S->AddDecl(Named);
5689 IdResolver.AddDecl(Named);
5690 }
5691 }
5692 }
5693}
5694
John McCalld226f652010-08-21 09:40:31 +00005695void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005696 if (!D)
5697 return;
5698
5699 TemplateParameterList *Params = 0;
5700 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5701 Params = Template->getTemplateParameters();
5702 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5703 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5704 Params = PartialSpec->getTemplateParameters();
5705 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005706 return;
5707
Douglas Gregor6569d682009-05-27 23:11:45 +00005708 for (TemplateParameterList::iterator Param = Params->begin(),
5709 ParamEnd = Params->end();
5710 Param != ParamEnd; ++Param) {
5711 NamedDecl *Named = cast<NamedDecl>(*Param);
5712 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005713 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005714 IdResolver.AddDecl(Named);
5715 }
5716 }
5717}
5718
John McCalld226f652010-08-21 09:40:31 +00005719void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005720 if (!RecordD) return;
5721 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005722 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005723 PushDeclContext(S, Record);
5724}
5725
John McCalld226f652010-08-21 09:40:31 +00005726void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005727 if (!RecordD) return;
5728 PopDeclContext();
5729}
5730
Douglas Gregor72b505b2008-12-16 21:30:33 +00005731/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5732/// parsing a top-level (non-nested) C++ class, and we are now
5733/// parsing those parts of the given Method declaration that could
5734/// not be parsed earlier (C++ [class.mem]p2), such as default
5735/// arguments. This action should enter the scope of the given
5736/// Method declaration as if we had just parsed the qualified method
5737/// name. However, it should not bring the parameters into scope;
5738/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005739void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005740}
5741
5742/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5743/// C++ method declaration. We're (re-)introducing the given
5744/// function parameter into scope for use in parsing later parts of
5745/// the method declaration. For example, we could see an
5746/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005747void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005748 if (!ParamD)
5749 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005750
John McCalld226f652010-08-21 09:40:31 +00005751 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005752
5753 // If this parameter has an unparsed default argument, clear it out
5754 // to make way for the parsed default argument.
5755 if (Param->hasUnparsedDefaultArg())
5756 Param->setDefaultArg(0);
5757
John McCalld226f652010-08-21 09:40:31 +00005758 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005759 if (Param->getDeclName())
5760 IdResolver.AddDecl(Param);
5761}
5762
5763/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5764/// processing the delayed method declaration for Method. The method
5765/// declaration is now considered finished. There may be a separate
5766/// ActOnStartOfFunctionDef action later (not necessarily
5767/// immediately!) for this method, if it was also defined inside the
5768/// class body.
John McCalld226f652010-08-21 09:40:31 +00005769void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005770 if (!MethodD)
5771 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005772
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005773 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005774
John McCalld226f652010-08-21 09:40:31 +00005775 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005776
5777 // Now that we have our default arguments, check the constructor
5778 // again. It could produce additional diagnostics or affect whether
5779 // the class has implicitly-declared destructors, among other
5780 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005781 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5782 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005783
5784 // Check the default arguments, which we may have added.
5785 if (!Method->isInvalidDecl())
5786 CheckCXXDefaultArguments(Method);
5787}
5788
Douglas Gregor42a552f2008-11-05 20:51:48 +00005789/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005790/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005791/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005792/// emit diagnostics and set the invalid bit to true. In any case, the type
5793/// will be updated to reflect a well-formed type for the constructor and
5794/// returned.
5795QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005796 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005797 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005798
5799 // C++ [class.ctor]p3:
5800 // A constructor shall not be virtual (10.3) or static (9.4). A
5801 // constructor can be invoked for a const, volatile or const
5802 // volatile object. A constructor shall not be declared const,
5803 // volatile, or const volatile (9.3.2).
5804 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005805 if (!D.isInvalidType())
5806 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5807 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5808 << SourceRange(D.getIdentifierLoc());
5809 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005810 }
John McCalld931b082010-08-26 03:08:43 +00005811 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005812 if (!D.isInvalidType())
5813 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5814 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5815 << SourceRange(D.getIdentifierLoc());
5816 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005817 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005818 }
Mike Stump1eb44332009-09-09 15:08:12 +00005819
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005820 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005821 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005822 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005823 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5824 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005825 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005826 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5827 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005828 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005829 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5830 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005831 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005832 }
Mike Stump1eb44332009-09-09 15:08:12 +00005833
Douglas Gregorc938c162011-01-26 05:01:58 +00005834 // C++0x [class.ctor]p4:
5835 // A constructor shall not be declared with a ref-qualifier.
5836 if (FTI.hasRefQualifier()) {
5837 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5838 << FTI.RefQualifierIsLValueRef
5839 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5840 D.setInvalidType();
5841 }
5842
Douglas Gregor42a552f2008-11-05 20:51:48 +00005843 // Rebuild the function type "R" without any type qualifiers (in
5844 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005845 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005846 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005847 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5848 return R;
5849
5850 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5851 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005852 EPI.RefQualifier = RQ_None;
5853
Richard Smith07b0fdc2013-03-18 21:12:30 +00005854 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005855}
5856
Douglas Gregor72b505b2008-12-16 21:30:33 +00005857/// CheckConstructor - Checks a fully-formed constructor for
5858/// well-formedness, issuing any diagnostics required. Returns true if
5859/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005860void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005861 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005862 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5863 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005864 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005865
5866 // C++ [class.copy]p3:
5867 // A declaration of a constructor for a class X is ill-formed if
5868 // its first parameter is of type (optionally cv-qualified) X and
5869 // either there are no other parameters or else all other
5870 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005871 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005872 ((Constructor->getNumParams() == 1) ||
5873 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005874 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5875 Constructor->getTemplateSpecializationKind()
5876 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005877 QualType ParamType = Constructor->getParamDecl(0)->getType();
5878 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5879 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005880 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005881 const char *ConstRef
5882 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5883 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005884 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005885 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005886
5887 // FIXME: Rather that making the constructor invalid, we should endeavor
5888 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005889 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005890 }
5891 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005892}
5893
John McCall15442822010-08-04 01:04:25 +00005894/// CheckDestructor - Checks a fully-formed destructor definition for
5895/// well-formedness, issuing any diagnostics required. Returns true
5896/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005897bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005898 CXXRecordDecl *RD = Destructor->getParent();
5899
5900 if (Destructor->isVirtual()) {
5901 SourceLocation Loc;
5902
5903 if (!Destructor->isImplicit())
5904 Loc = Destructor->getLocation();
5905 else
5906 Loc = RD->getLocation();
5907
5908 // If we have a virtual destructor, look up the deallocation function
5909 FunctionDecl *OperatorDelete = 0;
5910 DeclarationName Name =
5911 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005912 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005913 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005914
Eli Friedman5f2987c2012-02-02 03:46:19 +00005915 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005916
5917 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005918 }
Anders Carlsson37909802009-11-30 21:24:50 +00005919
5920 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005921}
5922
Mike Stump1eb44332009-09-09 15:08:12 +00005923static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005924FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5925 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5926 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005927 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005928}
5929
Douglas Gregor42a552f2008-11-05 20:51:48 +00005930/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5931/// the well-formednes of the destructor declarator @p D with type @p
5932/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005933/// emit diagnostics and set the declarator to invalid. Even if this happens,
5934/// will be updated to reflect a well-formed type for the destructor and
5935/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005936QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005937 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005938 // C++ [class.dtor]p1:
5939 // [...] A typedef-name that names a class is a class-name
5940 // (7.1.3); however, a typedef-name that names a class shall not
5941 // be used as the identifier in the declarator for a destructor
5942 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005943 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005944 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005945 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005946 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005947 else if (const TemplateSpecializationType *TST =
5948 DeclaratorType->getAs<TemplateSpecializationType>())
5949 if (TST->isTypeAlias())
5950 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5951 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005952
5953 // C++ [class.dtor]p2:
5954 // A destructor is used to destroy objects of its class type. A
5955 // destructor takes no parameters, and no return type can be
5956 // specified for it (not even void). The address of a destructor
5957 // shall not be taken. A destructor shall not be static. A
5958 // destructor can be invoked for a const, volatile or const
5959 // volatile object. A destructor shall not be declared const,
5960 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005961 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005962 if (!D.isInvalidType())
5963 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5964 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005965 << SourceRange(D.getIdentifierLoc())
5966 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5967
John McCalld931b082010-08-26 03:08:43 +00005968 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005969 }
Chris Lattner65401802009-04-25 08:28:21 +00005970 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005971 // Destructors don't have return types, but the parser will
5972 // happily parse something like:
5973 //
5974 // class X {
5975 // float ~X();
5976 // };
5977 //
5978 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005979 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5980 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5981 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005982 }
Mike Stump1eb44332009-09-09 15:08:12 +00005983
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005984 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005985 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005986 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005987 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5988 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005989 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005990 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5991 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005992 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005993 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5994 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005995 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005996 }
5997
Douglas Gregorc938c162011-01-26 05:01:58 +00005998 // C++0x [class.dtor]p2:
5999 // A destructor shall not be declared with a ref-qualifier.
6000 if (FTI.hasRefQualifier()) {
6001 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6002 << FTI.RefQualifierIsLValueRef
6003 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6004 D.setInvalidType();
6005 }
6006
Douglas Gregor42a552f2008-11-05 20:51:48 +00006007 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006008 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006009 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6010
6011 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006012 FTI.freeArgs();
6013 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006014 }
6015
Mike Stump1eb44332009-09-09 15:08:12 +00006016 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006017 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006018 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006019 D.setInvalidType();
6020 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006021
6022 // Rebuild the function type "R" without any type qualifiers or
6023 // parameters (in case any of the errors above fired) and with
6024 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006025 // types.
John McCalle23cf432010-12-14 08:05:40 +00006026 if (!D.isInvalidType())
6027 return R;
6028
Douglas Gregord92ec472010-07-01 05:10:53 +00006029 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006030 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6031 EPI.Variadic = false;
6032 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006033 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006034 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006035}
6036
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006037/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6038/// well-formednes of the conversion function declarator @p D with
6039/// type @p R. If there are any errors in the declarator, this routine
6040/// will emit diagnostics and return true. Otherwise, it will return
6041/// false. Either way, the type @p R will be updated to reflect a
6042/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006043void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006044 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006045 // C++ [class.conv.fct]p1:
6046 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006047 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006048 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006049 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006050 if (!D.isInvalidType())
6051 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6052 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6053 << SourceRange(D.getIdentifierLoc());
6054 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006055 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006056 }
John McCalla3f81372010-04-13 00:04:31 +00006057
6058 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6059
Chris Lattner6e475012009-04-25 08:35:12 +00006060 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006061 // Conversion functions don't have return types, but the parser will
6062 // happily parse something like:
6063 //
6064 // class X {
6065 // float operator bool();
6066 // };
6067 //
6068 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006069 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6070 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6071 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006072 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006073 }
6074
John McCalla3f81372010-04-13 00:04:31 +00006075 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6076
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006077 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006078 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006079 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6080
6081 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006082 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006083 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006084 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006085 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006086 D.setInvalidType();
6087 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006088
John McCalla3f81372010-04-13 00:04:31 +00006089 // Diagnose "&operator bool()" and other such nonsense. This
6090 // is actually a gcc extension which we don't support.
6091 if (Proto->getResultType() != ConvType) {
6092 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6093 << Proto->getResultType();
6094 D.setInvalidType();
6095 ConvType = Proto->getResultType();
6096 }
6097
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006098 // C++ [class.conv.fct]p4:
6099 // The conversion-type-id shall not represent a function type nor
6100 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006101 if (ConvType->isArrayType()) {
6102 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6103 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006104 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006105 } else if (ConvType->isFunctionType()) {
6106 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6107 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006108 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006109 }
6110
6111 // Rebuild the function type "R" without any parameters (in case any
6112 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006113 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006114 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006115 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006116
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006117 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006118 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006119 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006120 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006121 diag::warn_cxx98_compat_explicit_conversion_functions :
6122 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006123 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006124}
6125
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006126/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6127/// the declaration of the given C++ conversion function. This routine
6128/// is responsible for recording the conversion function in the C++
6129/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006130Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006131 assert(Conversion && "Expected to receive a conversion function declaration");
6132
Douglas Gregor9d350972008-12-12 08:25:50 +00006133 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006134
6135 // Make sure we aren't redeclaring the conversion function.
6136 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006137
6138 // C++ [class.conv.fct]p1:
6139 // [...] A conversion function is never used to convert a
6140 // (possibly cv-qualified) object to the (possibly cv-qualified)
6141 // same object type (or a reference to it), to a (possibly
6142 // cv-qualified) base class of that type (or a reference to it),
6143 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006144 // FIXME: Suppress this warning if the conversion function ends up being a
6145 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006146 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006147 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006148 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006149 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006150 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6151 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006152 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006153 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006154 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6155 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006156 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006157 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006158 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006159 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006160 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006161 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006162 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006163 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006164 }
6165
Douglas Gregore80622f2010-09-29 04:25:11 +00006166 if (FunctionTemplateDecl *ConversionTemplate
6167 = Conversion->getDescribedFunctionTemplate())
6168 return ConversionTemplate;
6169
John McCalld226f652010-08-21 09:40:31 +00006170 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006171}
6172
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006173//===----------------------------------------------------------------------===//
6174// Namespace Handling
6175//===----------------------------------------------------------------------===//
6176
Richard Smithd1a55a62012-10-04 22:13:39 +00006177/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6178/// reopened.
6179static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6180 SourceLocation Loc,
6181 IdentifierInfo *II, bool *IsInline,
6182 NamespaceDecl *PrevNS) {
6183 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006184
Richard Smithc969e6a2012-10-05 01:46:25 +00006185 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6186 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6187 // inline namespaces, with the intention of bringing names into namespace std.
6188 //
6189 // We support this just well enough to get that case working; this is not
6190 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006191 if (*IsInline && II && II->getName().startswith("__atomic") &&
6192 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006193 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006194 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6195 NS = NS->getPreviousDecl())
6196 NS->setInline(*IsInline);
6197 // Patch up the lookup table for the containing namespace. This isn't really
6198 // correct, but it's good enough for this particular case.
6199 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6200 E = PrevNS->decls_end(); I != E; ++I)
6201 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6202 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6203 return;
6204 }
6205
6206 if (PrevNS->isInline())
6207 // The user probably just forgot the 'inline', so suggest that it
6208 // be added back.
6209 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6210 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6211 else
6212 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6213 << IsInline;
6214
6215 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6216 *IsInline = PrevNS->isInline();
6217}
John McCallea318642010-08-26 09:15:37 +00006218
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006219/// ActOnStartNamespaceDef - This is called at the start of a namespace
6220/// definition.
John McCalld226f652010-08-21 09:40:31 +00006221Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006222 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006223 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006224 SourceLocation IdentLoc,
6225 IdentifierInfo *II,
6226 SourceLocation LBrace,
6227 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006228 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6229 // For anonymous namespace, take the location of the left brace.
6230 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006231 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006232 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006233 bool IsStd = false;
6234 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006235 Scope *DeclRegionScope = NamespcScope->getParent();
6236
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006237 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006238 if (II) {
6239 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006240 // The identifier in an original-namespace-definition shall not
6241 // have been previously defined in the declarative region in
6242 // which the original-namespace-definition appears. The
6243 // identifier in an original-namespace-definition is the name of
6244 // the namespace. Subsequently in that declarative region, it is
6245 // treated as an original-namespace-name.
6246 //
6247 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006248 // look through using directives, just look for any ordinary names.
6249
6250 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006251 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6252 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006253 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006254 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6255 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6256 ++I) {
6257 if ((*I)->getIdentifierNamespace() & IDNS) {
6258 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006259 break;
6260 }
6261 }
6262
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006263 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6264
6265 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006266 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006267 if (IsInline != PrevNS->isInline())
6268 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6269 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006270 } else if (PrevDecl) {
6271 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006272 Diag(Loc, diag::err_redefinition_different_kind)
6273 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006274 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006275 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006276 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006277 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006278 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006279 // This is the first "real" definition of the namespace "std", so update
6280 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006281 PrevNS = getStdNamespace();
6282 IsStd = true;
6283 AddToKnown = !IsInline;
6284 } else {
6285 // We've seen this namespace for the first time.
6286 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006287 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006288 } else {
John McCall9aeed322009-10-01 00:25:31 +00006289 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006290
6291 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006292 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006293 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006294 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006295 } else {
6296 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006297 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006298 }
6299
Richard Smithd1a55a62012-10-04 22:13:39 +00006300 if (PrevNS && IsInline != PrevNS->isInline())
6301 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6302 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006303 }
6304
6305 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6306 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006307 if (IsInvalid)
6308 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006309
6310 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006311
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006312 // FIXME: Should we be merging attributes?
6313 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006314 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006315
6316 if (IsStd)
6317 StdNamespace = Namespc;
6318 if (AddToKnown)
6319 KnownNamespaces[Namespc] = false;
6320
6321 if (II) {
6322 PushOnScopeChains(Namespc, DeclRegionScope);
6323 } else {
6324 // Link the anonymous namespace into its parent.
6325 DeclContext *Parent = CurContext->getRedeclContext();
6326 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6327 TU->setAnonymousNamespace(Namespc);
6328 } else {
6329 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006330 }
John McCall9aeed322009-10-01 00:25:31 +00006331
Douglas Gregora4181472010-03-24 00:46:35 +00006332 CurContext->addDecl(Namespc);
6333
John McCall9aeed322009-10-01 00:25:31 +00006334 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6335 // behaves as if it were replaced by
6336 // namespace unique { /* empty body */ }
6337 // using namespace unique;
6338 // namespace unique { namespace-body }
6339 // where all occurrences of 'unique' in a translation unit are
6340 // replaced by the same identifier and this identifier differs
6341 // from all other identifiers in the entire program.
6342
6343 // We just create the namespace with an empty name and then add an
6344 // implicit using declaration, just like the standard suggests.
6345 //
6346 // CodeGen enforces the "universally unique" aspect by giving all
6347 // declarations semantically contained within an anonymous
6348 // namespace internal linkage.
6349
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006350 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006351 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006352 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006353 /* 'using' */ LBrace,
6354 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006355 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006356 /* identifier */ SourceLocation(),
6357 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006358 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006359 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006360 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006361 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006362 }
6363
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006364 ActOnDocumentableDecl(Namespc);
6365
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006366 // Although we could have an invalid decl (i.e. the namespace name is a
6367 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006368 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6369 // for the namespace has the declarations that showed up in that particular
6370 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006371 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006372 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006373}
6374
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006375/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6376/// is a namespace alias, returns the namespace it points to.
6377static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6378 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6379 return AD->getNamespace();
6380 return dyn_cast_or_null<NamespaceDecl>(D);
6381}
6382
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006383/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6384/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006385void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006386 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6387 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006388 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006389 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006390 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006391 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006392}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006393
John McCall384aff82010-08-25 07:42:41 +00006394CXXRecordDecl *Sema::getStdBadAlloc() const {
6395 return cast_or_null<CXXRecordDecl>(
6396 StdBadAlloc.get(Context.getExternalSource()));
6397}
6398
6399NamespaceDecl *Sema::getStdNamespace() const {
6400 return cast_or_null<NamespaceDecl>(
6401 StdNamespace.get(Context.getExternalSource()));
6402}
6403
Douglas Gregor66992202010-06-29 17:53:46 +00006404/// \brief Retrieve the special "std" namespace, which may require us to
6405/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006406NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006407 if (!StdNamespace) {
6408 // The "std" namespace has not yet been defined, so build one implicitly.
6409 StdNamespace = NamespaceDecl::Create(Context,
6410 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006411 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006412 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006413 &PP.getIdentifierTable().get("std"),
6414 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006415 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006416 }
6417
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006418 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006419}
6420
Sebastian Redl395e04d2012-01-17 22:49:33 +00006421bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006422 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006423 "Looking for std::initializer_list outside of C++.");
6424
6425 // We're looking for implicit instantiations of
6426 // template <typename E> class std::initializer_list.
6427
6428 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6429 return false;
6430
Sebastian Redl84760e32012-01-17 22:49:58 +00006431 ClassTemplateDecl *Template = 0;
6432 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006433
Sebastian Redl84760e32012-01-17 22:49:58 +00006434 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006435
Sebastian Redl84760e32012-01-17 22:49:58 +00006436 ClassTemplateSpecializationDecl *Specialization =
6437 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6438 if (!Specialization)
6439 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006440
Sebastian Redl84760e32012-01-17 22:49:58 +00006441 Template = Specialization->getSpecializedTemplate();
6442 Arguments = Specialization->getTemplateArgs().data();
6443 } else if (const TemplateSpecializationType *TST =
6444 Ty->getAs<TemplateSpecializationType>()) {
6445 Template = dyn_cast_or_null<ClassTemplateDecl>(
6446 TST->getTemplateName().getAsTemplateDecl());
6447 Arguments = TST->getArgs();
6448 }
6449 if (!Template)
6450 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006451
6452 if (!StdInitializerList) {
6453 // Haven't recognized std::initializer_list yet, maybe this is it.
6454 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6455 if (TemplateClass->getIdentifier() !=
6456 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006457 !getStdNamespace()->InEnclosingNamespaceSetOf(
6458 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006459 return false;
6460 // This is a template called std::initializer_list, but is it the right
6461 // template?
6462 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006463 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006464 return false;
6465 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6466 return false;
6467
6468 // It's the right template.
6469 StdInitializerList = Template;
6470 }
6471
6472 if (Template != StdInitializerList)
6473 return false;
6474
6475 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006476 if (Element)
6477 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006478 return true;
6479}
6480
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006481static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6482 NamespaceDecl *Std = S.getStdNamespace();
6483 if (!Std) {
6484 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6485 return 0;
6486 }
6487
6488 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6489 Loc, Sema::LookupOrdinaryName);
6490 if (!S.LookupQualifiedName(Result, Std)) {
6491 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6492 return 0;
6493 }
6494 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6495 if (!Template) {
6496 Result.suppressDiagnostics();
6497 // We found something weird. Complain about the first thing we found.
6498 NamedDecl *Found = *Result.begin();
6499 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6500 return 0;
6501 }
6502
6503 // We found some template called std::initializer_list. Now verify that it's
6504 // correct.
6505 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006506 if (Params->getMinRequiredArguments() != 1 ||
6507 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006508 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6509 return 0;
6510 }
6511
6512 return Template;
6513}
6514
6515QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6516 if (!StdInitializerList) {
6517 StdInitializerList = LookupStdInitializerList(*this, Loc);
6518 if (!StdInitializerList)
6519 return QualType();
6520 }
6521
6522 TemplateArgumentListInfo Args(Loc, Loc);
6523 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6524 Context.getTrivialTypeSourceInfo(Element,
6525 Loc)));
6526 return Context.getCanonicalType(
6527 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6528}
6529
Sebastian Redl98d36062012-01-17 22:50:14 +00006530bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6531 // C++ [dcl.init.list]p2:
6532 // A constructor is an initializer-list constructor if its first parameter
6533 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6534 // std::initializer_list<E> for some type E, and either there are no other
6535 // parameters or else all other parameters have default arguments.
6536 if (Ctor->getNumParams() < 1 ||
6537 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6538 return false;
6539
6540 QualType ArgType = Ctor->getParamDecl(0)->getType();
6541 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6542 ArgType = RT->getPointeeType().getUnqualifiedType();
6543
6544 return isStdInitializerList(ArgType, 0);
6545}
6546
Douglas Gregor9172aa62011-03-26 22:25:30 +00006547/// \brief Determine whether a using statement is in a context where it will be
6548/// apply in all contexts.
6549static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6550 switch (CurContext->getDeclKind()) {
6551 case Decl::TranslationUnit:
6552 return true;
6553 case Decl::LinkageSpec:
6554 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6555 default:
6556 return false;
6557 }
6558}
6559
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006560namespace {
6561
6562// Callback to only accept typo corrections that are namespaces.
6563class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6564 public:
6565 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6566 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6567 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6568 }
6569 return false;
6570 }
6571};
6572
6573}
6574
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006575static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6576 CXXScopeSpec &SS,
6577 SourceLocation IdentLoc,
6578 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006579 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006580 R.clear();
6581 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006582 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006583 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006584 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6585 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006586 if (DeclContext *DC = S.computeDeclContext(SS, false))
6587 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6588 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006589 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6590 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006591 else
6592 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6593 << Ident << CorrectedQuotedStr
6594 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006595
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006596 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6597 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006598
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006599 R.addDecl(Corrected.getCorrectionDecl());
6600 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006601 }
6602 return false;
6603}
6604
John McCalld226f652010-08-21 09:40:31 +00006605Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006606 SourceLocation UsingLoc,
6607 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006608 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006609 SourceLocation IdentLoc,
6610 IdentifierInfo *NamespcName,
6611 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006612 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6613 assert(NamespcName && "Invalid NamespcName.");
6614 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006615
6616 // This can only happen along a recovery path.
6617 while (S->getFlags() & Scope::TemplateParamScope)
6618 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006619 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006620
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006621 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006622 NestedNameSpecifier *Qualifier = 0;
6623 if (SS.isSet())
6624 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6625
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006626 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006627 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6628 LookupParsedName(R, S, &SS);
6629 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006630 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006631
Douglas Gregor66992202010-06-29 17:53:46 +00006632 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006633 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006634 // Allow "using namespace std;" or "using namespace ::std;" even if
6635 // "std" hasn't been defined yet, for GCC compatibility.
6636 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6637 NamespcName->isStr("std")) {
6638 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006639 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006640 R.resolveKind();
6641 }
6642 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006643 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006644 }
6645
John McCallf36e02d2009-10-09 21:13:30 +00006646 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006647 NamedDecl *Named = R.getFoundDecl();
6648 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6649 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006650 // C++ [namespace.udir]p1:
6651 // A using-directive specifies that the names in the nominated
6652 // namespace can be used in the scope in which the
6653 // using-directive appears after the using-directive. During
6654 // unqualified name lookup (3.4.1), the names appear as if they
6655 // were declared in the nearest enclosing namespace which
6656 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006657 // namespace. [Note: in this context, "contains" means "contains
6658 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006659
6660 // Find enclosing context containing both using-directive and
6661 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006662 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006663 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6664 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6665 CommonAncestor = CommonAncestor->getParent();
6666
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006667 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006668 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006669 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006670
Douglas Gregor9172aa62011-03-26 22:25:30 +00006671 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006672 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006673 Diag(IdentLoc, diag::warn_using_directive_in_header);
6674 }
6675
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006676 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006677 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006678 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006679 }
6680
Richard Smith6b3d3e52013-02-20 19:22:51 +00006681 if (UDir)
6682 ProcessDeclAttributeList(S, UDir, AttrList);
6683
John McCalld226f652010-08-21 09:40:31 +00006684 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006685}
6686
6687void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006688 // If the scope has an associated entity and the using directive is at
6689 // namespace or translation unit scope, add the UsingDirectiveDecl into
6690 // its lookup structure so qualified name lookup can find it.
6691 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6692 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006693 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006694 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006695 // Otherwise, it is at block sope. The using-directives will affect lookup
6696 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006697 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006698}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006699
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006700
John McCalld226f652010-08-21 09:40:31 +00006701Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006702 AccessSpecifier AS,
6703 bool HasUsingKeyword,
6704 SourceLocation UsingLoc,
6705 CXXScopeSpec &SS,
6706 UnqualifiedId &Name,
6707 AttributeList *AttrList,
6708 bool IsTypeName,
6709 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006710 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006711
Douglas Gregor12c118a2009-11-04 16:30:06 +00006712 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006713 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006714 case UnqualifiedId::IK_Identifier:
6715 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006716 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006717 case UnqualifiedId::IK_ConversionFunctionId:
6718 break;
6719
6720 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006721 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006722 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006723 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006724 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006725 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006726 diag::err_using_decl_constructor)
6727 << SS.getRange();
6728
Richard Smith80ad52f2013-01-02 11:42:31 +00006729 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006730
John McCalld226f652010-08-21 09:40:31 +00006731 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006732
6733 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006734 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006735 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006736 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006737
6738 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006739 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006740 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006741 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006742 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006743
6744 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6745 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006746 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006747 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006748
Richard Smith07b0fdc2013-03-18 21:12:30 +00006749 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006750 // TODO: store that the declaration was written without 'using' and
6751 // talk about access decls instead of using decls in the
6752 // diagnostics.
6753 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006754 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006755
6756 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006757 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006758 }
6759
Douglas Gregor56c04582010-12-16 00:46:58 +00006760 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6761 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6762 return 0;
6763
John McCall9488ea12009-11-17 05:59:44 +00006764 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006765 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006766 /* IsInstantiation */ false,
6767 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006768 if (UD)
6769 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006770
John McCalld226f652010-08-21 09:40:31 +00006771 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006772}
6773
Douglas Gregor09acc982010-07-07 23:08:52 +00006774/// \brief Determine whether a using declaration considers the given
6775/// declarations as "equivalent", e.g., if they are redeclarations of
6776/// the same entity or are both typedefs of the same type.
6777static bool
6778IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6779 bool &SuppressRedeclaration) {
6780 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6781 SuppressRedeclaration = false;
6782 return true;
6783 }
6784
Richard Smith162e1c12011-04-15 14:24:37 +00006785 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6786 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006787 SuppressRedeclaration = true;
6788 return Context.hasSameType(TD1->getUnderlyingType(),
6789 TD2->getUnderlyingType());
6790 }
6791
6792 return false;
6793}
6794
6795
John McCall9f54ad42009-12-10 09:41:52 +00006796/// Determines whether to create a using shadow decl for a particular
6797/// decl, given the set of decls existing prior to this using lookup.
6798bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6799 const LookupResult &Previous) {
6800 // Diagnose finding a decl which is not from a base class of the
6801 // current class. We do this now because there are cases where this
6802 // function will silently decide not to build a shadow decl, which
6803 // will pre-empt further diagnostics.
6804 //
6805 // We don't need to do this in C++0x because we do the check once on
6806 // the qualifier.
6807 //
6808 // FIXME: diagnose the following if we care enough:
6809 // struct A { int foo; };
6810 // struct B : A { using A::foo; };
6811 // template <class T> struct C : A {};
6812 // template <class T> struct D : C<T> { using B::foo; } // <---
6813 // This is invalid (during instantiation) in C++03 because B::foo
6814 // resolves to the using decl in B, which is not a base class of D<T>.
6815 // We can't diagnose it immediately because C<T> is an unknown
6816 // specialization. The UsingShadowDecl in D<T> then points directly
6817 // to A::foo, which will look well-formed when we instantiate.
6818 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006819 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006820 DeclContext *OrigDC = Orig->getDeclContext();
6821
6822 // Handle enums and anonymous structs.
6823 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6824 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6825 while (OrigRec->isAnonymousStructOrUnion())
6826 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6827
6828 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6829 if (OrigDC == CurContext) {
6830 Diag(Using->getLocation(),
6831 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006832 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006833 Diag(Orig->getLocation(), diag::note_using_decl_target);
6834 return true;
6835 }
6836
Douglas Gregordc355712011-02-25 00:36:19 +00006837 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006838 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006839 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006840 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006841 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006842 Diag(Orig->getLocation(), diag::note_using_decl_target);
6843 return true;
6844 }
6845 }
6846
6847 if (Previous.empty()) return false;
6848
6849 NamedDecl *Target = Orig;
6850 if (isa<UsingShadowDecl>(Target))
6851 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6852
John McCalld7533ec2009-12-11 02:33:26 +00006853 // If the target happens to be one of the previous declarations, we
6854 // don't have a conflict.
6855 //
6856 // FIXME: but we might be increasing its access, in which case we
6857 // should redeclare it.
6858 NamedDecl *NonTag = 0, *Tag = 0;
6859 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6860 I != E; ++I) {
6861 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006862 bool Result;
6863 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6864 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006865
6866 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6867 }
6868
John McCall9f54ad42009-12-10 09:41:52 +00006869 if (Target->isFunctionOrFunctionTemplate()) {
6870 FunctionDecl *FD;
6871 if (isa<FunctionTemplateDecl>(Target))
6872 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6873 else
6874 FD = cast<FunctionDecl>(Target);
6875
6876 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006877 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006878 case Ovl_Overload:
6879 return false;
6880
6881 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006882 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006883 break;
6884
6885 // We found a decl with the exact signature.
6886 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006887 // If we're in a record, we want to hide the target, so we
6888 // return true (without a diagnostic) to tell the caller not to
6889 // build a shadow decl.
6890 if (CurContext->isRecord())
6891 return true;
6892
6893 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006894 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006895 break;
6896 }
6897
6898 Diag(Target->getLocation(), diag::note_using_decl_target);
6899 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6900 return true;
6901 }
6902
6903 // Target is not a function.
6904
John McCall9f54ad42009-12-10 09:41:52 +00006905 if (isa<TagDecl>(Target)) {
6906 // No conflict between a tag and a non-tag.
6907 if (!Tag) return false;
6908
John McCall41ce66f2009-12-10 19:51:03 +00006909 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006910 Diag(Target->getLocation(), diag::note_using_decl_target);
6911 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6912 return true;
6913 }
6914
6915 // No conflict between a tag and a non-tag.
6916 if (!NonTag) return false;
6917
John McCall41ce66f2009-12-10 19:51:03 +00006918 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006919 Diag(Target->getLocation(), diag::note_using_decl_target);
6920 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6921 return true;
6922}
6923
John McCall9488ea12009-11-17 05:59:44 +00006924/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006925UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006926 UsingDecl *UD,
6927 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006928
6929 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006930 NamedDecl *Target = Orig;
6931 if (isa<UsingShadowDecl>(Target)) {
6932 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6933 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006934 }
6935
6936 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006937 = UsingShadowDecl::Create(Context, CurContext,
6938 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006939 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006940
6941 Shadow->setAccess(UD->getAccess());
6942 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6943 Shadow->setInvalidDecl();
6944
John McCall9488ea12009-11-17 05:59:44 +00006945 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006946 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006947 else
John McCall604e7f12009-12-08 07:46:18 +00006948 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006949
John McCall604e7f12009-12-08 07:46:18 +00006950
John McCall9f54ad42009-12-10 09:41:52 +00006951 return Shadow;
6952}
John McCall604e7f12009-12-08 07:46:18 +00006953
John McCall9f54ad42009-12-10 09:41:52 +00006954/// Hides a using shadow declaration. This is required by the current
6955/// using-decl implementation when a resolvable using declaration in a
6956/// class is followed by a declaration which would hide or override
6957/// one or more of the using decl's targets; for example:
6958///
6959/// struct Base { void foo(int); };
6960/// struct Derived : Base {
6961/// using Base::foo;
6962/// void foo(int);
6963/// };
6964///
6965/// The governing language is C++03 [namespace.udecl]p12:
6966///
6967/// When a using-declaration brings names from a base class into a
6968/// derived class scope, member functions in the derived class
6969/// override and/or hide member functions with the same name and
6970/// parameter types in a base class (rather than conflicting).
6971///
6972/// There are two ways to implement this:
6973/// (1) optimistically create shadow decls when they're not hidden
6974/// by existing declarations, or
6975/// (2) don't create any shadow decls (or at least don't make them
6976/// visible) until we've fully parsed/instantiated the class.
6977/// The problem with (1) is that we might have to retroactively remove
6978/// a shadow decl, which requires several O(n) operations because the
6979/// decl structures are (very reasonably) not designed for removal.
6980/// (2) avoids this but is very fiddly and phase-dependent.
6981void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006982 if (Shadow->getDeclName().getNameKind() ==
6983 DeclarationName::CXXConversionFunctionName)
6984 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6985
John McCall9f54ad42009-12-10 09:41:52 +00006986 // Remove it from the DeclContext...
6987 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006988
John McCall9f54ad42009-12-10 09:41:52 +00006989 // ...and the scope, if applicable...
6990 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006991 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006992 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006993 }
6994
John McCall9f54ad42009-12-10 09:41:52 +00006995 // ...and the using decl.
6996 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6997
6998 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006999 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007000}
7001
John McCall7ba107a2009-11-18 02:36:19 +00007002/// Builds a using declaration.
7003///
7004/// \param IsInstantiation - Whether this call arises from an
7005/// instantiation of an unresolved using declaration. We treat
7006/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007007NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7008 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007009 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007010 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007011 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007012 bool IsInstantiation,
7013 bool IsTypeName,
7014 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007015 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007016 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007017 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007018
Anders Carlsson550b14b2009-08-28 05:49:21 +00007019 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007020
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007021 if (SS.isEmpty()) {
7022 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007023 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007024 }
Mike Stump1eb44332009-09-09 15:08:12 +00007025
John McCall9f54ad42009-12-10 09:41:52 +00007026 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007027 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007028 ForRedeclaration);
7029 Previous.setHideTags(false);
7030 if (S) {
7031 LookupName(Previous, S);
7032
7033 // It is really dumb that we have to do this.
7034 LookupResult::Filter F = Previous.makeFilter();
7035 while (F.hasNext()) {
7036 NamedDecl *D = F.next();
7037 if (!isDeclInScope(D, CurContext, S))
7038 F.erase();
7039 }
7040 F.done();
7041 } else {
7042 assert(IsInstantiation && "no scope in non-instantiation");
7043 assert(CurContext->isRecord() && "scope not record in instantiation");
7044 LookupQualifiedName(Previous, CurContext);
7045 }
7046
John McCall9f54ad42009-12-10 09:41:52 +00007047 // Check for invalid redeclarations.
7048 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
7049 return 0;
7050
7051 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007052 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7053 return 0;
7054
John McCallaf8e6ed2009-11-12 03:15:40 +00007055 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007056 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007057 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007058 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00007059 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00007060 // FIXME: not all declaration name kinds are legal here
7061 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7062 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007063 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007064 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007065 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007066 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7067 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007068 }
John McCalled976492009-12-04 22:46:56 +00007069 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007070 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7071 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007072 }
John McCalled976492009-12-04 22:46:56 +00007073 D->setAccess(AS);
7074 CurContext->addDecl(D);
7075
7076 if (!LookupContext) return D;
7077 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007078
John McCall77bb1aa2010-05-01 00:40:08 +00007079 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007080 UD->setInvalidDecl();
7081 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007082 }
7083
Richard Smithc5a89a12012-04-02 01:30:27 +00007084 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007085 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007086 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007087 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007088 return UD;
7089 }
7090
7091 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007092
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007093 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007094
John McCall604e7f12009-12-08 07:46:18 +00007095 // Unlike most lookups, we don't always want to hide tag
7096 // declarations: tag names are visible through the using declaration
7097 // even if hidden by ordinary names, *except* in a dependent context
7098 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007099 if (!IsInstantiation)
7100 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007101
John McCallb9abd8722012-04-07 03:04:20 +00007102 // For the purposes of this lookup, we have a base object type
7103 // equal to that of the current context.
7104 if (CurContext->isRecord()) {
7105 R.setBaseObjectType(
7106 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7107 }
7108
John McCalla24dc2e2009-11-17 02:14:36 +00007109 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007110
John McCallf36e02d2009-10-09 21:13:30 +00007111 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00007112 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007113 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007114 UD->setInvalidDecl();
7115 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007116 }
7117
John McCalled976492009-12-04 22:46:56 +00007118 if (R.isAmbiguous()) {
7119 UD->setInvalidDecl();
7120 return UD;
7121 }
Mike Stump1eb44332009-09-09 15:08:12 +00007122
John McCall7ba107a2009-11-18 02:36:19 +00007123 if (IsTypeName) {
7124 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007125 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007126 Diag(IdentLoc, diag::err_using_typename_non_type);
7127 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7128 Diag((*I)->getUnderlyingDecl()->getLocation(),
7129 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007130 UD->setInvalidDecl();
7131 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007132 }
7133 } else {
7134 // If we asked for a non-typename and we got a type, error out,
7135 // but only if this is an instantiation of an unresolved using
7136 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007137 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007138 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7139 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007140 UD->setInvalidDecl();
7141 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007142 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007143 }
7144
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007145 // C++0x N2914 [namespace.udecl]p6:
7146 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007147 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007148 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7149 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007150 UD->setInvalidDecl();
7151 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007152 }
Mike Stump1eb44332009-09-09 15:08:12 +00007153
John McCall9f54ad42009-12-10 09:41:52 +00007154 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7155 if (!CheckUsingShadowDecl(UD, *I, Previous))
7156 BuildUsingShadowDecl(S, UD, *I);
7157 }
John McCall9488ea12009-11-17 05:59:44 +00007158
7159 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007160}
7161
Sebastian Redlf677ea32011-02-05 19:23:19 +00007162/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007163bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7164 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007165
Douglas Gregordc355712011-02-25 00:36:19 +00007166 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007167 assert(SourceType &&
7168 "Using decl naming constructor doesn't have type in scope spec.");
7169 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7170
7171 // Check whether the named type is a direct base class.
7172 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7173 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7174 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7175 BaseIt != BaseE; ++BaseIt) {
7176 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7177 if (CanonicalSourceType == BaseType)
7178 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007179 if (BaseIt->getType()->isDependentType())
7180 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007181 }
7182
7183 if (BaseIt == BaseE) {
7184 // Did not find SourceType in the bases.
7185 Diag(UD->getUsingLocation(),
7186 diag::err_using_decl_constructor_not_in_direct_base)
7187 << UD->getNameInfo().getSourceRange()
7188 << QualType(SourceType, 0) << TargetClass;
7189 return true;
7190 }
7191
Richard Smithc5a89a12012-04-02 01:30:27 +00007192 if (!CurContext->isDependentContext())
7193 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007194
7195 return false;
7196}
7197
John McCall9f54ad42009-12-10 09:41:52 +00007198/// Checks that the given using declaration is not an invalid
7199/// redeclaration. Note that this is checking only for the using decl
7200/// itself, not for any ill-formedness among the UsingShadowDecls.
7201bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7202 bool isTypeName,
7203 const CXXScopeSpec &SS,
7204 SourceLocation NameLoc,
7205 const LookupResult &Prev) {
7206 // C++03 [namespace.udecl]p8:
7207 // C++0x [namespace.udecl]p10:
7208 // A using-declaration is a declaration and can therefore be used
7209 // repeatedly where (and only where) multiple declarations are
7210 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007211 //
John McCall8a726212010-11-29 18:01:58 +00007212 // That's in non-member contexts.
7213 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007214 return false;
7215
7216 NestedNameSpecifier *Qual
7217 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7218
7219 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7220 NamedDecl *D = *I;
7221
7222 bool DTypename;
7223 NestedNameSpecifier *DQual;
7224 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7225 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007226 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007227 } else if (UnresolvedUsingValueDecl *UD
7228 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7229 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007230 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007231 } else if (UnresolvedUsingTypenameDecl *UD
7232 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7233 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007234 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007235 } else continue;
7236
7237 // using decls differ if one says 'typename' and the other doesn't.
7238 // FIXME: non-dependent using decls?
7239 if (isTypeName != DTypename) continue;
7240
7241 // using decls differ if they name different scopes (but note that
7242 // template instantiation can cause this check to trigger when it
7243 // didn't before instantiation).
7244 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7245 Context.getCanonicalNestedNameSpecifier(DQual))
7246 continue;
7247
7248 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007249 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007250 return true;
7251 }
7252
7253 return false;
7254}
7255
John McCall604e7f12009-12-08 07:46:18 +00007256
John McCalled976492009-12-04 22:46:56 +00007257/// Checks that the given nested-name qualifier used in a using decl
7258/// in the current context is appropriately related to the current
7259/// scope. If an error is found, diagnoses it and returns true.
7260bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7261 const CXXScopeSpec &SS,
7262 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007263 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007264
John McCall604e7f12009-12-08 07:46:18 +00007265 if (!CurContext->isRecord()) {
7266 // C++03 [namespace.udecl]p3:
7267 // C++0x [namespace.udecl]p8:
7268 // A using-declaration for a class member shall be a member-declaration.
7269
7270 // If we weren't able to compute a valid scope, it must be a
7271 // dependent class scope.
7272 if (!NamedContext || NamedContext->isRecord()) {
7273 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7274 << SS.getRange();
7275 return true;
7276 }
7277
7278 // Otherwise, everything is known to be fine.
7279 return false;
7280 }
7281
7282 // The current scope is a record.
7283
7284 // If the named context is dependent, we can't decide much.
7285 if (!NamedContext) {
7286 // FIXME: in C++0x, we can diagnose if we can prove that the
7287 // nested-name-specifier does not refer to a base class, which is
7288 // still possible in some cases.
7289
7290 // Otherwise we have to conservatively report that things might be
7291 // okay.
7292 return false;
7293 }
7294
7295 if (!NamedContext->isRecord()) {
7296 // Ideally this would point at the last name in the specifier,
7297 // but we don't have that level of source info.
7298 Diag(SS.getRange().getBegin(),
7299 diag::err_using_decl_nested_name_specifier_is_not_class)
7300 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7301 return true;
7302 }
7303
Douglas Gregor6fb07292010-12-21 07:41:49 +00007304 if (!NamedContext->isDependentContext() &&
7305 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7306 return true;
7307
Richard Smith80ad52f2013-01-02 11:42:31 +00007308 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007309 // C++0x [namespace.udecl]p3:
7310 // In a using-declaration used as a member-declaration, the
7311 // nested-name-specifier shall name a base class of the class
7312 // being defined.
7313
7314 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7315 cast<CXXRecordDecl>(NamedContext))) {
7316 if (CurContext == NamedContext) {
7317 Diag(NameLoc,
7318 diag::err_using_decl_nested_name_specifier_is_current_class)
7319 << SS.getRange();
7320 return true;
7321 }
7322
7323 Diag(SS.getRange().getBegin(),
7324 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7325 << (NestedNameSpecifier*) SS.getScopeRep()
7326 << cast<CXXRecordDecl>(CurContext)
7327 << SS.getRange();
7328 return true;
7329 }
7330
7331 return false;
7332 }
7333
7334 // C++03 [namespace.udecl]p4:
7335 // A using-declaration used as a member-declaration shall refer
7336 // to a member of a base class of the class being defined [etc.].
7337
7338 // Salient point: SS doesn't have to name a base class as long as
7339 // lookup only finds members from base classes. Therefore we can
7340 // diagnose here only if we can prove that that can't happen,
7341 // i.e. if the class hierarchies provably don't intersect.
7342
7343 // TODO: it would be nice if "definitely valid" results were cached
7344 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7345 // need to be repeated.
7346
7347 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007348 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007349
7350 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7351 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7352 Data->Bases.insert(Base);
7353 return true;
7354 }
7355
7356 bool hasDependentBases(const CXXRecordDecl *Class) {
7357 return !Class->forallBases(collect, this);
7358 }
7359
7360 /// Returns true if the base is dependent or is one of the
7361 /// accumulated base classes.
7362 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7363 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7364 return !Data->Bases.count(Base);
7365 }
7366
7367 bool mightShareBases(const CXXRecordDecl *Class) {
7368 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7369 }
7370 };
7371
7372 UserData Data;
7373
7374 // Returns false if we find a dependent base.
7375 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7376 return false;
7377
7378 // Returns false if the class has a dependent base or if it or one
7379 // of its bases is present in the base set of the current context.
7380 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7381 return false;
7382
7383 Diag(SS.getRange().getBegin(),
7384 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7385 << (NestedNameSpecifier*) SS.getScopeRep()
7386 << cast<CXXRecordDecl>(CurContext)
7387 << SS.getRange();
7388
7389 return true;
John McCalled976492009-12-04 22:46:56 +00007390}
7391
Richard Smith162e1c12011-04-15 14:24:37 +00007392Decl *Sema::ActOnAliasDeclaration(Scope *S,
7393 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007394 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007395 SourceLocation UsingLoc,
7396 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007397 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007398 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007399 // Skip up to the relevant declaration scope.
7400 while (S->getFlags() & Scope::TemplateParamScope)
7401 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007402 assert((S->getFlags() & Scope::DeclScope) &&
7403 "got alias-declaration outside of declaration scope");
7404
7405 if (Type.isInvalid())
7406 return 0;
7407
7408 bool Invalid = false;
7409 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7410 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007411 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007412
7413 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7414 return 0;
7415
7416 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007417 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007418 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007419 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7420 TInfo->getTypeLoc().getBeginLoc());
7421 }
Richard Smith162e1c12011-04-15 14:24:37 +00007422
7423 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7424 LookupName(Previous, S);
7425
7426 // Warn about shadowing the name of a template parameter.
7427 if (Previous.isSingleResult() &&
7428 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007429 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007430 Previous.clear();
7431 }
7432
7433 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7434 "name in alias declaration must be an identifier");
7435 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7436 Name.StartLocation,
7437 Name.Identifier, TInfo);
7438
7439 NewTD->setAccess(AS);
7440
7441 if (Invalid)
7442 NewTD->setInvalidDecl();
7443
Richard Smith6b3d3e52013-02-20 19:22:51 +00007444 ProcessDeclAttributeList(S, NewTD, AttrList);
7445
Richard Smith3e4c6c42011-05-05 21:57:07 +00007446 CheckTypedefForVariablyModifiedType(S, NewTD);
7447 Invalid |= NewTD->isInvalidDecl();
7448
Richard Smith162e1c12011-04-15 14:24:37 +00007449 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007450
7451 NamedDecl *NewND;
7452 if (TemplateParamLists.size()) {
7453 TypeAliasTemplateDecl *OldDecl = 0;
7454 TemplateParameterList *OldTemplateParams = 0;
7455
7456 if (TemplateParamLists.size() != 1) {
7457 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007458 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7459 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007460 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007461 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007462
7463 // Only consider previous declarations in the same scope.
7464 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7465 /*ExplicitInstantiationOrSpecialization*/false);
7466 if (!Previous.empty()) {
7467 Redeclaration = true;
7468
7469 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7470 if (!OldDecl && !Invalid) {
7471 Diag(UsingLoc, diag::err_redefinition_different_kind)
7472 << Name.Identifier;
7473
7474 NamedDecl *OldD = Previous.getRepresentativeDecl();
7475 if (OldD->getLocation().isValid())
7476 Diag(OldD->getLocation(), diag::note_previous_definition);
7477
7478 Invalid = true;
7479 }
7480
7481 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7482 if (TemplateParameterListsAreEqual(TemplateParams,
7483 OldDecl->getTemplateParameters(),
7484 /*Complain=*/true,
7485 TPL_TemplateMatch))
7486 OldTemplateParams = OldDecl->getTemplateParameters();
7487 else
7488 Invalid = true;
7489
7490 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7491 if (!Invalid &&
7492 !Context.hasSameType(OldTD->getUnderlyingType(),
7493 NewTD->getUnderlyingType())) {
7494 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7495 // but we can't reasonably accept it.
7496 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7497 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7498 if (OldTD->getLocation().isValid())
7499 Diag(OldTD->getLocation(), diag::note_previous_definition);
7500 Invalid = true;
7501 }
7502 }
7503 }
7504
7505 // Merge any previous default template arguments into our parameters,
7506 // and check the parameter list.
7507 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7508 TPC_TypeAliasTemplate))
7509 return 0;
7510
7511 TypeAliasTemplateDecl *NewDecl =
7512 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7513 Name.Identifier, TemplateParams,
7514 NewTD);
7515
7516 NewDecl->setAccess(AS);
7517
7518 if (Invalid)
7519 NewDecl->setInvalidDecl();
7520 else if (OldDecl)
7521 NewDecl->setPreviousDeclaration(OldDecl);
7522
7523 NewND = NewDecl;
7524 } else {
7525 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7526 NewND = NewTD;
7527 }
Richard Smith162e1c12011-04-15 14:24:37 +00007528
7529 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007530 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007531
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007532 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007533 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007534}
7535
John McCalld226f652010-08-21 09:40:31 +00007536Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007537 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007538 SourceLocation AliasLoc,
7539 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007540 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007541 SourceLocation IdentLoc,
7542 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007543
Anders Carlsson81c85c42009-03-28 23:53:49 +00007544 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007545 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7546 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007547
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007548 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007549 NamedDecl *PrevDecl
7550 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7551 ForRedeclaration);
7552 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7553 PrevDecl = 0;
7554
7555 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007556 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007557 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007558 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007559 // FIXME: At some point, we'll want to create the (redundant)
7560 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007561 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007562 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007563 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007564 }
Mike Stump1eb44332009-09-09 15:08:12 +00007565
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007566 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7567 diag::err_redefinition_different_kind;
7568 Diag(AliasLoc, DiagID) << Alias;
7569 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007570 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007571 }
7572
John McCalla24dc2e2009-11-17 02:14:36 +00007573 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007574 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007575
John McCallf36e02d2009-10-09 21:13:30 +00007576 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007577 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007578 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007579 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007580 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007581 }
Mike Stump1eb44332009-09-09 15:08:12 +00007582
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007583 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007584 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007585 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007586 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007587
John McCall3dbd3d52010-02-16 06:53:13 +00007588 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007589 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007590}
7591
Sean Hunt001cad92011-05-10 00:49:42 +00007592Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007593Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7594 CXXMethodDecl *MD) {
7595 CXXRecordDecl *ClassDecl = MD->getParent();
7596
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007597 // C++ [except.spec]p14:
7598 // An implicitly declared special member function (Clause 12) shall have an
7599 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007600 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007601 if (ClassDecl->isInvalidDecl())
7602 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007603
Sebastian Redl60618fa2011-03-12 11:50:43 +00007604 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007605 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7606 BEnd = ClassDecl->bases_end();
7607 B != BEnd; ++B) {
7608 if (B->isVirtual()) // Handled below.
7609 continue;
7610
Douglas Gregor18274032010-07-03 00:47:00 +00007611 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7612 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007613 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7614 // If this is a deleted function, add it anyway. This might be conformant
7615 // with the standard. This might not. I'm not sure. It might not matter.
7616 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007617 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007618 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007619 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007620
7621 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007622 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7623 BEnd = ClassDecl->vbases_end();
7624 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007625 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7626 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007627 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7628 // If this is a deleted function, add it anyway. This might be conformant
7629 // with the standard. This might not. I'm not sure. It might not matter.
7630 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007631 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007632 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007633 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007634
7635 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007636 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7637 FEnd = ClassDecl->field_end();
7638 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007639 if (F->hasInClassInitializer()) {
7640 if (Expr *E = F->getInClassInitializer())
7641 ExceptSpec.CalledExpr(E);
7642 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007643 // DR1351:
7644 // If the brace-or-equal-initializer of a non-static data member
7645 // invokes a defaulted default constructor of its class or of an
7646 // enclosing class in a potentially evaluated subexpression, the
7647 // program is ill-formed.
7648 //
7649 // This resolution is unworkable: the exception specification of the
7650 // default constructor can be needed in an unevaluated context, in
7651 // particular, in the operand of a noexcept-expression, and we can be
7652 // unable to compute an exception specification for an enclosed class.
7653 //
7654 // We do not allow an in-class initializer to require the evaluation
7655 // of the exception specification for any in-class initializer whose
7656 // definition is not lexically complete.
7657 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007658 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007659 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007660 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7661 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7662 // If this is a deleted function, add it anyway. This might be conformant
7663 // with the standard. This might not. I'm not sure. It might not matter.
7664 // In particular, the problem is that this function never gets called. It
7665 // might just be ill-formed because this function attempts to refer to
7666 // a deleted function here.
7667 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007668 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007669 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007670 }
John McCalle23cf432010-12-14 08:05:40 +00007671
Sean Hunt001cad92011-05-10 00:49:42 +00007672 return ExceptSpec;
7673}
7674
Richard Smith07b0fdc2013-03-18 21:12:30 +00007675Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007676Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7677 CXXRecordDecl *ClassDecl = CD->getParent();
7678
7679 // C++ [except.spec]p14:
7680 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007681 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007682 if (ClassDecl->isInvalidDecl())
7683 return ExceptSpec;
7684
7685 // Inherited constructor.
7686 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7687 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7688 // FIXME: Copying or moving the parameters could add extra exceptions to the
7689 // set, as could the default arguments for the inherited constructor. This
7690 // will be addressed when we implement the resolution of core issue 1351.
7691 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7692
7693 // Direct base-class constructors.
7694 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7695 BEnd = ClassDecl->bases_end();
7696 B != BEnd; ++B) {
7697 if (B->isVirtual()) // Handled below.
7698 continue;
7699
7700 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7701 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7702 if (BaseClassDecl == InheritedDecl)
7703 continue;
7704 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7705 if (Constructor)
7706 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7707 }
7708 }
7709
7710 // Virtual base-class constructors.
7711 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7712 BEnd = ClassDecl->vbases_end();
7713 B != BEnd; ++B) {
7714 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7715 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7716 if (BaseClassDecl == InheritedDecl)
7717 continue;
7718 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7719 if (Constructor)
7720 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7721 }
7722 }
7723
7724 // Field constructors.
7725 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7726 FEnd = ClassDecl->field_end();
7727 F != FEnd; ++F) {
7728 if (F->hasInClassInitializer()) {
7729 if (Expr *E = F->getInClassInitializer())
7730 ExceptSpec.CalledExpr(E);
7731 else if (!F->isInvalidDecl())
7732 Diag(CD->getLocation(),
7733 diag::err_in_class_initializer_references_def_ctor) << CD;
7734 } else if (const RecordType *RecordTy
7735 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7736 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7737 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7738 if (Constructor)
7739 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7740 }
7741 }
7742
Richard Smith07b0fdc2013-03-18 21:12:30 +00007743 return ExceptSpec;
7744}
7745
Richard Smithafb49182012-11-29 01:34:07 +00007746namespace {
7747/// RAII object to register a special member as being currently declared.
7748struct DeclaringSpecialMember {
7749 Sema &S;
7750 Sema::SpecialMemberDecl D;
7751 bool WasAlreadyBeingDeclared;
7752
7753 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7754 : S(S), D(RD, CSM) {
7755 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7756 if (WasAlreadyBeingDeclared)
7757 // This almost never happens, but if it does, ensure that our cache
7758 // doesn't contain a stale result.
7759 S.SpecialMemberCache.clear();
7760
7761 // FIXME: Register a note to be produced if we encounter an error while
7762 // declaring the special member.
7763 }
7764 ~DeclaringSpecialMember() {
7765 if (!WasAlreadyBeingDeclared)
7766 S.SpecialMembersBeingDeclared.erase(D);
7767 }
7768
7769 /// \brief Are we already trying to declare this special member?
7770 bool isAlreadyBeingDeclared() const {
7771 return WasAlreadyBeingDeclared;
7772 }
7773};
7774}
7775
Sean Hunt001cad92011-05-10 00:49:42 +00007776CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7777 CXXRecordDecl *ClassDecl) {
7778 // C++ [class.ctor]p5:
7779 // A default constructor for a class X is a constructor of class X
7780 // that can be called without an argument. If there is no
7781 // user-declared constructor for class X, a default constructor is
7782 // implicitly declared. An implicitly-declared default constructor
7783 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007784 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007785 "Should not build implicit default constructor!");
7786
Richard Smithafb49182012-11-29 01:34:07 +00007787 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7788 if (DSM.isAlreadyBeingDeclared())
7789 return 0;
7790
Richard Smith7756afa2012-06-10 05:43:50 +00007791 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7792 CXXDefaultConstructor,
7793 false);
7794
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007795 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007796 CanQualType ClassType
7797 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007798 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007799 DeclarationName Name
7800 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007801 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007802 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007803 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007804 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007805 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007806 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007807 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007808 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007809
7810 // Build an exception specification pointing back at this constructor.
7811 FunctionProtoType::ExtProtoInfo EPI;
7812 EPI.ExceptionSpecType = EST_Unevaluated;
7813 EPI.ExceptionSpecDecl = DefaultCon;
Dmitri Gribenko55431692013-05-05 00:41:58 +00007814 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007815
Richard Smithbc2a35d2012-12-08 08:32:28 +00007816 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7817 // constructors is easy to compute.
7818 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7819
7820 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007821 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007822
Douglas Gregor18274032010-07-03 00:47:00 +00007823 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007824 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007825
Douglas Gregor23c94db2010-07-02 17:43:08 +00007826 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007827 PushOnScopeChains(DefaultCon, S, false);
7828 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007829
Douglas Gregor32df23e2010-07-01 22:02:46 +00007830 return DefaultCon;
7831}
7832
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007833void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7834 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007835 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007836 !Constructor->doesThisDeclarationHaveABody() &&
7837 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007838 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007839
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007840 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007841 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007842
Eli Friedman9a14db32012-10-18 20:14:08 +00007843 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007844 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007845 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007846 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007847 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007848 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007849 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007850 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007851 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007852
7853 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007854 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007855
7856 Constructor->setUsed();
7857 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007858
7859 if (ASTMutationListener *L = getASTMutationListener()) {
7860 L->CompletedImplicitDefinition(Constructor);
7861 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007862}
7863
Richard Smith7a614d82011-06-11 17:19:42 +00007864void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007865 // Check that any explicitly-defaulted methods have exception specifications
7866 // compatible with their implicit exception specifications.
7867 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007868}
7869
Richard Smith4841ca52013-04-10 05:48:59 +00007870namespace {
7871/// Information on inheriting constructors to declare.
7872class InheritingConstructorInfo {
7873public:
7874 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7875 : SemaRef(SemaRef), Derived(Derived) {
7876 // Mark the constructors that we already have in the derived class.
7877 //
7878 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7879 // unless there is a user-declared constructor with the same signature in
7880 // the class where the using-declaration appears.
7881 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7882 }
7883
7884 void inheritAll(CXXRecordDecl *RD) {
7885 visitAll(RD, &InheritingConstructorInfo::inherit);
7886 }
7887
7888private:
7889 /// Information about an inheriting constructor.
7890 struct InheritingConstructor {
7891 InheritingConstructor()
7892 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7893
7894 /// If \c true, a constructor with this signature is already declared
7895 /// in the derived class.
7896 bool DeclaredInDerived;
7897
7898 /// The constructor which is inherited.
7899 const CXXConstructorDecl *BaseCtor;
7900
7901 /// The derived constructor we declared.
7902 CXXConstructorDecl *DerivedCtor;
7903 };
7904
7905 /// Inheriting constructors with a given canonical type. There can be at
7906 /// most one such non-template constructor, and any number of templated
7907 /// constructors.
7908 struct InheritingConstructorsForType {
7909 InheritingConstructor NonTemplate;
7910 llvm::SmallVector<
7911 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7912
7913 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7914 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7915 TemplateParameterList *ParamList = FTD->getTemplateParameters();
7916 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7917 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7918 false, S.TPL_TemplateMatch))
7919 return Templates[I].second;
7920 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7921 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007922 }
Richard Smith4841ca52013-04-10 05:48:59 +00007923
7924 return NonTemplate;
7925 }
7926 };
7927
7928 /// Get or create the inheriting constructor record for a constructor.
7929 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7930 QualType CtorType) {
7931 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7932 .getEntry(SemaRef, Ctor);
7933 }
7934
7935 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7936
7937 /// Process all constructors for a class.
7938 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7939 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7940 CtorE = RD->ctor_end();
7941 CtorIt != CtorE; ++CtorIt)
7942 (this->*Callback)(*CtorIt);
7943 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7944 I(RD->decls_begin()), E(RD->decls_end());
7945 I != E; ++I) {
7946 const FunctionDecl *FD = (*I)->getTemplatedDecl();
7947 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7948 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007949 }
7950 }
Richard Smith4841ca52013-04-10 05:48:59 +00007951
7952 /// Note that a constructor (or constructor template) was declared in Derived.
7953 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7954 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7955 }
7956
7957 /// Inherit a single constructor.
7958 void inherit(const CXXConstructorDecl *Ctor) {
7959 const FunctionProtoType *CtorType =
7960 Ctor->getType()->castAs<FunctionProtoType>();
7961 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7962 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7963
7964 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7965
7966 // Core issue (no number yet): the ellipsis is always discarded.
7967 if (EPI.Variadic) {
7968 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7969 SemaRef.Diag(Ctor->getLocation(),
7970 diag::note_using_decl_constructor_ellipsis);
7971 EPI.Variadic = false;
7972 }
7973
7974 // Declare a constructor for each number of parameters.
7975 //
7976 // C++11 [class.inhctor]p1:
7977 // The candidate set of inherited constructors from the class X named in
7978 // the using-declaration consists of [... modulo defects ...] for each
7979 // constructor or constructor template of X, the set of constructors or
7980 // constructor templates that results from omitting any ellipsis parameter
7981 // specification and successively omitting parameters with a default
7982 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00007983 unsigned MinParams = minParamsToInherit(Ctor);
7984 unsigned Params = Ctor->getNumParams();
7985 if (Params >= MinParams) {
7986 do
7987 declareCtor(UsingLoc, Ctor,
7988 SemaRef.Context.getFunctionType(
7989 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7990 while (Params > MinParams &&
7991 Ctor->getParamDecl(--Params)->hasDefaultArg());
7992 }
Richard Smith4841ca52013-04-10 05:48:59 +00007993 }
7994
7995 /// Find the using-declaration which specified that we should inherit the
7996 /// constructors of \p Base.
7997 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
7998 // No fancy lookup required; just look for the base constructor name
7999 // directly within the derived class.
8000 ASTContext &Context = SemaRef.Context;
8001 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8002 Context.getCanonicalType(Context.getRecordType(Base)));
8003 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8004 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8005 }
8006
8007 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8008 // C++11 [class.inhctor]p3:
8009 // [F]or each constructor template in the candidate set of inherited
8010 // constructors, a constructor template is implicitly declared
8011 if (Ctor->getDescribedFunctionTemplate())
8012 return 0;
8013
8014 // For each non-template constructor in the candidate set of inherited
8015 // constructors other than a constructor having no parameters or a
8016 // copy/move constructor having a single parameter, a constructor is
8017 // implicitly declared [...]
8018 if (Ctor->getNumParams() == 0)
8019 return 1;
8020 if (Ctor->isCopyOrMoveConstructor())
8021 return 2;
8022
8023 // Per discussion on core reflector, never inherit a constructor which
8024 // would become a default, copy, or move constructor of Derived either.
8025 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8026 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8027 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8028 }
8029
8030 /// Declare a single inheriting constructor, inheriting the specified
8031 /// constructor, with the given type.
8032 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8033 QualType DerivedType) {
8034 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8035
8036 // C++11 [class.inhctor]p3:
8037 // ... a constructor is implicitly declared with the same constructor
8038 // characteristics unless there is a user-declared constructor with
8039 // the same signature in the class where the using-declaration appears
8040 if (Entry.DeclaredInDerived)
8041 return;
8042
8043 // C++11 [class.inhctor]p7:
8044 // If two using-declarations declare inheriting constructors with the
8045 // same signature, the program is ill-formed
8046 if (Entry.DerivedCtor) {
8047 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8048 // Only diagnose this once per constructor.
8049 if (Entry.DerivedCtor->isInvalidDecl())
8050 return;
8051 Entry.DerivedCtor->setInvalidDecl();
8052
8053 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8054 SemaRef.Diag(BaseCtor->getLocation(),
8055 diag::note_using_decl_constructor_conflict_current_ctor);
8056 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8057 diag::note_using_decl_constructor_conflict_previous_ctor);
8058 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8059 diag::note_using_decl_constructor_conflict_previous_using);
8060 } else {
8061 // Core issue (no number): if the same inheriting constructor is
8062 // produced by multiple base class constructors from the same base
8063 // class, the inheriting constructor is defined as deleted.
8064 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8065 }
8066
8067 return;
8068 }
8069
8070 ASTContext &Context = SemaRef.Context;
8071 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8072 Context.getCanonicalType(Context.getRecordType(Derived)));
8073 DeclarationNameInfo NameInfo(Name, UsingLoc);
8074
8075 TemplateParameterList *TemplateParams = 0;
8076 if (const FunctionTemplateDecl *FTD =
8077 BaseCtor->getDescribedFunctionTemplate()) {
8078 TemplateParams = FTD->getTemplateParameters();
8079 // We're reusing template parameters from a different DeclContext. This
8080 // is questionable at best, but works out because the template depth in
8081 // both places is guaranteed to be 0.
8082 // FIXME: Rebuild the template parameters in the new context, and
8083 // transform the function type to refer to them.
8084 }
8085
8086 // Build type source info pointing at the using-declaration. This is
8087 // required by template instantiation.
8088 TypeSourceInfo *TInfo =
8089 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8090 FunctionProtoTypeLoc ProtoLoc =
8091 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8092
8093 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8094 Context, Derived, UsingLoc, NameInfo, DerivedType,
8095 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8096 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8097
8098 // Build an unevaluated exception specification for this constructor.
8099 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8100 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8101 EPI.ExceptionSpecType = EST_Unevaluated;
8102 EPI.ExceptionSpecDecl = DerivedCtor;
8103 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8104 FPT->getArgTypes(), EPI));
8105
8106 // Build the parameter declarations.
8107 SmallVector<ParmVarDecl *, 16> ParamDecls;
8108 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8109 TypeSourceInfo *TInfo =
8110 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8111 ParmVarDecl *PD = ParmVarDecl::Create(
8112 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8113 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8114 PD->setScopeInfo(0, I);
8115 PD->setImplicit();
8116 ParamDecls.push_back(PD);
8117 ProtoLoc.setArg(I, PD);
8118 }
8119
8120 // Set up the new constructor.
8121 DerivedCtor->setAccess(BaseCtor->getAccess());
8122 DerivedCtor->setParams(ParamDecls);
8123 DerivedCtor->setInheritedConstructor(BaseCtor);
8124 if (BaseCtor->isDeleted())
8125 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8126
8127 // If this is a constructor template, build the template declaration.
8128 if (TemplateParams) {
8129 FunctionTemplateDecl *DerivedTemplate =
8130 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8131 TemplateParams, DerivedCtor);
8132 DerivedTemplate->setAccess(BaseCtor->getAccess());
8133 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8134 Derived->addDecl(DerivedTemplate);
8135 } else {
8136 Derived->addDecl(DerivedCtor);
8137 }
8138
8139 Entry.BaseCtor = BaseCtor;
8140 Entry.DerivedCtor = DerivedCtor;
8141 }
8142
8143 Sema &SemaRef;
8144 CXXRecordDecl *Derived;
8145 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8146 MapType Map;
8147};
8148}
8149
8150void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8151 // Defer declaring the inheriting constructors until the class is
8152 // instantiated.
8153 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008154 return;
8155
Richard Smith4841ca52013-04-10 05:48:59 +00008156 // Find base classes from which we might inherit constructors.
8157 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8158 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8159 BaseE = ClassDecl->bases_end();
8160 BaseIt != BaseE; ++BaseIt)
8161 if (BaseIt->getInheritConstructors())
8162 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008163
Richard Smith4841ca52013-04-10 05:48:59 +00008164 // Go no further if we're not inheriting any constructors.
8165 if (InheritedBases.empty())
8166 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008167
Richard Smith4841ca52013-04-10 05:48:59 +00008168 // Declare the inherited constructors.
8169 InheritingConstructorInfo ICI(*this, ClassDecl);
8170 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8171 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008172}
8173
Richard Smith07b0fdc2013-03-18 21:12:30 +00008174void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8175 CXXConstructorDecl *Constructor) {
8176 CXXRecordDecl *ClassDecl = Constructor->getParent();
8177 assert(Constructor->getInheritedConstructor() &&
8178 !Constructor->doesThisDeclarationHaveABody() &&
8179 !Constructor->isDeleted());
8180
8181 SynthesizedFunctionScope Scope(*this, Constructor);
8182 DiagnosticErrorTrap Trap(Diags);
8183 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8184 Trap.hasErrorOccurred()) {
8185 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8186 << Context.getTagDeclType(ClassDecl);
8187 Constructor->setInvalidDecl();
8188 return;
8189 }
8190
8191 SourceLocation Loc = Constructor->getLocation();
8192 Constructor->setBody(new (Context) CompoundStmt(Loc));
8193
8194 Constructor->setUsed();
8195 MarkVTableUsed(CurrentLocation, ClassDecl);
8196
8197 if (ASTMutationListener *L = getASTMutationListener()) {
8198 L->CompletedImplicitDefinition(Constructor);
8199 }
8200}
8201
8202
Sean Huntcb45a0f2011-05-12 22:46:25 +00008203Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008204Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8205 CXXRecordDecl *ClassDecl = MD->getParent();
8206
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008207 // C++ [except.spec]p14:
8208 // An implicitly declared special member function (Clause 12) shall have
8209 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008210 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008211 if (ClassDecl->isInvalidDecl())
8212 return ExceptSpec;
8213
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008214 // Direct base-class destructors.
8215 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8216 BEnd = ClassDecl->bases_end();
8217 B != BEnd; ++B) {
8218 if (B->isVirtual()) // Handled below.
8219 continue;
8220
8221 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008222 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008223 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008224 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008225
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008226 // Virtual base-class destructors.
8227 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8228 BEnd = ClassDecl->vbases_end();
8229 B != BEnd; ++B) {
8230 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008231 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008232 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008233 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008234
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008235 // Field destructors.
8236 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8237 FEnd = ClassDecl->field_end();
8238 F != FEnd; ++F) {
8239 if (const RecordType *RecordTy
8240 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008241 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008242 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008243 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008244
Sean Huntcb45a0f2011-05-12 22:46:25 +00008245 return ExceptSpec;
8246}
8247
8248CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8249 // C++ [class.dtor]p2:
8250 // If a class has no user-declared destructor, a destructor is
8251 // declared implicitly. An implicitly-declared destructor is an
8252 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008253 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008254
Richard Smithafb49182012-11-29 01:34:07 +00008255 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8256 if (DSM.isAlreadyBeingDeclared())
8257 return 0;
8258
Douglas Gregor4923aa22010-07-02 20:37:36 +00008259 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008260 CanQualType ClassType
8261 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008262 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008263 DeclarationName Name
8264 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008265 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008266 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008267 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8268 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008269 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008270 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008271 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008272 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008273
8274 // Build an exception specification pointing back at this destructor.
8275 FunctionProtoType::ExtProtoInfo EPI;
8276 EPI.ExceptionSpecType = EST_Unevaluated;
8277 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008278 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008279
Richard Smithbc2a35d2012-12-08 08:32:28 +00008280 AddOverriddenMethods(ClassDecl, Destructor);
8281
8282 // We don't need to use SpecialMemberIsTrivial here; triviality for
8283 // destructors is easy to compute.
8284 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8285
8286 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008287 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008288
Douglas Gregor4923aa22010-07-02 20:37:36 +00008289 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008290 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008291
Douglas Gregor4923aa22010-07-02 20:37:36 +00008292 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008293 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008294 PushOnScopeChains(Destructor, S, false);
8295 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008296
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008297 return Destructor;
8298}
8299
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008300void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008301 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008302 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008303 !Destructor->doesThisDeclarationHaveABody() &&
8304 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008305 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008306 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008307 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008308
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008309 if (Destructor->isInvalidDecl())
8310 return;
8311
Eli Friedman9a14db32012-10-18 20:14:08 +00008312 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008313
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008314 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008315 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8316 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008317
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008318 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008319 Diag(CurrentLocation, diag::note_member_synthesized_at)
8320 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8321
8322 Destructor->setInvalidDecl();
8323 return;
8324 }
8325
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008326 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008327 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008328 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008329 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008330 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008331
8332 if (ASTMutationListener *L = getASTMutationListener()) {
8333 L->CompletedImplicitDefinition(Destructor);
8334 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008335}
8336
Richard Smitha4156b82012-04-21 18:42:51 +00008337/// \brief Perform any semantic analysis which needs to be delayed until all
8338/// pending class member declarations have been parsed.
8339void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008340 // If the context is an invalid C++ class, just suppress these checks.
8341 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8342 if (Record->isInvalidDecl()) {
8343 DelayedDestructorExceptionSpecChecks.clear();
8344 return;
8345 }
8346 }
8347
Richard Smitha4156b82012-04-21 18:42:51 +00008348 // Perform any deferred checking of exception specifications for virtual
8349 // destructors.
8350 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8351 i != e; ++i) {
8352 const CXXDestructorDecl *Dtor =
8353 DelayedDestructorExceptionSpecChecks[i].first;
8354 assert(!Dtor->getParent()->isDependentType() &&
8355 "Should not ever add destructors of templates into the list.");
8356 CheckOverridingFunctionExceptionSpec(Dtor,
8357 DelayedDestructorExceptionSpecChecks[i].second);
8358 }
8359 DelayedDestructorExceptionSpecChecks.clear();
8360}
8361
Richard Smithb9d0b762012-07-27 04:22:15 +00008362void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8363 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008364 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008365 "adjusting dtor exception specs was introduced in c++11");
8366
Sebastian Redl0ee33912011-05-19 05:13:44 +00008367 // C++11 [class.dtor]p3:
8368 // A declaration of a destructor that does not have an exception-
8369 // specification is implicitly considered to have the same exception-
8370 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008371 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008372 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008373 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008374 return;
8375
Chandler Carruth3f224b22011-09-20 04:55:26 +00008376 // Replace the destructor's type, building off the existing one. Fortunately,
8377 // the only thing of interest in the destructor type is its extended info.
8378 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008379 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8380 EPI.ExceptionSpecType = EST_Unevaluated;
8381 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008382 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008383
Sebastian Redl0ee33912011-05-19 05:13:44 +00008384 // FIXME: If the destructor has a body that could throw, and the newly created
8385 // spec doesn't allow exceptions, we should emit a warning, because this
8386 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008387 // However, we don't have a body or an exception specification yet, so it
8388 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008389}
8390
Richard Smith8c889532012-11-14 00:50:40 +00008391/// When generating a defaulted copy or move assignment operator, if a field
8392/// should be copied with __builtin_memcpy rather than via explicit assignments,
8393/// do so. This optimization only applies for arrays of scalars, and for arrays
8394/// of class type where the selected copy/move-assignment operator is trivial.
8395static StmtResult
8396buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8397 Expr *To, Expr *From) {
8398 // Compute the size of the memory buffer to be copied.
8399 QualType SizeType = S.Context.getSizeType();
8400 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8401 S.Context.getTypeSizeInChars(T).getQuantity());
8402
8403 // Take the address of the field references for "from" and "to". We
8404 // directly construct UnaryOperators here because semantic analysis
8405 // does not permit us to take the address of an xvalue.
8406 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8407 S.Context.getPointerType(From->getType()),
8408 VK_RValue, OK_Ordinary, Loc);
8409 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8410 S.Context.getPointerType(To->getType()),
8411 VK_RValue, OK_Ordinary, Loc);
8412
8413 const Type *E = T->getBaseElementTypeUnsafe();
8414 bool NeedsCollectableMemCpy =
8415 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8416
8417 // Create a reference to the __builtin_objc_memmove_collectable function
8418 StringRef MemCpyName = NeedsCollectableMemCpy ?
8419 "__builtin_objc_memmove_collectable" :
8420 "__builtin_memcpy";
8421 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8422 Sema::LookupOrdinaryName);
8423 S.LookupName(R, S.TUScope, true);
8424
8425 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8426 if (!MemCpy)
8427 // Something went horribly wrong earlier, and we will have complained
8428 // about it.
8429 return StmtError();
8430
8431 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8432 VK_RValue, Loc, 0);
8433 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8434
8435 Expr *CallArgs[] = {
8436 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8437 };
8438 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8439 Loc, CallArgs, Loc);
8440
8441 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8442 return S.Owned(Call.takeAs<Stmt>());
8443}
8444
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008445/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008446/// \c To.
8447///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008448/// This routine is used to copy/move the members of a class with an
8449/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008450/// copied are arrays, this routine builds for loops to copy them.
8451///
8452/// \param S The Sema object used for type-checking.
8453///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008454/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008455///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008456/// \param T The type of the expressions being copied/moved. Both expressions
8457/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008458///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008459/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008460///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008461/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008462///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008463/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008464/// Otherwise, it's a non-static member subobject.
8465///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008466/// \param Copying Whether we're copying or moving.
8467///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008468/// \param Depth Internal parameter recording the depth of the recursion.
8469///
Richard Smith8c889532012-11-14 00:50:40 +00008470/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8471/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008472static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008473buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8474 Expr *To, Expr *From,
8475 bool CopyingBaseSubobject, bool Copying,
8476 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008477 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008478 // Each subobject is assigned in the manner appropriate to its type:
8479 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008480 // - if the subobject is of class type, as if by a call to operator= with
8481 // the subobject as the object expression and the corresponding
8482 // subobject of x as a single function argument (as if by explicit
8483 // qualification; that is, ignoring any possible virtual overriding
8484 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008485 //
8486 // C++03 [class.copy]p13:
8487 // - if the subobject is of class type, the copy assignment operator for
8488 // the class is used (as if by explicit qualification; that is,
8489 // ignoring any possible virtual overriding functions in more derived
8490 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008491 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8492 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008493
Douglas Gregor06a9f362010-05-01 20:49:11 +00008494 // Look for operator=.
8495 DeclarationName Name
8496 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8497 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8498 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008499
Richard Smith044c8aa2012-11-13 00:54:12 +00008500 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8501 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008502 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008503 LookupResult::Filter F = OpLookup.makeFilter();
8504 while (F.hasNext()) {
8505 NamedDecl *D = F.next();
8506 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8507 if (Method->isCopyAssignmentOperator() ||
8508 (!Copying && Method->isMoveAssignmentOperator()))
8509 continue;
8510
8511 F.erase();
8512 }
8513 F.done();
John McCallb0207482010-03-16 06:11:48 +00008514 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008515
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008516 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008517 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008518 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008519 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008520 // ambiguities), we need to cast "this" to that subobject type; to
8521 // ensure that we don't go through the virtual call mechanism, we need
8522 // to qualify the operator= name with the base class (see below). However,
8523 // this means that if the base class has a protected copy assignment
8524 // operator, the protected member access check will fail. So, we
8525 // rewrite "protected" access to "public" access in this case, since we
8526 // know by construction that we're calling from a derived class.
8527 if (CopyingBaseSubobject) {
8528 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8529 L != LEnd; ++L) {
8530 if (L.getAccess() == AS_protected)
8531 L.setAccess(AS_public);
8532 }
8533 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008534
Douglas Gregor06a9f362010-05-01 20:49:11 +00008535 // Create the nested-name-specifier that will be used to qualify the
8536 // reference to operator=; this is required to suppress the virtual
8537 // call mechanism.
8538 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008539 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008540 SS.MakeTrivial(S.Context,
8541 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008542 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008543 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008544
Douglas Gregor06a9f362010-05-01 20:49:11 +00008545 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008546 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008547 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008548 /*TemplateKWLoc=*/SourceLocation(),
8549 /*FirstQualifierInScope=*/0,
8550 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008551 /*TemplateArgs=*/0,
8552 /*SuppressQualifierCheck=*/true);
8553 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008554 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008555
Douglas Gregor06a9f362010-05-01 20:49:11 +00008556 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008557
Richard Smith044c8aa2012-11-13 00:54:12 +00008558 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008559 OpEqualRef.takeAs<Expr>(),
8560 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008561 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008562 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008563
Richard Smith8c889532012-11-14 00:50:40 +00008564 // If we built a call to a trivial 'operator=' while copying an array,
8565 // bail out. We'll replace the whole shebang with a memcpy.
8566 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8567 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8568 return StmtResult((Stmt*)0);
8569
Richard Smith044c8aa2012-11-13 00:54:12 +00008570 // Convert to an expression-statement, and clean up any produced
8571 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008572 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008573 }
John McCallb0207482010-03-16 06:11:48 +00008574
Richard Smith044c8aa2012-11-13 00:54:12 +00008575 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008576 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008577 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008578 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008579 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008580 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008581 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008582 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008583 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008584
8585 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008586 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008587
Douglas Gregor06a9f362010-05-01 20:49:11 +00008588 // Construct a loop over the array bounds, e.g.,
8589 //
8590 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8591 //
8592 // that will copy each of the array elements.
8593 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008594
Douglas Gregor06a9f362010-05-01 20:49:11 +00008595 // Create the iteration variable.
8596 IdentifierInfo *IterationVarName = 0;
8597 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008598 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008599 llvm::raw_svector_ostream OS(Str);
8600 OS << "__i" << Depth;
8601 IterationVarName = &S.Context.Idents.get(OS.str());
8602 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008603 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008604 IterationVarName, SizeType,
8605 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008606 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008607
Douglas Gregor06a9f362010-05-01 20:49:11 +00008608 // Initialize the iteration variable to zero.
8609 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008610 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008611
8612 // Create a reference to the iteration variable; we'll use this several
8613 // times throughout.
8614 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008615 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008616 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008617 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8618 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8619
Douglas Gregor06a9f362010-05-01 20:49:11 +00008620 // Create the DeclStmt that holds the iteration variable.
8621 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008622
Douglas Gregor06a9f362010-05-01 20:49:11 +00008623 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008624 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008625 IterationVarRefRVal,
8626 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008627 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008628 IterationVarRefRVal,
8629 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008630 if (!Copying) // Cast to rvalue
8631 From = CastForMoving(S, From);
8632
8633 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008634 StmtResult Copy =
8635 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8636 To, From, CopyingBaseSubobject,
8637 Copying, Depth + 1);
8638 // Bail out if copying fails or if we determined that we should use memcpy.
8639 if (Copy.isInvalid() || !Copy.get())
8640 return Copy;
8641
8642 // Create the comparison against the array bound.
8643 llvm::APInt Upper
8644 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8645 Expr *Comparison
8646 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8647 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8648 BO_NE, S.Context.BoolTy,
8649 VK_RValue, OK_Ordinary, Loc, false);
8650
8651 // Create the pre-increment of the iteration variable.
8652 Expr *Increment
8653 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8654 VK_LValue, OK_Ordinary, Loc);
8655
Douglas Gregor06a9f362010-05-01 20:49:11 +00008656 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008657 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008658 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008659 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008660 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008661}
8662
Richard Smith8c889532012-11-14 00:50:40 +00008663static StmtResult
8664buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8665 Expr *To, Expr *From,
8666 bool CopyingBaseSubobject, bool Copying) {
8667 // Maybe we should use a memcpy?
8668 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8669 T.isTriviallyCopyableType(S.Context))
8670 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8671
8672 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8673 CopyingBaseSubobject,
8674 Copying, 0));
8675
8676 // If we ended up picking a trivial assignment operator for an array of a
8677 // non-trivially-copyable class type, just emit a memcpy.
8678 if (!Result.isInvalid() && !Result.get())
8679 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8680
8681 return Result;
8682}
8683
Richard Smithb9d0b762012-07-27 04:22:15 +00008684Sema::ImplicitExceptionSpecification
8685Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8686 CXXRecordDecl *ClassDecl = MD->getParent();
8687
8688 ImplicitExceptionSpecification ExceptSpec(*this);
8689 if (ClassDecl->isInvalidDecl())
8690 return ExceptSpec;
8691
8692 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8693 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8694 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8695
Douglas Gregorb87786f2010-07-01 17:48:08 +00008696 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008697 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008698 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008699
8700 // It is unspecified whether or not an implicit copy assignment operator
8701 // attempts to deduplicate calls to assignment operators of virtual bases are
8702 // made. As such, this exception specification is effectively unspecified.
8703 // Based on a similar decision made for constness in C++0x, we're erring on
8704 // the side of assuming such calls to be made regardless of whether they
8705 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008706 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8707 BaseEnd = ClassDecl->bases_end();
8708 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008709 if (Base->isVirtual())
8710 continue;
8711
Douglas Gregora376d102010-07-02 21:50:04 +00008712 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008713 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008714 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8715 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008716 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008717 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008718
8719 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8720 BaseEnd = ClassDecl->vbases_end();
8721 Base != BaseEnd; ++Base) {
8722 CXXRecordDecl *BaseClassDecl
8723 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8724 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8725 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008726 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008727 }
8728
Douglas Gregorb87786f2010-07-01 17:48:08 +00008729 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8730 FieldEnd = ClassDecl->field_end();
8731 Field != FieldEnd;
8732 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008733 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008734 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8735 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008736 LookupCopyingAssignment(FieldClassDecl,
8737 ArgQuals | FieldType.getCVRQualifiers(),
8738 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008739 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008740 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008741 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008742
Richard Smithb9d0b762012-07-27 04:22:15 +00008743 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008744}
8745
8746CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8747 // Note: The following rules are largely analoguous to the copy
8748 // constructor rules. Note that virtual bases are not taken into account
8749 // for determining the argument type of the operator. Note also that
8750 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008751 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008752
Richard Smithafb49182012-11-29 01:34:07 +00008753 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8754 if (DSM.isAlreadyBeingDeclared())
8755 return 0;
8756
Sean Hunt30de05c2011-05-14 05:23:20 +00008757 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8758 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00008759 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
8760 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00008761 ArgType = ArgType.withConst();
8762 ArgType = Context.getLValueReferenceType(ArgType);
8763
Richard Smitha8942d72013-05-07 03:19:20 +00008764 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8765 CXXCopyAssignment,
8766 Const);
8767
Douglas Gregord3c35902010-07-01 16:36:15 +00008768 // An implicitly-declared copy assignment operator is an inline public
8769 // member of its class.
8770 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008771 SourceLocation ClassLoc = ClassDecl->getLocation();
8772 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00008773 CXXMethodDecl *CopyAssignment =
8774 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8775 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
8776 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008777 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008778 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008779 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008780
8781 // Build an exception specification pointing back at this member.
8782 FunctionProtoType::ExtProtoInfo EPI;
8783 EPI.ExceptionSpecType = EST_Unevaluated;
8784 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008785 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008786
Douglas Gregord3c35902010-07-01 16:36:15 +00008787 // Add the parameter to the operator.
8788 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008789 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008790 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008791 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008792 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008793
Richard Smithbc2a35d2012-12-08 08:32:28 +00008794 AddOverriddenMethods(ClassDecl, CopyAssignment);
8795
8796 CopyAssignment->setTrivial(
8797 ClassDecl->needsOverloadResolutionForCopyAssignment()
8798 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8799 : ClassDecl->hasTrivialCopyAssignment());
8800
Richard Smitha8942d72013-05-07 03:19:20 +00008801 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00008802 // .... If the class definition does not explicitly declare a copy
8803 // assignment operator, there is no user-declared move constructor, and
8804 // there is no user-declared move assignment operator, a copy assignment
8805 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008806 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008807 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008808
Richard Smithbc2a35d2012-12-08 08:32:28 +00008809 // Note that we have added this copy-assignment operator.
8810 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8811
8812 if (Scope *S = getScopeForContext(ClassDecl))
8813 PushOnScopeChains(CopyAssignment, S, false);
8814 ClassDecl->addDecl(CopyAssignment);
8815
Douglas Gregord3c35902010-07-01 16:36:15 +00008816 return CopyAssignment;
8817}
8818
Douglas Gregor06a9f362010-05-01 20:49:11 +00008819void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8820 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008821 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008822 CopyAssignOperator->isOverloadedOperator() &&
8823 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008824 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8825 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008826 "DefineImplicitCopyAssignment called for wrong function");
8827
8828 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8829
8830 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8831 CopyAssignOperator->setInvalidDecl();
8832 return;
8833 }
8834
8835 CopyAssignOperator->setUsed();
8836
Eli Friedman9a14db32012-10-18 20:14:08 +00008837 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008838 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008839
8840 // C++0x [class.copy]p30:
8841 // The implicitly-defined or explicitly-defaulted copy assignment operator
8842 // for a non-union class X performs memberwise copy assignment of its
8843 // subobjects. The direct base classes of X are assigned first, in the
8844 // order of their declaration in the base-specifier-list, and then the
8845 // immediate non-static data members of X are assigned, in the order in
8846 // which they were declared in the class definition.
8847
8848 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008849 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008850
8851 // The parameter for the "other" object, which we are copying from.
8852 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8853 Qualifiers OtherQuals = Other->getType().getQualifiers();
8854 QualType OtherRefType = Other->getType();
8855 if (const LValueReferenceType *OtherRef
8856 = OtherRefType->getAs<LValueReferenceType>()) {
8857 OtherRefType = OtherRef->getPointeeType();
8858 OtherQuals = OtherRefType.getQualifiers();
8859 }
8860
8861 // Our location for everything implicitly-generated.
8862 SourceLocation Loc = CopyAssignOperator->getLocation();
8863
8864 // Construct a reference to the "other" object. We'll be using this
8865 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008866 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008867 assert(OtherRef && "Reference to parameter cannot fail!");
8868
8869 // Construct the "this" pointer. We'll be using this throughout the generated
8870 // ASTs.
8871 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8872 assert(This && "Reference to this cannot fail!");
8873
8874 // Assign base classes.
8875 bool Invalid = false;
8876 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8877 E = ClassDecl->bases_end(); Base != E; ++Base) {
8878 // Form the assignment:
8879 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8880 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008881 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008882 Invalid = true;
8883 continue;
8884 }
8885
John McCallf871d0c2010-08-07 06:22:56 +00008886 CXXCastPath BasePath;
8887 BasePath.push_back(Base);
8888
Douglas Gregor06a9f362010-05-01 20:49:11 +00008889 // Construct the "from" expression, which is an implicit cast to the
8890 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008891 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008892 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8893 CK_UncheckedDerivedToBase,
8894 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008895
8896 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008897 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008898
8899 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008900 To = ImpCastExprToType(To.take(),
8901 Context.getCVRQualifiedType(BaseType,
8902 CopyAssignOperator->getTypeQualifiers()),
8903 CK_UncheckedDerivedToBase,
8904 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008905
8906 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008907 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008908 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008909 /*CopyingBaseSubobject=*/true,
8910 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008911 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008912 Diag(CurrentLocation, diag::note_member_synthesized_at)
8913 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8914 CopyAssignOperator->setInvalidDecl();
8915 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008916 }
8917
8918 // Success! Record the copy.
8919 Statements.push_back(Copy.takeAs<Expr>());
8920 }
8921
Douglas Gregor06a9f362010-05-01 20:49:11 +00008922 // Assign non-static members.
8923 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8924 FieldEnd = ClassDecl->field_end();
8925 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008926 if (Field->isUnnamedBitfield())
8927 continue;
8928
Douglas Gregor06a9f362010-05-01 20:49:11 +00008929 // Check for members of reference type; we can't copy those.
8930 if (Field->getType()->isReferenceType()) {
8931 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8932 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8933 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008934 Diag(CurrentLocation, diag::note_member_synthesized_at)
8935 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008936 Invalid = true;
8937 continue;
8938 }
8939
8940 // Check for members of const-qualified, non-class type.
8941 QualType BaseType = Context.getBaseElementType(Field->getType());
8942 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8943 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8944 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8945 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008946 Diag(CurrentLocation, diag::note_member_synthesized_at)
8947 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008948 Invalid = true;
8949 continue;
8950 }
John McCallb77115d2011-06-17 00:18:42 +00008951
8952 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008953 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8954 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008955
8956 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008957 if (FieldType->isIncompleteArrayType()) {
8958 assert(ClassDecl->hasFlexibleArrayMember() &&
8959 "Incomplete array type is not valid");
8960 continue;
8961 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008962
8963 // Build references to the field in the object we're copying from and to.
8964 CXXScopeSpec SS; // Intentionally empty
8965 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8966 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008967 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008968 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008969 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008970 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008971 SS, SourceLocation(), 0,
8972 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008973 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008974 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008975 SS, SourceLocation(), 0,
8976 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008977 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8978 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008979
Douglas Gregor06a9f362010-05-01 20:49:11 +00008980 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008981 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008982 To.get(), From.get(),
8983 /*CopyingBaseSubobject=*/false,
8984 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008985 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008986 Diag(CurrentLocation, diag::note_member_synthesized_at)
8987 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8988 CopyAssignOperator->setInvalidDecl();
8989 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008990 }
8991
8992 // Success! Record the copy.
8993 Statements.push_back(Copy.takeAs<Stmt>());
8994 }
8995
8996 if (!Invalid) {
8997 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008998 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008999
John McCall60d7b3a2010-08-24 06:29:42 +00009000 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009001 if (Return.isInvalid())
9002 Invalid = true;
9003 else {
9004 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009005
9006 if (Trap.hasErrorOccurred()) {
9007 Diag(CurrentLocation, diag::note_member_synthesized_at)
9008 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9009 Invalid = true;
9010 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009011 }
9012 }
9013
9014 if (Invalid) {
9015 CopyAssignOperator->setInvalidDecl();
9016 return;
9017 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009018
9019 StmtResult Body;
9020 {
9021 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009022 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009023 /*isStmtExpr=*/false);
9024 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9025 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009026 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009027
9028 if (ASTMutationListener *L = getASTMutationListener()) {
9029 L->CompletedImplicitDefinition(CopyAssignOperator);
9030 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009031}
9032
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009033Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009034Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9035 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009036
Richard Smithb9d0b762012-07-27 04:22:15 +00009037 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009038 if (ClassDecl->isInvalidDecl())
9039 return ExceptSpec;
9040
9041 // C++0x [except.spec]p14:
9042 // An implicitly declared special member function (Clause 12) shall have an
9043 // exception-specification. [...]
9044
9045 // It is unspecified whether or not an implicit move assignment operator
9046 // attempts to deduplicate calls to assignment operators of virtual bases are
9047 // made. As such, this exception specification is effectively unspecified.
9048 // Based on a similar decision made for constness in C++0x, we're erring on
9049 // the side of assuming such calls to be made regardless of whether they
9050 // actually happen.
9051 // Note that a move constructor is not implicitly declared when there are
9052 // virtual bases, but it can still be user-declared and explicitly defaulted.
9053 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9054 BaseEnd = ClassDecl->bases_end();
9055 Base != BaseEnd; ++Base) {
9056 if (Base->isVirtual())
9057 continue;
9058
9059 CXXRecordDecl *BaseClassDecl
9060 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9061 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009062 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009063 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009064 }
9065
9066 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9067 BaseEnd = ClassDecl->vbases_end();
9068 Base != BaseEnd; ++Base) {
9069 CXXRecordDecl *BaseClassDecl
9070 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9071 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009072 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009073 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009074 }
9075
9076 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9077 FieldEnd = ClassDecl->field_end();
9078 Field != FieldEnd;
9079 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009080 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009081 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009082 if (CXXMethodDecl *MoveAssign =
9083 LookupMovingAssignment(FieldClassDecl,
9084 FieldType.getCVRQualifiers(),
9085 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009086 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009087 }
9088 }
9089
9090 return ExceptSpec;
9091}
9092
Richard Smith1c931be2012-04-02 18:40:40 +00009093/// Determine whether the class type has any direct or indirect virtual base
9094/// classes which have a non-trivial move assignment operator.
9095static bool
9096hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9097 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9098 BaseEnd = ClassDecl->vbases_end();
9099 Base != BaseEnd; ++Base) {
9100 CXXRecordDecl *BaseClass =
9101 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9102
9103 // Try to declare the move assignment. If it would be deleted, then the
9104 // class does not have a non-trivial move assignment.
9105 if (BaseClass->needsImplicitMoveAssignment())
9106 S.DeclareImplicitMoveAssignment(BaseClass);
9107
Richard Smith426391c2012-11-16 00:53:38 +00009108 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009109 return true;
9110 }
9111
9112 return false;
9113}
9114
9115/// Determine whether the given type either has a move constructor or is
9116/// trivially copyable.
9117static bool
9118hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9119 Type = S.Context.getBaseElementType(Type);
9120
9121 // FIXME: Technically, non-trivially-copyable non-class types, such as
9122 // reference types, are supposed to return false here, but that appears
9123 // to be a standard defect.
9124 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009125 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009126 return true;
9127
9128 if (Type.isTriviallyCopyableType(S.Context))
9129 return true;
9130
9131 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009132 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9133 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009134 if (ClassDecl->needsImplicitMoveConstructor())
9135 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009136 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009137 }
9138
Richard Smithe5411b72012-12-01 02:35:44 +00009139 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9140 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009141 if (ClassDecl->needsImplicitMoveAssignment())
9142 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009143 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009144}
9145
9146/// Determine whether all non-static data members and direct or virtual bases
9147/// of class \p ClassDecl have either a move operation, or are trivially
9148/// copyable.
9149static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9150 bool IsConstructor) {
9151 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9152 BaseEnd = ClassDecl->bases_end();
9153 Base != BaseEnd; ++Base) {
9154 if (Base->isVirtual())
9155 continue;
9156
9157 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9158 return false;
9159 }
9160
9161 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9162 BaseEnd = ClassDecl->vbases_end();
9163 Base != BaseEnd; ++Base) {
9164 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9165 return false;
9166 }
9167
9168 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9169 FieldEnd = ClassDecl->field_end();
9170 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009171 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009172 return false;
9173 }
9174
9175 return true;
9176}
9177
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009178CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009179 // C++11 [class.copy]p20:
9180 // If the definition of a class X does not explicitly declare a move
9181 // assignment operator, one will be implicitly declared as defaulted
9182 // if and only if:
9183 //
9184 // - [first 4 bullets]
9185 assert(ClassDecl->needsImplicitMoveAssignment());
9186
Richard Smithafb49182012-11-29 01:34:07 +00009187 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9188 if (DSM.isAlreadyBeingDeclared())
9189 return 0;
9190
Richard Smith1c931be2012-04-02 18:40:40 +00009191 // [Checked after we build the declaration]
9192 // - the move assignment operator would not be implicitly defined as
9193 // deleted,
9194
9195 // [DR1402]:
9196 // - X has no direct or indirect virtual base class with a non-trivial
9197 // move assignment operator, and
9198 // - each of X's non-static data members and direct or virtual base classes
9199 // has a type that either has a move assignment operator or is trivially
9200 // copyable.
9201 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9202 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9203 ClassDecl->setFailedImplicitMoveAssignment();
9204 return 0;
9205 }
9206
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009207 // Note: The following rules are largely analoguous to the move
9208 // constructor rules.
9209
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009210 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9211 QualType RetType = Context.getLValueReferenceType(ArgType);
9212 ArgType = Context.getRValueReferenceType(ArgType);
9213
Richard Smitha8942d72013-05-07 03:19:20 +00009214 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9215 CXXMoveAssignment,
9216 false);
9217
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009218 // An implicitly-declared move assignment operator is an inline public
9219 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009220 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9221 SourceLocation ClassLoc = ClassDecl->getLocation();
9222 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009223 CXXMethodDecl *MoveAssignment =
9224 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9225 /*TInfo=*/0, /*StorageClass=*/SC_None,
9226 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009227 MoveAssignment->setAccess(AS_public);
9228 MoveAssignment->setDefaulted();
9229 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009230
Richard Smithb9d0b762012-07-27 04:22:15 +00009231 // Build an exception specification pointing back at this member.
9232 FunctionProtoType::ExtProtoInfo EPI;
9233 EPI.ExceptionSpecType = EST_Unevaluated;
9234 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009235 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009236
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009237 // Add the parameter to the operator.
9238 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9239 ClassLoc, ClassLoc, /*Id=*/0,
9240 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009241 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009242 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009243
Richard Smithbc2a35d2012-12-08 08:32:28 +00009244 AddOverriddenMethods(ClassDecl, MoveAssignment);
9245
9246 MoveAssignment->setTrivial(
9247 ClassDecl->needsOverloadResolutionForMoveAssignment()
9248 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9249 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009250
9251 // C++0x [class.copy]p9:
9252 // If the definition of a class X does not explicitly declare a move
9253 // assignment operator, one will be implicitly declared as defaulted if and
9254 // only if:
9255 // [...]
9256 // - the move assignment operator would not be implicitly defined as
9257 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009258 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009259 // Cache this result so that we don't try to generate this over and over
9260 // on every lookup, leaking memory and wasting time.
9261 ClassDecl->setFailedImplicitMoveAssignment();
9262 return 0;
9263 }
9264
Richard Smithbc2a35d2012-12-08 08:32:28 +00009265 // Note that we have added this copy-assignment operator.
9266 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9267
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009268 if (Scope *S = getScopeForContext(ClassDecl))
9269 PushOnScopeChains(MoveAssignment, S, false);
9270 ClassDecl->addDecl(MoveAssignment);
9271
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009272 return MoveAssignment;
9273}
9274
9275void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9276 CXXMethodDecl *MoveAssignOperator) {
9277 assert((MoveAssignOperator->isDefaulted() &&
9278 MoveAssignOperator->isOverloadedOperator() &&
9279 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009280 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9281 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009282 "DefineImplicitMoveAssignment called for wrong function");
9283
9284 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9285
9286 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9287 MoveAssignOperator->setInvalidDecl();
9288 return;
9289 }
9290
9291 MoveAssignOperator->setUsed();
9292
Eli Friedman9a14db32012-10-18 20:14:08 +00009293 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009294 DiagnosticErrorTrap Trap(Diags);
9295
9296 // C++0x [class.copy]p28:
9297 // The implicitly-defined or move assignment operator for a non-union class
9298 // X performs memberwise move assignment of its subobjects. The direct base
9299 // classes of X are assigned first, in the order of their declaration in the
9300 // base-specifier-list, and then the immediate non-static data members of X
9301 // are assigned, in the order in which they were declared in the class
9302 // definition.
9303
9304 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009305 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009306
9307 // The parameter for the "other" object, which we are move from.
9308 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9309 QualType OtherRefType = Other->getType()->
9310 getAs<RValueReferenceType>()->getPointeeType();
9311 assert(OtherRefType.getQualifiers() == 0 &&
9312 "Bad argument type of defaulted move assignment");
9313
9314 // Our location for everything implicitly-generated.
9315 SourceLocation Loc = MoveAssignOperator->getLocation();
9316
9317 // Construct a reference to the "other" object. We'll be using this
9318 // throughout the generated ASTs.
9319 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9320 assert(OtherRef && "Reference to parameter cannot fail!");
9321 // Cast to rvalue.
9322 OtherRef = CastForMoving(*this, OtherRef);
9323
9324 // Construct the "this" pointer. We'll be using this throughout the generated
9325 // ASTs.
9326 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9327 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009328
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009329 // Assign base classes.
9330 bool Invalid = false;
9331 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9332 E = ClassDecl->bases_end(); Base != E; ++Base) {
9333 // Form the assignment:
9334 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9335 QualType BaseType = Base->getType().getUnqualifiedType();
9336 if (!BaseType->isRecordType()) {
9337 Invalid = true;
9338 continue;
9339 }
9340
9341 CXXCastPath BasePath;
9342 BasePath.push_back(Base);
9343
9344 // Construct the "from" expression, which is an implicit cast to the
9345 // appropriately-qualified base type.
9346 Expr *From = OtherRef;
9347 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009348 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009349
9350 // Dereference "this".
9351 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9352
9353 // Implicitly cast "this" to the appropriately-qualified base type.
9354 To = ImpCastExprToType(To.take(),
9355 Context.getCVRQualifiedType(BaseType,
9356 MoveAssignOperator->getTypeQualifiers()),
9357 CK_UncheckedDerivedToBase,
9358 VK_LValue, &BasePath);
9359
9360 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009361 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009362 To.get(), From,
9363 /*CopyingBaseSubobject=*/true,
9364 /*Copying=*/false);
9365 if (Move.isInvalid()) {
9366 Diag(CurrentLocation, diag::note_member_synthesized_at)
9367 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9368 MoveAssignOperator->setInvalidDecl();
9369 return;
9370 }
9371
9372 // Success! Record the move.
9373 Statements.push_back(Move.takeAs<Expr>());
9374 }
9375
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009376 // Assign non-static members.
9377 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9378 FieldEnd = ClassDecl->field_end();
9379 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009380 if (Field->isUnnamedBitfield())
9381 continue;
9382
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009383 // Check for members of reference type; we can't move those.
9384 if (Field->getType()->isReferenceType()) {
9385 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9386 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9387 Diag(Field->getLocation(), diag::note_declared_at);
9388 Diag(CurrentLocation, diag::note_member_synthesized_at)
9389 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9390 Invalid = true;
9391 continue;
9392 }
9393
9394 // Check for members of const-qualified, non-class type.
9395 QualType BaseType = Context.getBaseElementType(Field->getType());
9396 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9397 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9398 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9399 Diag(Field->getLocation(), diag::note_declared_at);
9400 Diag(CurrentLocation, diag::note_member_synthesized_at)
9401 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9402 Invalid = true;
9403 continue;
9404 }
9405
9406 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009407 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9408 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009409
9410 QualType FieldType = Field->getType().getNonReferenceType();
9411 if (FieldType->isIncompleteArrayType()) {
9412 assert(ClassDecl->hasFlexibleArrayMember() &&
9413 "Incomplete array type is not valid");
9414 continue;
9415 }
9416
9417 // Build references to the field in the object we're copying from and to.
9418 CXXScopeSpec SS; // Intentionally empty
9419 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9420 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009421 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009422 MemberLookup.resolveKind();
9423 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9424 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009425 SS, SourceLocation(), 0,
9426 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009427 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9428 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009429 SS, SourceLocation(), 0,
9430 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009431 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9432 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9433
9434 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9435 "Member reference with rvalue base must be rvalue except for reference "
9436 "members, which aren't allowed for move assignment.");
9437
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009438 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009439 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009440 To.get(), From.get(),
9441 /*CopyingBaseSubobject=*/false,
9442 /*Copying=*/false);
9443 if (Move.isInvalid()) {
9444 Diag(CurrentLocation, diag::note_member_synthesized_at)
9445 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9446 MoveAssignOperator->setInvalidDecl();
9447 return;
9448 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009449
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009450 // Success! Record the copy.
9451 Statements.push_back(Move.takeAs<Stmt>());
9452 }
9453
9454 if (!Invalid) {
9455 // Add a "return *this;"
9456 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9457
9458 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9459 if (Return.isInvalid())
9460 Invalid = true;
9461 else {
9462 Statements.push_back(Return.takeAs<Stmt>());
9463
9464 if (Trap.hasErrorOccurred()) {
9465 Diag(CurrentLocation, diag::note_member_synthesized_at)
9466 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9467 Invalid = true;
9468 }
9469 }
9470 }
9471
9472 if (Invalid) {
9473 MoveAssignOperator->setInvalidDecl();
9474 return;
9475 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009476
9477 StmtResult Body;
9478 {
9479 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009480 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009481 /*isStmtExpr=*/false);
9482 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9483 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009484 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9485
9486 if (ASTMutationListener *L = getASTMutationListener()) {
9487 L->CompletedImplicitDefinition(MoveAssignOperator);
9488 }
9489}
9490
Richard Smithb9d0b762012-07-27 04:22:15 +00009491Sema::ImplicitExceptionSpecification
9492Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9493 CXXRecordDecl *ClassDecl = MD->getParent();
9494
9495 ImplicitExceptionSpecification ExceptSpec(*this);
9496 if (ClassDecl->isInvalidDecl())
9497 return ExceptSpec;
9498
9499 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9500 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9501 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9502
Douglas Gregor0d405db2010-07-01 20:59:04 +00009503 // C++ [except.spec]p14:
9504 // An implicitly declared special member function (Clause 12) shall have an
9505 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009506 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9507 BaseEnd = ClassDecl->bases_end();
9508 Base != BaseEnd;
9509 ++Base) {
9510 // Virtual bases are handled below.
9511 if (Base->isVirtual())
9512 continue;
9513
Douglas Gregor22584312010-07-02 23:41:54 +00009514 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009515 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009516 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009517 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009518 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009519 }
9520 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9521 BaseEnd = ClassDecl->vbases_end();
9522 Base != BaseEnd;
9523 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009524 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009525 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009526 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009527 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009528 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009529 }
9530 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9531 FieldEnd = ClassDecl->field_end();
9532 Field != FieldEnd;
9533 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009534 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009535 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9536 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009537 LookupCopyingConstructor(FieldClassDecl,
9538 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009539 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009540 }
9541 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009542
Richard Smithb9d0b762012-07-27 04:22:15 +00009543 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009544}
9545
9546CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9547 CXXRecordDecl *ClassDecl) {
9548 // C++ [class.copy]p4:
9549 // If the class definition does not explicitly declare a copy
9550 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009551 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009552
Richard Smithafb49182012-11-29 01:34:07 +00009553 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9554 if (DSM.isAlreadyBeingDeclared())
9555 return 0;
9556
Sean Hunt49634cf2011-05-13 06:10:58 +00009557 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9558 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009559 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009560 if (Const)
9561 ArgType = ArgType.withConst();
9562 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009563
Richard Smith7756afa2012-06-10 05:43:50 +00009564 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9565 CXXCopyConstructor,
9566 Const);
9567
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009568 DeclarationName Name
9569 = Context.DeclarationNames.getCXXConstructorName(
9570 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009571 SourceLocation ClassLoc = ClassDecl->getLocation();
9572 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009573
9574 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009575 // member of its class.
9576 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009577 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009578 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009579 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009580 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009581 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009582
Richard Smithb9d0b762012-07-27 04:22:15 +00009583 // Build an exception specification pointing back at this member.
9584 FunctionProtoType::ExtProtoInfo EPI;
9585 EPI.ExceptionSpecType = EST_Unevaluated;
9586 EPI.ExceptionSpecDecl = CopyConstructor;
9587 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009588 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009589
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009590 // Add the parameter to the constructor.
9591 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009592 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009593 /*IdentifierInfo=*/0,
9594 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009595 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009596 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009597
Richard Smithbc2a35d2012-12-08 08:32:28 +00009598 CopyConstructor->setTrivial(
9599 ClassDecl->needsOverloadResolutionForCopyConstructor()
9600 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9601 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009602
Nico Weberafcc96a2012-01-23 03:19:29 +00009603 // C++11 [class.copy]p8:
9604 // ... If the class definition does not explicitly declare a copy
9605 // constructor, there is no user-declared move constructor, and there is no
9606 // user-declared move assignment operator, a copy constructor is implicitly
9607 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009608 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009609 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009610
Richard Smithbc2a35d2012-12-08 08:32:28 +00009611 // Note that we have declared this constructor.
9612 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9613
9614 if (Scope *S = getScopeForContext(ClassDecl))
9615 PushOnScopeChains(CopyConstructor, S, false);
9616 ClassDecl->addDecl(CopyConstructor);
9617
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009618 return CopyConstructor;
9619}
9620
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009621void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009622 CXXConstructorDecl *CopyConstructor) {
9623 assert((CopyConstructor->isDefaulted() &&
9624 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009625 !CopyConstructor->doesThisDeclarationHaveABody() &&
9626 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009627 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009628
Anders Carlsson63010a72010-04-23 16:24:12 +00009629 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009630 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009631
Eli Friedman9a14db32012-10-18 20:14:08 +00009632 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009633 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009634
David Blaikie93c86172013-01-17 05:26:25 +00009635 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009636 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009637 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009638 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009639 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009640 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009641 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009642 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9643 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009644 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009645 /*isStmtExpr=*/false)
9646 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009647 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009648 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009649
9650 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009651 if (ASTMutationListener *L = getASTMutationListener()) {
9652 L->CompletedImplicitDefinition(CopyConstructor);
9653 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009654}
9655
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009656Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009657Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9658 CXXRecordDecl *ClassDecl = MD->getParent();
9659
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009660 // C++ [except.spec]p14:
9661 // An implicitly declared special member function (Clause 12) shall have an
9662 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009663 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009664 if (ClassDecl->isInvalidDecl())
9665 return ExceptSpec;
9666
9667 // Direct base-class constructors.
9668 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9669 BEnd = ClassDecl->bases_end();
9670 B != BEnd; ++B) {
9671 if (B->isVirtual()) // Handled below.
9672 continue;
9673
9674 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9675 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009676 CXXConstructorDecl *Constructor =
9677 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009678 // If this is a deleted function, add it anyway. This might be conformant
9679 // with the standard. This might not. I'm not sure. It might not matter.
9680 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009681 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009682 }
9683 }
9684
9685 // Virtual base-class constructors.
9686 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9687 BEnd = ClassDecl->vbases_end();
9688 B != BEnd; ++B) {
9689 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9690 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009691 CXXConstructorDecl *Constructor =
9692 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009693 // If this is a deleted function, add it anyway. This might be conformant
9694 // with the standard. This might not. I'm not sure. It might not matter.
9695 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009696 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009697 }
9698 }
9699
9700 // Field constructors.
9701 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9702 FEnd = ClassDecl->field_end();
9703 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009704 QualType FieldType = Context.getBaseElementType(F->getType());
9705 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9706 CXXConstructorDecl *Constructor =
9707 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009708 // If this is a deleted function, add it anyway. This might be conformant
9709 // with the standard. This might not. I'm not sure. It might not matter.
9710 // In particular, the problem is that this function never gets called. It
9711 // might just be ill-formed because this function attempts to refer to
9712 // a deleted function here.
9713 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009714 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009715 }
9716 }
9717
9718 return ExceptSpec;
9719}
9720
9721CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9722 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009723 // C++11 [class.copy]p9:
9724 // If the definition of a class X does not explicitly declare a move
9725 // constructor, one will be implicitly declared as defaulted if and only if:
9726 //
9727 // - [first 4 bullets]
9728 assert(ClassDecl->needsImplicitMoveConstructor());
9729
Richard Smithafb49182012-11-29 01:34:07 +00009730 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9731 if (DSM.isAlreadyBeingDeclared())
9732 return 0;
9733
Richard Smith1c931be2012-04-02 18:40:40 +00009734 // [Checked after we build the declaration]
9735 // - the move assignment operator would not be implicitly defined as
9736 // deleted,
9737
9738 // [DR1402]:
9739 // - each of X's non-static data members and direct or virtual base classes
9740 // has a type that either has a move constructor or is trivially copyable.
9741 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9742 ClassDecl->setFailedImplicitMoveConstructor();
9743 return 0;
9744 }
9745
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009746 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9747 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009748
Richard Smith7756afa2012-06-10 05:43:50 +00009749 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9750 CXXMoveConstructor,
9751 false);
9752
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009753 DeclarationName Name
9754 = Context.DeclarationNames.getCXXConstructorName(
9755 Context.getCanonicalType(ClassType));
9756 SourceLocation ClassLoc = ClassDecl->getLocation();
9757 DeclarationNameInfo NameInfo(Name, ClassLoc);
9758
Richard Smitha8942d72013-05-07 03:19:20 +00009759 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009760 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009761 // member of its class.
9762 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009763 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009764 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009765 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009766 MoveConstructor->setAccess(AS_public);
9767 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009768
Richard Smithb9d0b762012-07-27 04:22:15 +00009769 // Build an exception specification pointing back at this member.
9770 FunctionProtoType::ExtProtoInfo EPI;
9771 EPI.ExceptionSpecType = EST_Unevaluated;
9772 EPI.ExceptionSpecDecl = MoveConstructor;
9773 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009774 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009775
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009776 // Add the parameter to the constructor.
9777 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9778 ClassLoc, ClassLoc,
9779 /*IdentifierInfo=*/0,
9780 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009781 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009782 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009783
Richard Smithbc2a35d2012-12-08 08:32:28 +00009784 MoveConstructor->setTrivial(
9785 ClassDecl->needsOverloadResolutionForMoveConstructor()
9786 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9787 : ClassDecl->hasTrivialMoveConstructor());
9788
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009789 // C++0x [class.copy]p9:
9790 // If the definition of a class X does not explicitly declare a move
9791 // constructor, one will be implicitly declared as defaulted if and only if:
9792 // [...]
9793 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009794 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009795 // Cache this result so that we don't try to generate this over and over
9796 // on every lookup, leaking memory and wasting time.
9797 ClassDecl->setFailedImplicitMoveConstructor();
9798 return 0;
9799 }
9800
9801 // Note that we have declared this constructor.
9802 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9803
9804 if (Scope *S = getScopeForContext(ClassDecl))
9805 PushOnScopeChains(MoveConstructor, S, false);
9806 ClassDecl->addDecl(MoveConstructor);
9807
9808 return MoveConstructor;
9809}
9810
9811void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9812 CXXConstructorDecl *MoveConstructor) {
9813 assert((MoveConstructor->isDefaulted() &&
9814 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009815 !MoveConstructor->doesThisDeclarationHaveABody() &&
9816 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009817 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9818
9819 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9820 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9821
Eli Friedman9a14db32012-10-18 20:14:08 +00009822 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009823 DiagnosticErrorTrap Trap(Diags);
9824
David Blaikie93c86172013-01-17 05:26:25 +00009825 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009826 Trap.hasErrorOccurred()) {
9827 Diag(CurrentLocation, diag::note_member_synthesized_at)
9828 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9829 MoveConstructor->setInvalidDecl();
9830 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009831 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009832 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9833 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009834 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009835 /*isStmtExpr=*/false)
9836 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009837 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009838 }
9839
9840 MoveConstructor->setUsed();
9841
9842 if (ASTMutationListener *L = getASTMutationListener()) {
9843 L->CompletedImplicitDefinition(MoveConstructor);
9844 }
9845}
9846
Douglas Gregore4e68d42012-02-15 19:33:52 +00009847bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9848 return FD->isDeleted() &&
9849 (FD->isDefaulted() || FD->isImplicit()) &&
9850 isa<CXXMethodDecl>(FD);
9851}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009852
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009853/// \brief Mark the call operator of the given lambda closure type as "used".
9854static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9855 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009856 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009857 Lambda->lookup(
9858 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009859 CallOperator->setReferenced();
9860 CallOperator->setUsed();
9861}
9862
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009863void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9864 SourceLocation CurrentLocation,
9865 CXXConversionDecl *Conv)
9866{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009867 CXXRecordDecl *Lambda = Conv->getParent();
9868
9869 // Make sure that the lambda call operator is marked used.
9870 markLambdaCallOperatorUsed(*this, Lambda);
9871
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009872 Conv->setUsed();
9873
Eli Friedman9a14db32012-10-18 20:14:08 +00009874 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009875 DiagnosticErrorTrap Trap(Diags);
9876
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009877 // Return the address of the __invoke function.
9878 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9879 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009880 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009881 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9882 VK_LValue, Conv->getLocation()).take();
9883 assert(FunctionRef && "Can't refer to __invoke function?");
9884 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009885 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009886 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009887 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009888
9889 // Fill in the __invoke function with a dummy implementation. IR generation
9890 // will fill in the actual details.
9891 Invoke->setUsed();
9892 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009893 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009894
9895 if (ASTMutationListener *L = getASTMutationListener()) {
9896 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009897 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009898 }
9899}
9900
9901void Sema::DefineImplicitLambdaToBlockPointerConversion(
9902 SourceLocation CurrentLocation,
9903 CXXConversionDecl *Conv)
9904{
9905 Conv->setUsed();
9906
Eli Friedman9a14db32012-10-18 20:14:08 +00009907 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009908 DiagnosticErrorTrap Trap(Diags);
9909
Douglas Gregorac1303e2012-02-22 05:02:47 +00009910 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009911 Expr *This = ActOnCXXThis(CurrentLocation).take();
9912 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009913
Eli Friedman23f02672012-03-01 04:01:32 +00009914 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9915 Conv->getLocation(),
9916 Conv, DerefThis);
9917
9918 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9919 // behavior. Note that only the general conversion function does this
9920 // (since it's unusable otherwise); in the case where we inline the
9921 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009922 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009923 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9924 CK_CopyAndAutoreleaseBlockObject,
9925 BuildBlock.get(), 0, VK_RValue);
9926
9927 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009928 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009929 Conv->setInvalidDecl();
9930 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009931 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009932
Douglas Gregorac1303e2012-02-22 05:02:47 +00009933 // Create the return statement that returns the block from the conversion
9934 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009935 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009936 if (Return.isInvalid()) {
9937 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9938 Conv->setInvalidDecl();
9939 return;
9940 }
9941
9942 // Set the body of the conversion function.
9943 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009944 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009945 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009946 Conv->getLocation()));
9947
Douglas Gregorac1303e2012-02-22 05:02:47 +00009948 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009949 if (ASTMutationListener *L = getASTMutationListener()) {
9950 L->CompletedImplicitDefinition(Conv);
9951 }
9952}
9953
Douglas Gregorf52757d2012-03-10 06:53:13 +00009954/// \brief Determine whether the given list arguments contains exactly one
9955/// "real" (non-default) argument.
9956static bool hasOneRealArgument(MultiExprArg Args) {
9957 switch (Args.size()) {
9958 case 0:
9959 return false;
9960
9961 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009962 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009963 return false;
9964
9965 // fall through
9966 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009967 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009968 }
9969
9970 return false;
9971}
9972
John McCall60d7b3a2010-08-24 06:29:42 +00009973ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009974Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009975 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009976 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009977 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009978 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009979 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009980 unsigned ConstructKind,
9981 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009982 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009983
Douglas Gregor2f599792010-04-02 18:24:57 +00009984 // C++0x [class.copy]p34:
9985 // When certain criteria are met, an implementation is allowed to
9986 // omit the copy/move construction of a class object, even if the
9987 // copy/move constructor and/or destructor for the object have
9988 // side effects. [...]
9989 // - when a temporary class object that has not been bound to a
9990 // reference (12.2) would be copied/moved to a class object
9991 // with the same cv-unqualified type, the copy/move operation
9992 // can be omitted by constructing the temporary object
9993 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009994 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009995 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009996 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009997 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009998 }
Mike Stump1eb44332009-09-09 15:08:12 +00009999
10000 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010001 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010002 IsListInitialization, RequiresZeroInit,
10003 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010004}
10005
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010006/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10007/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010008ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010009Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10010 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010011 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010012 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010013 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010014 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010015 unsigned ConstructKind,
10016 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010017 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010018 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010019 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010020 HadMultipleCandidates,
10021 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010022 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10023 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010024}
10025
John McCall68c6c9a2010-02-02 09:10:11 +000010026void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010027 if (VD->isInvalidDecl()) return;
10028
John McCall68c6c9a2010-02-02 09:10:11 +000010029 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010030 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010031 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010032 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010033
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010034 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010035 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010036 CheckDestructorAccess(VD->getLocation(), Destructor,
10037 PDiag(diag::err_access_dtor_var)
10038 << VD->getDeclName()
10039 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010040 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010041
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010042 if (!VD->hasGlobalStorage()) return;
10043
10044 // Emit warning for non-trivial dtor in global scope (a real global,
10045 // class-static, function-static).
10046 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10047
10048 // TODO: this should be re-enabled for static locals by !CXAAtExit
10049 if (!VD->isStaticLocal())
10050 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010051}
10052
Douglas Gregor39da0b82009-09-09 23:08:42 +000010053/// \brief Given a constructor and the set of arguments provided for the
10054/// constructor, convert the arguments and add any required default arguments
10055/// to form a proper call to this constructor.
10056///
10057/// \returns true if an error occurred, false otherwise.
10058bool
10059Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10060 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010061 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010062 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010063 bool AllowExplicit,
10064 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010065 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10066 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010067 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010068
10069 const FunctionProtoType *Proto
10070 = Constructor->getType()->getAs<FunctionProtoType>();
10071 assert(Proto && "Constructor without a prototype?");
10072 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010073
10074 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010075 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010076 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010077 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010078 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010079
10080 VariadicCallType CallType =
10081 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010082 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010083 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10084 Proto, 0, Args, NumArgs, AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010085 CallType, AllowExplicit,
10086 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010087 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010088
10089 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
10090
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010091 CheckConstructorCall(Constructor,
10092 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10093 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010094 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010095
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010096 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010097}
10098
Anders Carlsson20d45d22009-12-12 00:32:00 +000010099static inline bool
10100CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10101 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010102 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010103 if (isa<NamespaceDecl>(DC)) {
10104 return SemaRef.Diag(FnDecl->getLocation(),
10105 diag::err_operator_new_delete_declared_in_namespace)
10106 << FnDecl->getDeclName();
10107 }
10108
10109 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010110 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010111 return SemaRef.Diag(FnDecl->getLocation(),
10112 diag::err_operator_new_delete_declared_static)
10113 << FnDecl->getDeclName();
10114 }
10115
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010116 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010117}
10118
Anders Carlsson156c78e2009-12-13 17:53:43 +000010119static inline bool
10120CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10121 CanQualType ExpectedResultType,
10122 CanQualType ExpectedFirstParamType,
10123 unsigned DependentParamTypeDiag,
10124 unsigned InvalidParamTypeDiag) {
10125 QualType ResultType =
10126 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10127
10128 // Check that the result type is not dependent.
10129 if (ResultType->isDependentType())
10130 return SemaRef.Diag(FnDecl->getLocation(),
10131 diag::err_operator_new_delete_dependent_result_type)
10132 << FnDecl->getDeclName() << ExpectedResultType;
10133
10134 // Check that the result type is what we expect.
10135 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10136 return SemaRef.Diag(FnDecl->getLocation(),
10137 diag::err_operator_new_delete_invalid_result_type)
10138 << FnDecl->getDeclName() << ExpectedResultType;
10139
10140 // A function template must have at least 2 parameters.
10141 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10142 return SemaRef.Diag(FnDecl->getLocation(),
10143 diag::err_operator_new_delete_template_too_few_parameters)
10144 << FnDecl->getDeclName();
10145
10146 // The function decl must have at least 1 parameter.
10147 if (FnDecl->getNumParams() == 0)
10148 return SemaRef.Diag(FnDecl->getLocation(),
10149 diag::err_operator_new_delete_too_few_parameters)
10150 << FnDecl->getDeclName();
10151
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010152 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010153 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10154 if (FirstParamType->isDependentType())
10155 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10156 << FnDecl->getDeclName() << ExpectedFirstParamType;
10157
10158 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010159 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010160 ExpectedFirstParamType)
10161 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10162 << FnDecl->getDeclName() << ExpectedFirstParamType;
10163
10164 return false;
10165}
10166
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010167static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010168CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010169 // C++ [basic.stc.dynamic.allocation]p1:
10170 // A program is ill-formed if an allocation function is declared in a
10171 // namespace scope other than global scope or declared static in global
10172 // scope.
10173 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10174 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010175
10176 CanQualType SizeTy =
10177 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10178
10179 // C++ [basic.stc.dynamic.allocation]p1:
10180 // The return type shall be void*. The first parameter shall have type
10181 // std::size_t.
10182 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10183 SizeTy,
10184 diag::err_operator_new_dependent_param_type,
10185 diag::err_operator_new_param_type))
10186 return true;
10187
10188 // C++ [basic.stc.dynamic.allocation]p1:
10189 // The first parameter shall not have an associated default argument.
10190 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010191 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010192 diag::err_operator_new_default_arg)
10193 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10194
10195 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010196}
10197
10198static bool
Richard Smith444d3842012-10-20 08:26:51 +000010199CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010200 // C++ [basic.stc.dynamic.deallocation]p1:
10201 // A program is ill-formed if deallocation functions are declared in a
10202 // namespace scope other than global scope or declared static in global
10203 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010204 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10205 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010206
10207 // C++ [basic.stc.dynamic.deallocation]p2:
10208 // Each deallocation function shall return void and its first parameter
10209 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010210 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10211 SemaRef.Context.VoidPtrTy,
10212 diag::err_operator_delete_dependent_param_type,
10213 diag::err_operator_delete_param_type))
10214 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010215
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010216 return false;
10217}
10218
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010219/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10220/// of this overloaded operator is well-formed. If so, returns false;
10221/// otherwise, emits appropriate diagnostics and returns true.
10222bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010223 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010224 "Expected an overloaded operator declaration");
10225
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010226 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10227
Mike Stump1eb44332009-09-09 15:08:12 +000010228 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010229 // The allocation and deallocation functions, operator new,
10230 // operator new[], operator delete and operator delete[], are
10231 // described completely in 3.7.3. The attributes and restrictions
10232 // found in the rest of this subclause do not apply to them unless
10233 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010234 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010235 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010236
Anders Carlssona3ccda52009-12-12 00:26:23 +000010237 if (Op == OO_New || Op == OO_Array_New)
10238 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010239
10240 // C++ [over.oper]p6:
10241 // An operator function shall either be a non-static member
10242 // function or be a non-member function and have at least one
10243 // parameter whose type is a class, a reference to a class, an
10244 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010245 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10246 if (MethodDecl->isStatic())
10247 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010248 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010249 } else {
10250 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010251 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10252 ParamEnd = FnDecl->param_end();
10253 Param != ParamEnd; ++Param) {
10254 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010255 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10256 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010257 ClassOrEnumParam = true;
10258 break;
10259 }
10260 }
10261
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010262 if (!ClassOrEnumParam)
10263 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010264 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010265 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010266 }
10267
10268 // C++ [over.oper]p8:
10269 // An operator function cannot have default arguments (8.3.6),
10270 // except where explicitly stated below.
10271 //
Mike Stump1eb44332009-09-09 15:08:12 +000010272 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010273 // (C++ [over.call]p1).
10274 if (Op != OO_Call) {
10275 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10276 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010277 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010278 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010279 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010280 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010281 }
10282 }
10283
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010284 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10285 { false, false, false }
10286#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10287 , { Unary, Binary, MemberOnly }
10288#include "clang/Basic/OperatorKinds.def"
10289 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010290
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010291 bool CanBeUnaryOperator = OperatorUses[Op][0];
10292 bool CanBeBinaryOperator = OperatorUses[Op][1];
10293 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010294
10295 // C++ [over.oper]p8:
10296 // [...] Operator functions cannot have more or fewer parameters
10297 // than the number required for the corresponding operator, as
10298 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010299 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010300 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010301 if (Op != OO_Call &&
10302 ((NumParams == 1 && !CanBeUnaryOperator) ||
10303 (NumParams == 2 && !CanBeBinaryOperator) ||
10304 (NumParams < 1) || (NumParams > 2))) {
10305 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010306 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010307 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010308 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010309 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010310 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010311 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010312 assert(CanBeBinaryOperator &&
10313 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010314 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010315 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010316
Chris Lattner416e46f2008-11-21 07:57:12 +000010317 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010318 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010319 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010320
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010321 // Overloaded operators other than operator() cannot be variadic.
10322 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010323 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010324 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010325 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010326 }
10327
10328 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010329 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10330 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010331 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010332 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010333 }
10334
10335 // C++ [over.inc]p1:
10336 // The user-defined function called operator++ implements the
10337 // prefix and postfix ++ operator. If this function is a member
10338 // function with no parameters, or a non-member function with one
10339 // parameter of class or enumeration type, it defines the prefix
10340 // increment operator ++ for objects of that type. If the function
10341 // is a member function with one parameter (which shall be of type
10342 // int) or a non-member function with two parameters (the second
10343 // of which shall be of type int), it defines the postfix
10344 // increment operator ++ for objects of that type.
10345 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10346 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10347 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010348 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010349 ParamIsInt = BT->getKind() == BuiltinType::Int;
10350
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010351 if (!ParamIsInt)
10352 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010353 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010354 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010355 }
10356
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010357 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010358}
Chris Lattner5a003a42008-12-17 07:09:26 +000010359
Sean Hunta6c058d2010-01-13 09:01:02 +000010360/// CheckLiteralOperatorDeclaration - Check whether the declaration
10361/// of this literal operator function is well-formed. If so, returns
10362/// false; otherwise, emits appropriate diagnostics and returns true.
10363bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010364 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010365 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10366 << FnDecl->getDeclName();
10367 return true;
10368 }
10369
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010370 if (FnDecl->isExternC()) {
10371 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10372 return true;
10373 }
10374
Sean Hunta6c058d2010-01-13 09:01:02 +000010375 bool Valid = false;
10376
Richard Smith36f5cfe2012-03-09 08:00:36 +000010377 // This might be the definition of a literal operator template.
10378 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10379 // This might be a specialization of a literal operator template.
10380 if (!TpDecl)
10381 TpDecl = FnDecl->getPrimaryTemplate();
10382
Sean Hunt216c2782010-04-07 23:11:06 +000010383 // template <char...> type operator "" name() is the only valid template
10384 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010385 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010386 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010387 // Must have only one template parameter
10388 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10389 if (Params->size() == 1) {
10390 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010391 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010392
Sean Hunt216c2782010-04-07 23:11:06 +000010393 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010394 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10395 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10396 Valid = true;
10397 }
10398 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010399 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010400 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010401 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10402
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010403 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010404
Sean Hunt30019c02010-04-07 22:57:35 +000010405 // unsigned long long int, long double, and any character type are allowed
10406 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010407 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10408 Context.hasSameType(T, Context.LongDoubleTy) ||
10409 Context.hasSameType(T, Context.CharTy) ||
10410 Context.hasSameType(T, Context.WCharTy) ||
10411 Context.hasSameType(T, Context.Char16Ty) ||
10412 Context.hasSameType(T, Context.Char32Ty)) {
10413 if (++Param == FnDecl->param_end())
10414 Valid = true;
10415 goto FinishedParams;
10416 }
10417
Sean Hunt30019c02010-04-07 22:57:35 +000010418 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010419 const PointerType *PT = T->getAs<PointerType>();
10420 if (!PT)
10421 goto FinishedParams;
10422 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010423 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010424 goto FinishedParams;
10425 T = T.getUnqualifiedType();
10426
10427 // Move on to the second parameter;
10428 ++Param;
10429
10430 // If there is no second parameter, the first must be a const char *
10431 if (Param == FnDecl->param_end()) {
10432 if (Context.hasSameType(T, Context.CharTy))
10433 Valid = true;
10434 goto FinishedParams;
10435 }
10436
10437 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10438 // are allowed as the first parameter to a two-parameter function
10439 if (!(Context.hasSameType(T, Context.CharTy) ||
10440 Context.hasSameType(T, Context.WCharTy) ||
10441 Context.hasSameType(T, Context.Char16Ty) ||
10442 Context.hasSameType(T, Context.Char32Ty)))
10443 goto FinishedParams;
10444
10445 // The second and final parameter must be an std::size_t
10446 T = (*Param)->getType().getUnqualifiedType();
10447 if (Context.hasSameType(T, Context.getSizeType()) &&
10448 ++Param == FnDecl->param_end())
10449 Valid = true;
10450 }
10451
10452 // FIXME: This diagnostic is absolutely terrible.
10453FinishedParams:
10454 if (!Valid) {
10455 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10456 << FnDecl->getDeclName();
10457 return true;
10458 }
10459
Richard Smitha9e88b22012-03-09 08:16:22 +000010460 // A parameter-declaration-clause containing a default argument is not
10461 // equivalent to any of the permitted forms.
10462 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10463 ParamEnd = FnDecl->param_end();
10464 Param != ParamEnd; ++Param) {
10465 if ((*Param)->hasDefaultArg()) {
10466 Diag((*Param)->getDefaultArgRange().getBegin(),
10467 diag::err_literal_operator_default_argument)
10468 << (*Param)->getDefaultArgRange();
10469 break;
10470 }
10471 }
10472
Richard Smith2fb4ae32012-03-08 02:39:21 +000010473 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010474 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10475 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010476 // C++11 [usrlit.suffix]p1:
10477 // Literal suffix identifiers that do not start with an underscore
10478 // are reserved for future standardization.
10479 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010480 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010481
Sean Hunta6c058d2010-01-13 09:01:02 +000010482 return false;
10483}
10484
Douglas Gregor074149e2009-01-05 19:45:36 +000010485/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10486/// linkage specification, including the language and (if present)
10487/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10488/// the location of the language string literal, which is provided
10489/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10490/// the '{' brace. Otherwise, this linkage specification does not
10491/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010492Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10493 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010494 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010495 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010496 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010497 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010498 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010499 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010500 Language = LinkageSpecDecl::lang_cxx;
10501 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010502 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010503 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010504 }
Mike Stump1eb44332009-09-09 15:08:12 +000010505
Chris Lattnercc98eac2008-12-17 07:13:27 +000010506 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010507
Douglas Gregor074149e2009-01-05 19:45:36 +000010508 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010509 ExternLoc, LangLoc, Language,
10510 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010511 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010512 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010513 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010514}
10515
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010516/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010517/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10518/// valid, it's the position of the closing '}' brace in a linkage
10519/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010520Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010521 Decl *LinkageSpec,
10522 SourceLocation RBraceLoc) {
10523 if (LinkageSpec) {
10524 if (RBraceLoc.isValid()) {
10525 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10526 LSDecl->setRBraceLoc(RBraceLoc);
10527 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010528 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010529 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010530 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010531}
10532
Michael Han684aa732013-02-22 17:15:32 +000010533Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10534 AttributeList *AttrList,
10535 SourceLocation SemiLoc) {
10536 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10537 // Attribute declarations appertain to empty declaration so we handle
10538 // them here.
10539 if (AttrList)
10540 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010541
Michael Han684aa732013-02-22 17:15:32 +000010542 CurContext->addDecl(ED);
10543 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010544}
10545
Douglas Gregord308e622009-05-18 20:51:54 +000010546/// \brief Perform semantic analysis for the variable declaration that
10547/// occurs within a C++ catch clause, returning the newly-created
10548/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010549VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010550 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010551 SourceLocation StartLoc,
10552 SourceLocation Loc,
10553 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010554 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010555 QualType ExDeclType = TInfo->getType();
10556
Sebastian Redl4b07b292008-12-22 19:15:10 +000010557 // Arrays and functions decay.
10558 if (ExDeclType->isArrayType())
10559 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10560 else if (ExDeclType->isFunctionType())
10561 ExDeclType = Context.getPointerType(ExDeclType);
10562
10563 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10564 // The exception-declaration shall not denote a pointer or reference to an
10565 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010566 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010567 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010568 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010569 Invalid = true;
10570 }
Douglas Gregord308e622009-05-18 20:51:54 +000010571
Sebastian Redl4b07b292008-12-22 19:15:10 +000010572 QualType BaseType = ExDeclType;
10573 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010574 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010575 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010576 BaseType = Ptr->getPointeeType();
10577 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010578 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010579 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010580 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010581 BaseType = Ref->getPointeeType();
10582 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010583 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010584 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010585 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010586 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010587 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010588
Mike Stump1eb44332009-09-09 15:08:12 +000010589 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010590 RequireNonAbstractType(Loc, ExDeclType,
10591 diag::err_abstract_type_in_decl,
10592 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010593 Invalid = true;
10594
John McCall5a180392010-07-24 00:37:23 +000010595 // Only the non-fragile NeXT runtime currently supports C++ catches
10596 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010597 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010598 QualType T = ExDeclType;
10599 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10600 T = RT->getPointeeType();
10601
10602 if (T->isObjCObjectType()) {
10603 Diag(Loc, diag::err_objc_object_catch);
10604 Invalid = true;
10605 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010606 // FIXME: should this be a test for macosx-fragile specifically?
10607 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010608 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010609 }
10610 }
10611
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010612 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010613 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010614 ExDecl->setExceptionVariable(true);
10615
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010616 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010617 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010618 Invalid = true;
10619
Douglas Gregorc41b8782011-07-06 18:14:43 +000010620 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010621 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010622 // Insulate this from anything else we might currently be parsing.
10623 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10624
Douglas Gregor6d182892010-03-05 23:38:39 +000010625 // C++ [except.handle]p16:
10626 // The object declared in an exception-declaration or, if the
10627 // exception-declaration does not specify a name, a temporary (12.2) is
10628 // copy-initialized (8.5) from the exception object. [...]
10629 // The object is destroyed when the handler exits, after the destruction
10630 // of any automatic objects initialized within the handler.
10631 //
10632 // We just pretend to initialize the object with itself, then make sure
10633 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010634 QualType initType = ExDeclType;
10635
10636 InitializedEntity entity =
10637 InitializedEntity::InitializeVariable(ExDecl);
10638 InitializationKind initKind =
10639 InitializationKind::CreateCopy(Loc, SourceLocation());
10640
10641 Expr *opaqueValue =
10642 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000010643 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10644 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000010645 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010646 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010647 else {
10648 // If the constructor used was non-trivial, set this as the
10649 // "initializer".
10650 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10651 if (!construct->getConstructor()->isTrivial()) {
10652 Expr *init = MaybeCreateExprWithCleanups(construct);
10653 ExDecl->setInit(init);
10654 }
10655
10656 // And make sure it's destructable.
10657 FinalizeVarWithDestructor(ExDecl, recordType);
10658 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010659 }
10660 }
10661
Douglas Gregord308e622009-05-18 20:51:54 +000010662 if (Invalid)
10663 ExDecl->setInvalidDecl();
10664
10665 return ExDecl;
10666}
10667
10668/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10669/// handler.
John McCalld226f652010-08-21 09:40:31 +000010670Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010671 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010672 bool Invalid = D.isInvalidType();
10673
10674 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010675 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10676 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010677 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10678 D.getIdentifierLoc());
10679 Invalid = true;
10680 }
10681
Sebastian Redl4b07b292008-12-22 19:15:10 +000010682 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010683 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010684 LookupOrdinaryName,
10685 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010686 // The scope should be freshly made just for us. There is just no way
10687 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010688 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010689 if (PrevDecl->isTemplateParameter()) {
10690 // Maybe we will complain about the shadowed template parameter.
10691 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010692 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010693 }
10694 }
10695
Chris Lattnereaaebc72009-04-25 08:06:05 +000010696 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010697 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10698 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010699 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010700 }
10701
Douglas Gregor83cb9422010-09-09 17:09:21 +000010702 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010703 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010704 D.getIdentifierLoc(),
10705 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010706 if (Invalid)
10707 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010708
Sebastian Redl4b07b292008-12-22 19:15:10 +000010709 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010710 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010711 PushOnScopeChains(ExDecl, S);
10712 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010713 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010714
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010715 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010716 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010717}
Anders Carlssonfb311762009-03-14 00:25:26 +000010718
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010719Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010720 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010721 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010722 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010723 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010724
Richard Smithe3f470a2012-07-11 22:37:56 +000010725 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10726 return 0;
10727
10728 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10729 AssertMessage, RParenLoc, false);
10730}
10731
10732Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10733 Expr *AssertExpr,
10734 StringLiteral *AssertMessage,
10735 SourceLocation RParenLoc,
10736 bool Failed) {
10737 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10738 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010739 // In a static_assert-declaration, the constant-expression shall be a
10740 // constant expression that can be contextually converted to bool.
10741 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10742 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010743 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010744
Richard Smithdaaefc52011-12-14 23:32:26 +000010745 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010746 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010747 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010748 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010749 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010750
Richard Smithe3f470a2012-07-11 22:37:56 +000010751 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010752 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010753 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010754 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010755 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010756 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010757 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010758 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010759 }
Mike Stump1eb44332009-09-09 15:08:12 +000010760
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010761 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010762 AssertExpr, AssertMessage, RParenLoc,
10763 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010764
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010765 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010766 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010767}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010768
Douglas Gregor1d869352010-04-07 16:53:43 +000010769/// \brief Perform semantic analysis of the given friend type declaration.
10770///
10771/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010772FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010773 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010774 TypeSourceInfo *TSInfo) {
10775 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10776
10777 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010778 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010779
Richard Smith6b130222011-10-18 21:39:00 +000010780 // C++03 [class.friend]p2:
10781 // An elaborated-type-specifier shall be used in a friend declaration
10782 // for a class.*
10783 //
10784 // * The class-key of the elaborated-type-specifier is required.
10785 if (!ActiveTemplateInstantiations.empty()) {
10786 // Do not complain about the form of friend template types during
10787 // template instantiation; we will already have complained when the
10788 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010789 } else {
10790 if (!T->isElaboratedTypeSpecifier()) {
10791 // If we evaluated the type to a record type, suggest putting
10792 // a tag in front.
10793 if (const RecordType *RT = T->getAs<RecordType>()) {
10794 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010795
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010796 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010797
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010798 Diag(TypeRange.getBegin(),
10799 getLangOpts().CPlusPlus11 ?
10800 diag::warn_cxx98_compat_unelaborated_friend_type :
10801 diag::ext_unelaborated_friend_type)
10802 << (unsigned) RD->getTagKind()
10803 << T
10804 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10805 InsertionText);
10806 } else {
10807 Diag(FriendLoc,
10808 getLangOpts().CPlusPlus11 ?
10809 diag::warn_cxx98_compat_nonclass_type_friend :
10810 diag::ext_nonclass_type_friend)
10811 << T
10812 << TypeRange;
10813 }
10814 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010815 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010816 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010817 diag::warn_cxx98_compat_enum_friend :
10818 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010819 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010820 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010821 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010822
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010823 // C++11 [class.friend]p3:
10824 // A friend declaration that does not declare a function shall have one
10825 // of the following forms:
10826 // friend elaborated-type-specifier ;
10827 // friend simple-type-specifier ;
10828 // friend typename-specifier ;
10829 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10830 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10831 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010832
Douglas Gregor06245bf2010-04-07 17:57:12 +000010833 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010834 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010835 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010836 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010837}
10838
John McCall9a34edb2010-10-19 01:40:49 +000010839/// Handle a friend tag declaration where the scope specifier was
10840/// templated.
10841Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10842 unsigned TagSpec, SourceLocation TagLoc,
10843 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010844 IdentifierInfo *Name,
10845 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010846 AttributeList *Attr,
10847 MultiTemplateParamsArg TempParamLists) {
10848 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10849
10850 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010851 bool Invalid = false;
10852
10853 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010854 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010855 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010856 TempParamLists.size(),
10857 /*friend*/ true,
10858 isExplicitSpecialization,
10859 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010860 if (TemplateParams->size() > 0) {
10861 // This is a declaration of a class template.
10862 if (Invalid)
10863 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010864
Eric Christopher4110e132011-07-21 05:34:24 +000010865 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10866 SS, Name, NameLoc, Attr,
10867 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010868 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010869 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010870 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010871 } else {
10872 // The "template<>" header is extraneous.
10873 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10874 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10875 isExplicitSpecialization = true;
10876 }
10877 }
10878
10879 if (Invalid) return 0;
10880
John McCall9a34edb2010-10-19 01:40:49 +000010881 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010882 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010883 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010884 isAllExplicitSpecializations = false;
10885 break;
10886 }
10887 }
10888
10889 // FIXME: don't ignore attributes.
10890
10891 // If it's explicit specializations all the way down, just forget
10892 // about the template header and build an appropriate non-templated
10893 // friend. TODO: for source fidelity, remember the headers.
10894 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010895 if (SS.isEmpty()) {
10896 bool Owned = false;
10897 bool IsDependent = false;
10898 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10899 Attr, AS_public,
10900 /*ModulePrivateLoc=*/SourceLocation(),
10901 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010902 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010903 /*ScopedEnumUsesClassTag=*/false,
10904 /*UnderlyingType=*/TypeResult());
10905 }
10906
Douglas Gregor2494dd02011-03-01 01:34:45 +000010907 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010908 ElaboratedTypeKeyword Keyword
10909 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010910 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010911 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010912 if (T.isNull())
10913 return 0;
10914
10915 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10916 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010917 DependentNameTypeLoc TL =
10918 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010919 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010920 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010921 TL.setNameLoc(NameLoc);
10922 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010923 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010924 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010925 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010926 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010927 }
10928
10929 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010930 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010931 Friend->setAccess(AS_public);
10932 CurContext->addDecl(Friend);
10933 return Friend;
10934 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010935
10936 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10937
10938
John McCall9a34edb2010-10-19 01:40:49 +000010939
10940 // Handle the case of a templated-scope friend class. e.g.
10941 // template <class T> class A<T>::B;
10942 // FIXME: we don't support these right now.
10943 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10944 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10945 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000010946 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010947 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010948 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010949 TL.setNameLoc(NameLoc);
10950
10951 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010952 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010953 Friend->setAccess(AS_public);
10954 Friend->setUnsupportedFriend(true);
10955 CurContext->addDecl(Friend);
10956 return Friend;
10957}
10958
10959
John McCalldd4a3b02009-09-16 22:47:08 +000010960/// Handle a friend type declaration. This works in tandem with
10961/// ActOnTag.
10962///
10963/// Notes on friend class templates:
10964///
10965/// We generally treat friend class declarations as if they were
10966/// declaring a class. So, for example, the elaborated type specifier
10967/// in a friend declaration is required to obey the restrictions of a
10968/// class-head (i.e. no typedefs in the scope chain), template
10969/// parameters are required to match up with simple template-ids, &c.
10970/// However, unlike when declaring a template specialization, it's
10971/// okay to refer to a template specialization without an empty
10972/// template parameter declaration, e.g.
10973/// friend class A<T>::B<unsigned>;
10974/// We permit this as a special case; if there are any template
10975/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010976/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010977Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010978 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010979 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010980
10981 assert(DS.isFriendSpecified());
10982 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10983
John McCalldd4a3b02009-09-16 22:47:08 +000010984 // Try to convert the decl specifier to a type. This works for
10985 // friend templates because ActOnTag never produces a ClassTemplateDecl
10986 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010987 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010988 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10989 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010990 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010991 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010992
Douglas Gregor6ccab972010-12-16 01:14:37 +000010993 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10994 return 0;
10995
John McCalldd4a3b02009-09-16 22:47:08 +000010996 // This is definitely an error in C++98. It's probably meant to
10997 // be forbidden in C++0x, too, but the specification is just
10998 // poorly written.
10999 //
11000 // The problem is with declarations like the following:
11001 // template <T> friend A<T>::foo;
11002 // where deciding whether a class C is a friend or not now hinges
11003 // on whether there exists an instantiation of A that causes
11004 // 'foo' to equal C. There are restrictions on class-heads
11005 // (which we declare (by fiat) elaborated friend declarations to
11006 // be) that makes this tractable.
11007 //
11008 // FIXME: handle "template <> friend class A<T>;", which
11009 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011010 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011011 Diag(Loc, diag::err_tagless_friend_type_template)
11012 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011013 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011014 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011015
John McCall02cace72009-08-28 07:59:38 +000011016 // C++98 [class.friend]p1: A friend of a class is a function
11017 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011018 // This is fixed in DR77, which just barely didn't make the C++03
11019 // deadline. It's also a very silly restriction that seriously
11020 // affects inner classes and which nobody else seems to implement;
11021 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011022 //
11023 // But note that we could warn about it: it's always useless to
11024 // friend one of your own members (it's not, however, worthless to
11025 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011026
John McCalldd4a3b02009-09-16 22:47:08 +000011027 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011028 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011029 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011030 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011031 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011032 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011033 DS.getFriendSpecLoc());
11034 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011035 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011036
11037 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011038 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011039
John McCalldd4a3b02009-09-16 22:47:08 +000011040 D->setAccess(AS_public);
11041 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011042
John McCalld226f652010-08-21 09:40:31 +000011043 return D;
John McCall02cace72009-08-28 07:59:38 +000011044}
11045
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011046NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11047 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011048 const DeclSpec &DS = D.getDeclSpec();
11049
11050 assert(DS.isFriendSpecified());
11051 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11052
11053 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011054 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011055
11056 // C++ [class.friend]p1
11057 // A friend of a class is a function or class....
11058 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011059 // It *doesn't* see through dependent types, which is correct
11060 // according to [temp.arg.type]p3:
11061 // If a declaration acquires a function type through a
11062 // type dependent on a template-parameter and this causes
11063 // a declaration that does not use the syntactic form of a
11064 // function declarator to have a function type, the program
11065 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011066 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011067 Diag(Loc, diag::err_unexpected_friend);
11068
11069 // It might be worthwhile to try to recover by creating an
11070 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011071 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011072 }
11073
11074 // C++ [namespace.memdef]p3
11075 // - If a friend declaration in a non-local class first declares a
11076 // class or function, the friend class or function is a member
11077 // of the innermost enclosing namespace.
11078 // - The name of the friend is not found by simple name lookup
11079 // until a matching declaration is provided in that namespace
11080 // scope (either before or after the class declaration granting
11081 // friendship).
11082 // - If a friend function is called, its name may be found by the
11083 // name lookup that considers functions from namespaces and
11084 // classes associated with the types of the function arguments.
11085 // - When looking for a prior declaration of a class or a function
11086 // declared as a friend, scopes outside the innermost enclosing
11087 // namespace scope are not considered.
11088
John McCall337ec3d2010-10-12 23:13:28 +000011089 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011090 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11091 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011092 assert(Name);
11093
Douglas Gregor6ccab972010-12-16 01:14:37 +000011094 // Check for unexpanded parameter packs.
11095 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11096 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11097 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11098 return 0;
11099
John McCall67d1a672009-08-06 02:15:43 +000011100 // The context we found the declaration in, or in which we should
11101 // create the declaration.
11102 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011103 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011104 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011105 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011106
John McCall337ec3d2010-10-12 23:13:28 +000011107 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000011108
John McCall337ec3d2010-10-12 23:13:28 +000011109 // There are four cases here.
11110 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000011111 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000011112 // there as appropriate.
11113 // Recover from invalid scope qualifiers as if they just weren't there.
11114 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000011115 // C++0x [namespace.memdef]p3:
11116 // If the name in a friend declaration is neither qualified nor
11117 // a template-id and the declaration is a function or an
11118 // elaborated-type-specifier, the lookup to determine whether
11119 // the entity has been previously declared shall not consider
11120 // any scopes outside the innermost enclosing namespace.
11121 // C++0x [class.friend]p11:
11122 // If a friend declaration appears in a local class and the name
11123 // specified is an unqualified name, a prior declaration is
11124 // looked up without considering scopes that are outside the
11125 // innermost enclosing non-class scope. For a friend function
11126 // declaration, if there is no prior declaration, the program is
11127 // ill-formed.
11128 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000011129 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011130
John McCall29ae6e52010-10-13 05:45:15 +000011131 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011132 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011133
Rafael Espindola11dc6342013-04-25 20:12:36 +000011134 // Skip class contexts. If someone can cite chapter and verse
11135 // for this behavior, that would be nice --- it's what GCC and
11136 // EDG do, and it seems like a reasonable intent, but the spec
11137 // really only says that checks for unqualified existing
11138 // declarations should stop at the nearest enclosing namespace,
11139 // not that they should only consider the nearest enclosing
11140 // namespace.
11141 while (DC->isRecord())
11142 DC = DC->getParent();
11143
11144 DeclContext *LookupDC = DC;
11145 while (LookupDC->isTransparentContext())
11146 LookupDC = LookupDC->getParent();
11147
11148 while (true) {
11149 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011150
11151 // TODO: decide what we think about using declarations.
Rafael Espindola11dc6342013-04-25 20:12:36 +000011152 if (isLocal)
John McCall67d1a672009-08-06 02:15:43 +000011153 break;
John McCall29ae6e52010-10-13 05:45:15 +000011154
Rafael Espindola11dc6342013-04-25 20:12:36 +000011155 if (!Previous.empty()) {
11156 DC = LookupDC;
11157 break;
John McCall8a407372010-10-14 22:22:28 +000011158 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011159
11160 if (isTemplateId) {
11161 if (isa<TranslationUnitDecl>(LookupDC)) break;
11162 } else {
11163 if (LookupDC->isFileContext()) break;
11164 }
11165 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011166 }
11167
John McCall380aaa42010-10-13 06:22:15 +000011168 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011169
Douglas Gregor883af832011-10-10 01:11:59 +000011170 // C++ [class.friend]p6:
11171 // A function can be defined in a friend declaration of a class if and
11172 // only if the class is a non-local class (9.8), the function name is
11173 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011174 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011175 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11176 }
11177
John McCall337ec3d2010-10-12 23:13:28 +000011178 // - There's a non-dependent scope specifier, in which case we
11179 // compute it and do a previous lookup there for a function
11180 // or function template.
11181 } else if (!SS.getScopeRep()->isDependent()) {
11182 DC = computeDeclContext(SS);
11183 if (!DC) return 0;
11184
11185 if (RequireCompleteDeclContext(SS, DC)) return 0;
11186
11187 LookupQualifiedName(Previous, DC);
11188
11189 // Ignore things found implicitly in the wrong scope.
11190 // TODO: better diagnostics for this case. Suggesting the right
11191 // qualified scope would be nice...
11192 LookupResult::Filter F = Previous.makeFilter();
11193 while (F.hasNext()) {
11194 NamedDecl *D = F.next();
11195 if (!DC->InEnclosingNamespaceSetOf(
11196 D->getDeclContext()->getRedeclContext()))
11197 F.erase();
11198 }
11199 F.done();
11200
11201 if (Previous.empty()) {
11202 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011203 Diag(Loc, diag::err_qualified_friend_not_found)
11204 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011205 return 0;
11206 }
11207
11208 // C++ [class.friend]p1: A friend of a class is a function or
11209 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011210 if (DC->Equals(CurContext))
11211 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011212 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011213 diag::warn_cxx98_compat_friend_is_member :
11214 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011215
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011216 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011217 // C++ [class.friend]p6:
11218 // A function can be defined in a friend declaration of a class if and
11219 // only if the class is a non-local class (9.8), the function name is
11220 // unqualified, and the function has namespace scope.
11221 SemaDiagnosticBuilder DB
11222 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11223
11224 DB << SS.getScopeRep();
11225 if (DC->isFileContext())
11226 DB << FixItHint::CreateRemoval(SS.getRange());
11227 SS.clear();
11228 }
John McCall337ec3d2010-10-12 23:13:28 +000011229
11230 // - There's a scope specifier that does not match any template
11231 // parameter lists, in which case we use some arbitrary context,
11232 // create a method or method template, and wait for instantiation.
11233 // - There's a scope specifier that does match some template
11234 // parameter lists, which we don't handle right now.
11235 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011236 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011237 // C++ [class.friend]p6:
11238 // A function can be defined in a friend declaration of a class if and
11239 // only if the class is a non-local class (9.8), the function name is
11240 // unqualified, and the function has namespace scope.
11241 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11242 << SS.getScopeRep();
11243 }
11244
John McCall337ec3d2010-10-12 23:13:28 +000011245 DC = CurContext;
11246 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011247 }
Douglas Gregor883af832011-10-10 01:11:59 +000011248
John McCall29ae6e52010-10-13 05:45:15 +000011249 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011250 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011251 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11252 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11253 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011254 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011255 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11256 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011257 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011258 }
John McCall67d1a672009-08-06 02:15:43 +000011259 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011260
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011261 // FIXME: This is an egregious hack to cope with cases where the scope stack
11262 // does not contain the declaration context, i.e., in an out-of-line
11263 // definition of a class.
11264 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11265 if (!DCScope) {
11266 FakeDCScope.setEntity(DC);
11267 DCScope = &FakeDCScope;
11268 }
11269
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011270 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011271 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011272 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011273 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011274
Douglas Gregor182ddf02009-09-28 00:08:27 +000011275 assert(ND->getDeclContext() == DC);
11276 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011277
John McCallab88d972009-08-31 22:39:49 +000011278 // Add the function declaration to the appropriate lookup tables,
11279 // adjusting the redeclarations list as necessary. We don't
11280 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011281 //
John McCallab88d972009-08-31 22:39:49 +000011282 // Also update the scope-based lookup if the target context's
11283 // lookup context is in lexical scope.
11284 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011285 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011286 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011287 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011288 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011289 }
John McCall02cace72009-08-28 07:59:38 +000011290
11291 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011292 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011293 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011294 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011295 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011296
John McCall1f2e1a92012-08-10 03:15:35 +000011297 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011298 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011299 } else {
11300 if (DC->isRecord()) CheckFriendAccess(ND);
11301
John McCall6102ca12010-10-16 06:59:13 +000011302 FunctionDecl *FD;
11303 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11304 FD = FTD->getTemplatedDecl();
11305 else
11306 FD = cast<FunctionDecl>(ND);
11307
11308 // Mark templated-scope function declarations as unsupported.
11309 if (FD->getNumTemplateParameterLists())
11310 FrD->setUnsupportedFriend(true);
11311 }
John McCall337ec3d2010-10-12 23:13:28 +000011312
John McCalld226f652010-08-21 09:40:31 +000011313 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011314}
11315
John McCalld226f652010-08-21 09:40:31 +000011316void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11317 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011318
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011319 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011320 if (!Fn) {
11321 Diag(DelLoc, diag::err_deleted_non_function);
11322 return;
11323 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011324
Douglas Gregoref96ee02012-01-14 16:38:05 +000011325 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011326 // Don't consider the implicit declaration we generate for explicit
11327 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011328 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11329 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011330 Diag(DelLoc, diag::err_deleted_decl_not_first);
11331 Diag(Prev->getLocation(), diag::note_previous_declaration);
11332 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011333 // If the declaration wasn't the first, we delete the function anyway for
11334 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011335 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011336 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011337
11338 if (Fn->isDeleted())
11339 return;
11340
11341 // See if we're deleting a function which is already known to override a
11342 // non-deleted virtual function.
11343 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11344 bool IssuedDiagnostic = false;
11345 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11346 E = MD->end_overridden_methods();
11347 I != E; ++I) {
11348 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11349 if (!IssuedDiagnostic) {
11350 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11351 IssuedDiagnostic = true;
11352 }
11353 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11354 }
11355 }
11356 }
11357
Sean Hunt10620eb2011-05-06 20:44:56 +000011358 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011359}
Sebastian Redl13e88542009-04-27 21:33:24 +000011360
Sean Hunte4246a62011-05-12 06:15:49 +000011361void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011362 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011363
11364 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011365 if (MD->getParent()->isDependentType()) {
11366 MD->setDefaulted();
11367 MD->setExplicitlyDefaulted();
11368 return;
11369 }
11370
Sean Hunte4246a62011-05-12 06:15:49 +000011371 CXXSpecialMember Member = getSpecialMember(MD);
11372 if (Member == CXXInvalid) {
11373 Diag(DefaultLoc, diag::err_default_special_members);
11374 return;
11375 }
11376
11377 MD->setDefaulted();
11378 MD->setExplicitlyDefaulted();
11379
Sean Huntcd10dec2011-05-23 23:14:04 +000011380 // If this definition appears within the record, do the checking when
11381 // the record is complete.
11382 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011383 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011384 // Find the uninstantiated declaration that actually had the '= default'
11385 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011386 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011387
Richard Smith12fef492013-03-27 00:22:47 +000011388 // If the method was defaulted on its first declaration, we will have
11389 // already performed the checking in CheckCompletedCXXClass. Such a
11390 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011391 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011392 return;
11393
Richard Smithb9d0b762012-07-27 04:22:15 +000011394 CheckExplicitlyDefaultedSpecialMember(MD);
11395
Richard Smith1d28caf2012-12-11 01:14:52 +000011396 // The exception specification is needed because we are defining the
11397 // function.
11398 ResolveExceptionSpec(DefaultLoc,
11399 MD->getType()->castAs<FunctionProtoType>());
11400
Sean Hunte4246a62011-05-12 06:15:49 +000011401 switch (Member) {
11402 case CXXDefaultConstructor: {
11403 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011404 if (!CD->isInvalidDecl())
11405 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11406 break;
11407 }
11408
11409 case CXXCopyConstructor: {
11410 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011411 if (!CD->isInvalidDecl())
11412 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011413 break;
11414 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011415
Sean Hunt2b188082011-05-14 05:23:28 +000011416 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011417 if (!MD->isInvalidDecl())
11418 DefineImplicitCopyAssignment(DefaultLoc, MD);
11419 break;
11420 }
11421
Sean Huntcb45a0f2011-05-12 22:46:25 +000011422 case CXXDestructor: {
11423 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011424 if (!DD->isInvalidDecl())
11425 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011426 break;
11427 }
11428
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011429 case CXXMoveConstructor: {
11430 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011431 if (!CD->isInvalidDecl())
11432 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011433 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011434 }
Sean Hunt82713172011-05-25 23:16:36 +000011435
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011436 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011437 if (!MD->isInvalidDecl())
11438 DefineImplicitMoveAssignment(DefaultLoc, MD);
11439 break;
11440 }
11441
11442 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011443 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011444 }
11445 } else {
11446 Diag(DefaultLoc, diag::err_default_special_members);
11447 }
11448}
11449
Sebastian Redl13e88542009-04-27 21:33:24 +000011450static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011451 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011452 Stmt *SubStmt = *CI;
11453 if (!SubStmt)
11454 continue;
11455 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011456 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011457 diag::err_return_in_constructor_handler);
11458 if (!isa<Expr>(SubStmt))
11459 SearchForReturnInStmt(Self, SubStmt);
11460 }
11461}
11462
11463void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11464 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11465 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11466 SearchForReturnInStmt(*this, Handler);
11467 }
11468}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011469
David Blaikie299adab2013-01-18 23:03:15 +000011470bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011471 const CXXMethodDecl *Old) {
11472 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11473 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11474
11475 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11476
11477 // If the calling conventions match, everything is fine
11478 if (NewCC == OldCC)
11479 return false;
11480
11481 // If either of the calling conventions are set to "default", we need to pick
11482 // something more sensible based on the target. This supports code where the
11483 // one method explicitly sets thiscall, and another has no explicit calling
11484 // convention.
11485 CallingConv Default =
11486 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11487 if (NewCC == CC_Default)
11488 NewCC = Default;
11489 if (OldCC == CC_Default)
11490 OldCC = Default;
11491
11492 // If the calling conventions still don't match, then report the error
11493 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011494 Diag(New->getLocation(),
11495 diag::err_conflicting_overriding_cc_attributes)
11496 << New->getDeclName() << New->getType() << Old->getType();
11497 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11498 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011499 }
11500
11501 return false;
11502}
11503
Mike Stump1eb44332009-09-09 15:08:12 +000011504bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011505 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011506 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11507 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011508
Chandler Carruth73857792010-02-15 11:53:20 +000011509 if (Context.hasSameType(NewTy, OldTy) ||
11510 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011511 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011512
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011513 // Check if the return types are covariant
11514 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011515
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011516 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011517 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11518 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011519 NewClassTy = NewPT->getPointeeType();
11520 OldClassTy = OldPT->getPointeeType();
11521 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011522 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11523 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11524 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11525 NewClassTy = NewRT->getPointeeType();
11526 OldClassTy = OldRT->getPointeeType();
11527 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011528 }
11529 }
Mike Stump1eb44332009-09-09 15:08:12 +000011530
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011531 // The return types aren't either both pointers or references to a class type.
11532 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011533 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011534 diag::err_different_return_type_for_overriding_virtual_function)
11535 << New->getDeclName() << NewTy << OldTy;
11536 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011537
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011538 return true;
11539 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011540
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011541 // C++ [class.virtual]p6:
11542 // If the return type of D::f differs from the return type of B::f, the
11543 // class type in the return type of D::f shall be complete at the point of
11544 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011545 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11546 if (!RT->isBeingDefined() &&
11547 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011548 diag::err_covariant_return_incomplete,
11549 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011550 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011551 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011552
Douglas Gregora4923eb2009-11-16 21:35:15 +000011553 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011554 // Check if the new class derives from the old class.
11555 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11556 Diag(New->getLocation(),
11557 diag::err_covariant_return_not_derived)
11558 << New->getDeclName() << NewTy << OldTy;
11559 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11560 return true;
11561 }
Mike Stump1eb44332009-09-09 15:08:12 +000011562
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011563 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011564 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011565 diag::err_covariant_return_inaccessible_base,
11566 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11567 // FIXME: Should this point to the return type?
11568 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011569 // FIXME: this note won't trigger for delayed access control
11570 // diagnostics, and it's impossible to get an undelayed error
11571 // here from access control during the original parse because
11572 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011573 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11574 return true;
11575 }
11576 }
Mike Stump1eb44332009-09-09 15:08:12 +000011577
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011578 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011579 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011580 Diag(New->getLocation(),
11581 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011582 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011583 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11584 return true;
11585 };
Mike Stump1eb44332009-09-09 15:08:12 +000011586
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011587
11588 // The new class type must have the same or less qualifiers as the old type.
11589 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11590 Diag(New->getLocation(),
11591 diag::err_covariant_return_type_class_type_more_qualified)
11592 << New->getDeclName() << NewTy << OldTy;
11593 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11594 return true;
11595 };
Mike Stump1eb44332009-09-09 15:08:12 +000011596
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011597 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011598}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011599
Douglas Gregor4ba31362009-12-01 17:24:26 +000011600/// \brief Mark the given method pure.
11601///
11602/// \param Method the method to be marked pure.
11603///
11604/// \param InitRange the source range that covers the "0" initializer.
11605bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011606 SourceLocation EndLoc = InitRange.getEnd();
11607 if (EndLoc.isValid())
11608 Method->setRangeEnd(EndLoc);
11609
Douglas Gregor4ba31362009-12-01 17:24:26 +000011610 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11611 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011612 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011613 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011614
11615 if (!Method->isInvalidDecl())
11616 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11617 << Method->getDeclName() << InitRange;
11618 return true;
11619}
11620
Douglas Gregor552e2992012-02-21 02:22:07 +000011621/// \brief Determine whether the given declaration is a static data member.
11622static bool isStaticDataMember(Decl *D) {
11623 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11624 if (!Var)
11625 return false;
11626
11627 return Var->isStaticDataMember();
11628}
John McCall731ad842009-12-19 09:28:58 +000011629/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11630/// an initializer for the out-of-line declaration 'Dcl'. The scope
11631/// is a fresh scope pushed for just this purpose.
11632///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011633/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11634/// static data member of class X, names should be looked up in the scope of
11635/// class X.
John McCalld226f652010-08-21 09:40:31 +000011636void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011637 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011638 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011639
John McCall731ad842009-12-19 09:28:58 +000011640 // We should only get called for declarations with scope specifiers, like:
11641 // int foo::bar;
11642 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011643 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011644
11645 // If we are parsing the initializer for a static data member, push a
11646 // new expression evaluation context that is associated with this static
11647 // data member.
11648 if (isStaticDataMember(D))
11649 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011650}
11651
11652/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011653/// initializer for the out-of-line declaration 'D'.
11654void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011655 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011656 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011657
Douglas Gregor552e2992012-02-21 02:22:07 +000011658 if (isStaticDataMember(D))
11659 PopExpressionEvaluationContext();
11660
John McCall731ad842009-12-19 09:28:58 +000011661 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011662 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011663}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011664
11665/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11666/// C++ if/switch/while/for statement.
11667/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011668DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011669 // C++ 6.4p2:
11670 // The declarator shall not specify a function or an array.
11671 // The type-specifier-seq shall not contain typedef and shall not declare a
11672 // new class or enumeration.
11673 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11674 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011675
11676 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011677 if (!Dcl)
11678 return true;
11679
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011680 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11681 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011682 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011683 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011684 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011685
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011686 return Dcl;
11687}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011688
Douglas Gregordfe65432011-07-28 19:11:31 +000011689void Sema::LoadExternalVTableUses() {
11690 if (!ExternalSource)
11691 return;
11692
11693 SmallVector<ExternalVTableUse, 4> VTables;
11694 ExternalSource->ReadUsedVTables(VTables);
11695 SmallVector<VTableUse, 4> NewUses;
11696 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11697 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11698 = VTablesUsed.find(VTables[I].Record);
11699 // Even if a definition wasn't required before, it may be required now.
11700 if (Pos != VTablesUsed.end()) {
11701 if (!Pos->second && VTables[I].DefinitionRequired)
11702 Pos->second = true;
11703 continue;
11704 }
11705
11706 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11707 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11708 }
11709
11710 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11711}
11712
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011713void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11714 bool DefinitionRequired) {
11715 // Ignore any vtable uses in unevaluated operands or for classes that do
11716 // not have a vtable.
11717 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000011718 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011719 return;
11720
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011721 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011722 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011723 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11724 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11725 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11726 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011727 // If we already had an entry, check to see if we are promoting this vtable
11728 // to required a definition. If so, we need to reappend to the VTableUses
11729 // list, since we may have already processed the first entry.
11730 if (DefinitionRequired && !Pos.first->second) {
11731 Pos.first->second = true;
11732 } else {
11733 // Otherwise, we can early exit.
11734 return;
11735 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011736 }
11737
11738 // Local classes need to have their virtual members marked
11739 // immediately. For all other classes, we mark their virtual members
11740 // at the end of the translation unit.
11741 if (Class->isLocalClass())
11742 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011743 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011744 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011745}
11746
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011747bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011748 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011749 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011750 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011751
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011752 // Note: The VTableUses vector could grow as a result of marking
11753 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011754 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011755 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011756 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011757 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011758 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011759 if (!Class)
11760 continue;
11761
11762 SourceLocation Loc = VTableUses[I].second;
11763
Richard Smithb9d0b762012-07-27 04:22:15 +000011764 bool DefineVTable = true;
11765
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011766 // If this class has a key function, but that key function is
11767 // defined in another translation unit, we don't need to emit the
11768 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011769 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011770 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011771 switch (KeyFunction->getTemplateSpecializationKind()) {
11772 case TSK_Undeclared:
11773 case TSK_ExplicitSpecialization:
11774 case TSK_ExplicitInstantiationDeclaration:
11775 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011776 DefineVTable = false;
11777 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011778
11779 case TSK_ExplicitInstantiationDefinition:
11780 case TSK_ImplicitInstantiation:
11781 // We will be instantiating the key function.
11782 break;
11783 }
11784 } else if (!KeyFunction) {
11785 // If we have a class with no key function that is the subject
11786 // of an explicit instantiation declaration, suppress the
11787 // vtable; it will live with the explicit instantiation
11788 // definition.
11789 bool IsExplicitInstantiationDeclaration
11790 = Class->getTemplateSpecializationKind()
11791 == TSK_ExplicitInstantiationDeclaration;
11792 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11793 REnd = Class->redecls_end();
11794 R != REnd; ++R) {
11795 TemplateSpecializationKind TSK
11796 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11797 if (TSK == TSK_ExplicitInstantiationDeclaration)
11798 IsExplicitInstantiationDeclaration = true;
11799 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11800 IsExplicitInstantiationDeclaration = false;
11801 break;
11802 }
11803 }
11804
11805 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011806 DefineVTable = false;
11807 }
11808
11809 // The exception specifications for all virtual members may be needed even
11810 // if we are not providing an authoritative form of the vtable in this TU.
11811 // We may choose to emit it available_externally anyway.
11812 if (!DefineVTable) {
11813 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11814 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011815 }
11816
11817 // Mark all of the virtual members of this class as referenced, so
11818 // that we can build a vtable. Then, tell the AST consumer that a
11819 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011820 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011821 MarkVirtualMembersReferenced(Loc, Class);
11822 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11823 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11824
11825 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola531db822013-03-07 02:00:27 +000011826 if (Class->hasExternalLinkage() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011827 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011828 const FunctionDecl *KeyFunctionDef = 0;
11829 if (!KeyFunction ||
11830 (KeyFunction->hasBody(KeyFunctionDef) &&
11831 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011832 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11833 TSK_ExplicitInstantiationDefinition
11834 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11835 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011836 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011837 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011838 VTableUses.clear();
11839
Douglas Gregor78844032011-04-22 22:25:37 +000011840 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011841}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011842
Richard Smithb9d0b762012-07-27 04:22:15 +000011843void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11844 const CXXRecordDecl *RD) {
11845 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11846 E = RD->method_end(); I != E; ++I)
11847 if ((*I)->isVirtual() && !(*I)->isPure())
11848 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11849}
11850
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011851void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11852 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011853 // Mark all functions which will appear in RD's vtable as used.
11854 CXXFinalOverriderMap FinalOverriders;
11855 RD->getFinalOverriders(FinalOverriders);
11856 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11857 E = FinalOverriders.end();
11858 I != E; ++I) {
11859 for (OverridingMethods::const_iterator OI = I->second.begin(),
11860 OE = I->second.end();
11861 OI != OE; ++OI) {
11862 assert(OI->second.size() > 0 && "no final overrider");
11863 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011864
Richard Smithff817f72012-07-07 06:59:51 +000011865 // C++ [basic.def.odr]p2:
11866 // [...] A virtual member function is used if it is not pure. [...]
11867 if (!Overrider->isPure())
11868 MarkFunctionReferenced(Loc, Overrider);
11869 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011870 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011871
11872 // Only classes that have virtual bases need a VTT.
11873 if (RD->getNumVBases() == 0)
11874 return;
11875
11876 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11877 e = RD->bases_end(); i != e; ++i) {
11878 const CXXRecordDecl *Base =
11879 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011880 if (Base->getNumVBases() == 0)
11881 continue;
11882 MarkVirtualMembersReferenced(Loc, Base);
11883 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011884}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011885
11886/// SetIvarInitializers - This routine builds initialization ASTs for the
11887/// Objective-C implementation whose ivars need be initialized.
11888void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011889 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011890 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011891 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011892 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011893 CollectIvarsToConstructOrDestruct(OID, ivars);
11894 if (ivars.empty())
11895 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011896 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011897 for (unsigned i = 0; i < ivars.size(); i++) {
11898 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011899 if (Field->isInvalidDecl())
11900 continue;
11901
Sean Huntcbb67482011-01-08 20:30:50 +000011902 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011903 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11904 InitializationKind InitKind =
11905 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000011906
11907 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
11908 ExprResult MemberInit =
11909 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000011910 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011911 // Note, MemberInit could actually come back empty if no initialization
11912 // is required (e.g., because it would call a trivial default constructor)
11913 if (!MemberInit.get() || MemberInit.isInvalid())
11914 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011915
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011916 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011917 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11918 SourceLocation(),
11919 MemberInit.takeAs<Expr>(),
11920 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011921 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011922
11923 // Be sure that the destructor is accessible and is marked as referenced.
11924 if (const RecordType *RecordTy
11925 = Context.getBaseElementType(Field->getType())
11926 ->getAs<RecordType>()) {
11927 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011928 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011929 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011930 CheckDestructorAccess(Field->getLocation(), Destructor,
11931 PDiag(diag::err_access_dtor_ivar)
11932 << Context.getBaseElementType(Field->getType()));
11933 }
11934 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011935 }
11936 ObjCImplementation->setIvarInitializers(Context,
11937 AllToInit.data(), AllToInit.size());
11938 }
11939}
Sean Huntfe57eef2011-05-04 05:57:24 +000011940
Sean Huntebcbe1d2011-05-04 23:29:54 +000011941static
11942void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11943 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11944 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11945 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11946 Sema &S) {
11947 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11948 CE = Current.end();
11949 if (Ctor->isInvalidDecl())
11950 return;
11951
Richard Smitha8eaf002012-08-23 06:16:52 +000011952 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11953
11954 // Target may not be determinable yet, for instance if this is a dependent
11955 // call in an uninstantiated template.
11956 if (Target) {
11957 const FunctionDecl *FNTarget = 0;
11958 (void)Target->hasBody(FNTarget);
11959 Target = const_cast<CXXConstructorDecl*>(
11960 cast_or_null<CXXConstructorDecl>(FNTarget));
11961 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011962
11963 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11964 // Avoid dereferencing a null pointer here.
11965 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11966
11967 if (!Current.insert(Canonical))
11968 return;
11969
11970 // We know that beyond here, we aren't chaining into a cycle.
11971 if (!Target || !Target->isDelegatingConstructor() ||
11972 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11973 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11974 Valid.insert(*CI);
11975 Current.clear();
11976 // We've hit a cycle.
11977 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11978 Current.count(TCanonical)) {
11979 // If we haven't diagnosed this cycle yet, do so now.
11980 if (!Invalid.count(TCanonical)) {
11981 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011982 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011983 << Ctor;
11984
Richard Smitha8eaf002012-08-23 06:16:52 +000011985 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011986 if (TCanonical != Canonical)
11987 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11988
11989 CXXConstructorDecl *C = Target;
11990 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011991 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011992 (void)C->getTargetConstructor()->hasBody(FNTarget);
11993 assert(FNTarget && "Ctor cycle through bodiless function");
11994
Richard Smitha8eaf002012-08-23 06:16:52 +000011995 C = const_cast<CXXConstructorDecl*>(
11996 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011997 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11998 }
11999 }
12000
12001 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12002 Invalid.insert(*CI);
12003 Current.clear();
12004 } else {
12005 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12006 }
12007}
12008
12009
Sean Huntfe57eef2011-05-04 05:57:24 +000012010void Sema::CheckDelegatingCtorCycles() {
12011 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12012
Sean Huntebcbe1d2011-05-04 23:29:54 +000012013 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12014 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000012015
Douglas Gregor0129b562011-07-27 21:57:17 +000012016 for (DelegatingCtorDeclsType::iterator
12017 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012018 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012019 I != E; ++I)
12020 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012021
12022 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
12023 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012024}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012025
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012026namespace {
12027 /// \brief AST visitor that finds references to the 'this' expression.
12028 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12029 Sema &S;
12030
12031 public:
12032 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12033
12034 bool VisitCXXThisExpr(CXXThisExpr *E) {
12035 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12036 << E->isImplicit();
12037 return false;
12038 }
12039 };
12040}
12041
12042bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12043 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12044 if (!TSInfo)
12045 return false;
12046
12047 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012048 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012049 if (!ProtoTL)
12050 return false;
12051
12052 // C++11 [expr.prim.general]p3:
12053 // [The expression this] shall not appear before the optional
12054 // cv-qualifier-seq and it shall not appear within the declaration of a
12055 // static member function (although its type and value category are defined
12056 // within a static member function as they are within a non-static member
12057 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012058 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012059 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012060 FindCXXThisExpr Finder(*this);
12061
12062 // If the return type came after the cv-qualifier-seq, check it now.
12063 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012064 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012065 return true;
12066
12067 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012068 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12069 return true;
12070
12071 return checkThisInStaticMemberFunctionAttributes(Method);
12072}
12073
12074bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12075 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12076 if (!TSInfo)
12077 return false;
12078
12079 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012080 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012081 if (!ProtoTL)
12082 return false;
12083
David Blaikie39e6ab42013-02-18 22:06:02 +000012084 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012085 FindCXXThisExpr Finder(*this);
12086
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012087 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012088 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012089 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012090 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012091 case EST_DynamicNone:
12092 case EST_MSAny:
12093 case EST_None:
12094 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012095
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012096 case EST_ComputedNoexcept:
12097 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12098 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012099
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012100 case EST_Dynamic:
12101 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012102 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012103 E != EEnd; ++E) {
12104 if (!Finder.TraverseType(*E))
12105 return true;
12106 }
12107 break;
12108 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012109
12110 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012111}
12112
12113bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12114 FindCXXThisExpr Finder(*this);
12115
12116 // Check attributes.
12117 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12118 A != AEnd; ++A) {
12119 // FIXME: This should be emitted by tblgen.
12120 Expr *Arg = 0;
12121 ArrayRef<Expr *> Args;
12122 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12123 Arg = G->getArg();
12124 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12125 Arg = G->getArg();
12126 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12127 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12128 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12129 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12130 else if (ExclusiveLockFunctionAttr *ELF
12131 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12132 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12133 else if (SharedLockFunctionAttr *SLF
12134 = dyn_cast<SharedLockFunctionAttr>(*A))
12135 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12136 else if (ExclusiveTrylockFunctionAttr *ETLF
12137 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12138 Arg = ETLF->getSuccessValue();
12139 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12140 } else if (SharedTrylockFunctionAttr *STLF
12141 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12142 Arg = STLF->getSuccessValue();
12143 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12144 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12145 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12146 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12147 Arg = LR->getArg();
12148 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12149 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12150 else if (ExclusiveLocksRequiredAttr *ELR
12151 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12152 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12153 else if (SharedLocksRequiredAttr *SLR
12154 = dyn_cast<SharedLocksRequiredAttr>(*A))
12155 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12156
12157 if (Arg && !Finder.TraverseStmt(Arg))
12158 return true;
12159
12160 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12161 if (!Finder.TraverseStmt(Args[I]))
12162 return true;
12163 }
12164 }
12165
12166 return false;
12167}
12168
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012169void
12170Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12171 ArrayRef<ParsedType> DynamicExceptions,
12172 ArrayRef<SourceRange> DynamicExceptionRanges,
12173 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012174 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012175 FunctionProtoType::ExtProtoInfo &EPI) {
12176 Exceptions.clear();
12177 EPI.ExceptionSpecType = EST;
12178 if (EST == EST_Dynamic) {
12179 Exceptions.reserve(DynamicExceptions.size());
12180 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12181 // FIXME: Preserve type source info.
12182 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12183
12184 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12185 collectUnexpandedParameterPacks(ET, Unexpanded);
12186 if (!Unexpanded.empty()) {
12187 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12188 UPPC_ExceptionType,
12189 Unexpanded);
12190 continue;
12191 }
12192
12193 // Check that the type is valid for an exception spec, and
12194 // drop it if not.
12195 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12196 Exceptions.push_back(ET);
12197 }
12198 EPI.NumExceptions = Exceptions.size();
12199 EPI.Exceptions = Exceptions.data();
12200 return;
12201 }
12202
12203 if (EST == EST_ComputedNoexcept) {
12204 // If an error occurred, there's no expression here.
12205 if (NoexceptExpr) {
12206 assert((NoexceptExpr->isTypeDependent() ||
12207 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12208 Context.BoolTy) &&
12209 "Parser should have made sure that the expression is boolean");
12210 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12211 EPI.ExceptionSpecType = EST_BasicNoexcept;
12212 return;
12213 }
12214
12215 if (!NoexceptExpr->isValueDependent())
12216 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012217 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012218 /*AllowFold*/ false).take();
12219 EPI.NoexceptExpr = NoexceptExpr;
12220 }
12221 return;
12222 }
12223}
12224
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012225/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12226Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12227 // Implicitly declared functions (e.g. copy constructors) are
12228 // __host__ __device__
12229 if (D->isImplicit())
12230 return CFT_HostDevice;
12231
12232 if (D->hasAttr<CUDAGlobalAttr>())
12233 return CFT_Global;
12234
12235 if (D->hasAttr<CUDADeviceAttr>()) {
12236 if (D->hasAttr<CUDAHostAttr>())
12237 return CFT_HostDevice;
12238 else
12239 return CFT_Device;
12240 }
12241
12242 return CFT_Host;
12243}
12244
12245bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12246 CUDAFunctionTarget CalleeTarget) {
12247 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12248 // Callable from the device only."
12249 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12250 return true;
12251
12252 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12253 // Callable from the host only."
12254 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12255 // Callable from the host only."
12256 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12257 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12258 return true;
12259
12260 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12261 return true;
12262
12263 return false;
12264}
John McCall76da55d2013-04-16 07:28:30 +000012265
12266/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12267///
12268MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12269 SourceLocation DeclStart,
12270 Declarator &D, Expr *BitWidth,
12271 InClassInitStyle InitStyle,
12272 AccessSpecifier AS,
12273 AttributeList *MSPropertyAttr) {
12274 IdentifierInfo *II = D.getIdentifier();
12275 if (!II) {
12276 Diag(DeclStart, diag::err_anonymous_property);
12277 return NULL;
12278 }
12279 SourceLocation Loc = D.getIdentifierLoc();
12280
12281 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12282 QualType T = TInfo->getType();
12283 if (getLangOpts().CPlusPlus) {
12284 CheckExtraCXXDefaultArguments(D);
12285
12286 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12287 UPPC_DataMemberType)) {
12288 D.setInvalidType();
12289 T = Context.IntTy;
12290 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12291 }
12292 }
12293
12294 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12295
12296 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12297 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12298 diag::err_invalid_thread)
12299 << DeclSpec::getSpecifierName(TSCS);
12300
12301 // Check to see if this name was declared as a member previously
12302 NamedDecl *PrevDecl = 0;
12303 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12304 LookupName(Previous, S);
12305 switch (Previous.getResultKind()) {
12306 case LookupResult::Found:
12307 case LookupResult::FoundUnresolvedValue:
12308 PrevDecl = Previous.getAsSingle<NamedDecl>();
12309 break;
12310
12311 case LookupResult::FoundOverloaded:
12312 PrevDecl = Previous.getRepresentativeDecl();
12313 break;
12314
12315 case LookupResult::NotFound:
12316 case LookupResult::NotFoundInCurrentInstantiation:
12317 case LookupResult::Ambiguous:
12318 break;
12319 }
12320
12321 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12322 // Maybe we will complain about the shadowed template parameter.
12323 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12324 // Just pretend that we didn't see the previous declaration.
12325 PrevDecl = 0;
12326 }
12327
12328 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12329 PrevDecl = 0;
12330
12331 SourceLocation TSSL = D.getLocStart();
12332 MSPropertyDecl *NewPD;
12333 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12334 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12335 II, T, TInfo, TSSL,
12336 Data.GetterId, Data.SetterId);
12337 ProcessDeclAttributes(TUScope, NewPD, D);
12338 NewPD->setAccess(AS);
12339
12340 if (NewPD->isInvalidDecl())
12341 Record->setInvalidDecl();
12342
12343 if (D.getDeclSpec().isModulePrivateSpecified())
12344 NewPD->setModulePrivate();
12345
12346 if (NewPD->isInvalidDecl() && PrevDecl) {
12347 // Don't introduce NewFD into scope; there's already something
12348 // with the same name in the same scope.
12349 } else if (II) {
12350 PushOnScopeChains(NewPD, S);
12351 } else
12352 Record->addDecl(NewPD);
12353
12354 return NewPD;
12355}