blob: bfde60e8f87c2e8938ea354f379f32b4ba8c03e7 [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 Gribenko1f78a502013-05-03 15:05:50 +00002859 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, MultiExprArg());
Benjamin Kramer5354e772012-08-23 23:38:35 +00002860 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
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);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003087
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003088 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall60d7b3a2010-08-24 06:29:42 +00003089 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00003090 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
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 [...]
4281 switch (CSM) {
4282 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004283 // Since default constructor lookup is essentially trivial (and cannot
4284 // involve, for instance, template instantiation), we compute whether a
4285 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4286 //
4287 // This is important for performance; we need to know whether the default
4288 // constructor is constexpr to determine whether the type is a literal type.
4289 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4290
Richard Smith7756afa2012-06-10 05:43:50 +00004291 case Sema::CXXCopyConstructor:
4292 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004293 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004294 break;
4295
4296 case Sema::CXXCopyAssignment:
4297 case Sema::CXXMoveAssignment:
4298 case Sema::CXXDestructor:
4299 case Sema::CXXInvalid:
4300 return false;
4301 }
4302
4303 // -- if the class is a non-empty union, or for each non-empty anonymous
4304 // union member of a non-union class, exactly one non-static data member
4305 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004306 //
4307 // If we squint, this is guaranteed, since exactly one non-static data member
4308 // will be initialized (if the constructor isn't deleted), we just don't know
4309 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004310 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004311 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004312
4313 // -- the class shall not have any virtual base classes;
4314 if (ClassDecl->getNumVBases())
4315 return false;
4316
4317 // -- every constructor involved in initializing [...] base class
4318 // sub-objects shall be a constexpr constructor;
4319 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4320 BEnd = ClassDecl->bases_end();
4321 B != BEnd; ++B) {
4322 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4323 if (!BaseType) continue;
4324
4325 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4326 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4327 return false;
4328 }
4329
4330 // -- every constructor involved in initializing non-static data members
4331 // [...] shall be a constexpr constructor;
4332 // -- every non-static data member and base class sub-object shall be
4333 // initialized
4334 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4335 FEnd = ClassDecl->field_end();
4336 F != FEnd; ++F) {
4337 if (F->isInvalidDecl())
4338 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004339 if (const RecordType *RecordTy =
4340 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004341 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4342 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4343 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004344 }
4345 }
4346
4347 // All OK, it's constexpr!
4348 return true;
4349}
4350
Richard Smithb9d0b762012-07-27 04:22:15 +00004351static Sema::ImplicitExceptionSpecification
4352computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4353 switch (S.getSpecialMember(MD)) {
4354 case Sema::CXXDefaultConstructor:
4355 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4356 case Sema::CXXCopyConstructor:
4357 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4358 case Sema::CXXCopyAssignment:
4359 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4360 case Sema::CXXMoveConstructor:
4361 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4362 case Sema::CXXMoveAssignment:
4363 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4364 case Sema::CXXDestructor:
4365 return S.ComputeDefaultedDtorExceptionSpec(MD);
4366 case Sema::CXXInvalid:
4367 break;
4368 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004369 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4370 "only special members have implicit exception specs");
4371 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004372}
4373
Richard Smithdd25e802012-07-30 23:48:14 +00004374static void
4375updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4376 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4377 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4378 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004379 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4380 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004381}
4382
Richard Smithb9d0b762012-07-27 04:22:15 +00004383void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4384 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4385 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4386 return;
4387
Richard Smithdd25e802012-07-30 23:48:14 +00004388 // Evaluate the exception specification.
4389 ImplicitExceptionSpecification ExceptSpec =
4390 computeImplicitExceptionSpec(*this, Loc, MD);
4391
4392 // Update the type of the special member to use it.
4393 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4394
4395 // A user-provided destructor can be defined outside the class. When that
4396 // happens, be sure to update the exception specification on both
4397 // declarations.
4398 const FunctionProtoType *CanonicalFPT =
4399 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4400 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4401 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4402 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004403}
4404
Richard Smith3003e1d2012-05-15 04:39:51 +00004405void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4406 CXXRecordDecl *RD = MD->getParent();
4407 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004408
Richard Smith3003e1d2012-05-15 04:39:51 +00004409 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4410 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004411
4412 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004413 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004414 bool First = MD == MD->getCanonicalDecl();
4415
4416 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004417
4418 // C++11 [dcl.fct.def.default]p1:
4419 // A function that is explicitly defaulted shall
4420 // -- be a special member function (checked elsewhere),
4421 // -- have the same type (except for ref-qualifiers, and except that a
4422 // copy operation can take a non-const reference) as an implicit
4423 // declaration, and
4424 // -- not have default arguments.
4425 unsigned ExpectedParams = 1;
4426 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4427 ExpectedParams = 0;
4428 if (MD->getNumParams() != ExpectedParams) {
4429 // This also checks for default arguments: a copy or move constructor with a
4430 // default argument is classified as a default constructor, and assignment
4431 // operations and destructors can't have default arguments.
4432 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4433 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004434 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004435 } else if (MD->isVariadic()) {
4436 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4437 << CSM << MD->getSourceRange();
4438 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004439 }
4440
Richard Smith3003e1d2012-05-15 04:39:51 +00004441 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004442
Richard Smith7756afa2012-06-10 05:43:50 +00004443 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004444 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004445 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004446 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004447 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004448
Richard Smith3003e1d2012-05-15 04:39:51 +00004449 QualType ReturnType = Context.VoidTy;
4450 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4451 // Check for return type matching.
4452 ReturnType = Type->getResultType();
4453 QualType ExpectedReturnType =
4454 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4455 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4456 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4457 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4458 HadError = true;
4459 }
4460
4461 // A defaulted special member cannot have cv-qualifiers.
4462 if (Type->getTypeQuals()) {
4463 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4464 << (CSM == CXXMoveAssignment);
4465 HadError = true;
4466 }
4467 }
4468
4469 // Check for parameter type matching.
4470 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004471 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004472 if (ExpectedParams && ArgType->isReferenceType()) {
4473 // Argument must be reference to possibly-const T.
4474 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004475 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004476
4477 if (ReferentType.isVolatileQualified()) {
4478 Diag(MD->getLocation(),
4479 diag::err_defaulted_special_member_volatile_param) << CSM;
4480 HadError = true;
4481 }
4482
Richard Smith7756afa2012-06-10 05:43:50 +00004483 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004484 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4485 Diag(MD->getLocation(),
4486 diag::err_defaulted_special_member_copy_const_param)
4487 << (CSM == CXXCopyAssignment);
4488 // FIXME: Explain why this special member can't be const.
4489 } else {
4490 Diag(MD->getLocation(),
4491 diag::err_defaulted_special_member_move_const_param)
4492 << (CSM == CXXMoveAssignment);
4493 }
4494 HadError = true;
4495 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004496 } else if (ExpectedParams) {
4497 // A copy assignment operator can take its argument by value, but a
4498 // defaulted one cannot.
4499 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004500 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004501 HadError = true;
4502 }
Sean Huntbe631222011-05-17 20:44:43 +00004503
Richard Smith61802452011-12-22 02:22:31 +00004504 // C++11 [dcl.fct.def.default]p2:
4505 // An explicitly-defaulted function may be declared constexpr only if it
4506 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004507 // Do not apply this rule to members of class templates, since core issue 1358
4508 // makes such functions always instantiate to constexpr functions. For
4509 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004510 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4511 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004512 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4513 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4514 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004515 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004516 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004517 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004518
Richard Smith61802452011-12-22 02:22:31 +00004519 // and may have an explicit exception-specification only if it is compatible
4520 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004521 if (Type->hasExceptionSpec()) {
4522 // Delay the check if this is the first declaration of the special member,
4523 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004524 if (First) {
4525 // If the exception specification needs to be instantiated, do so now,
4526 // before we clobber it with an EST_Unevaluated specification below.
4527 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4528 InstantiateExceptionSpec(MD->getLocStart(), MD);
4529 Type = MD->getType()->getAs<FunctionProtoType>();
4530 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004531 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004532 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004533 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4534 }
Richard Smith61802452011-12-22 02:22:31 +00004535
4536 // If a function is explicitly defaulted on its first declaration,
4537 if (First) {
4538 // -- it is implicitly considered to be constexpr if the implicit
4539 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004540 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004541
Richard Smith3003e1d2012-05-15 04:39:51 +00004542 // -- it is implicitly considered to have the same exception-specification
4543 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004544 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4545 EPI.ExceptionSpecType = EST_Unevaluated;
4546 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004547 MD->setType(Context.getFunctionType(ReturnType,
4548 ArrayRef<QualType>(&ArgType,
4549 ExpectedParams),
4550 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004551 }
4552
Richard Smith3003e1d2012-05-15 04:39:51 +00004553 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004554 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004555 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004556 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004557 // C++11 [dcl.fct.def.default]p4:
4558 // [For a] user-provided explicitly-defaulted function [...] if such a
4559 // function is implicitly defined as deleted, the program is ill-formed.
4560 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4561 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004562 }
4563 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004564
Richard Smith3003e1d2012-05-15 04:39:51 +00004565 if (HadError)
4566 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004567}
4568
Richard Smith1d28caf2012-12-11 01:14:52 +00004569/// Check whether the exception specification provided for an
4570/// explicitly-defaulted special member matches the exception specification
4571/// that would have been generated for an implicit special member, per
4572/// C++11 [dcl.fct.def.default]p2.
4573void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4574 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4575 // Compute the implicit exception specification.
4576 FunctionProtoType::ExtProtoInfo EPI;
4577 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4578 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004579 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004580
4581 // Ensure that it matches.
4582 CheckEquivalentExceptionSpec(
4583 PDiag(diag::err_incorrect_defaulted_exception_spec)
4584 << getSpecialMember(MD), PDiag(),
4585 ImplicitType, SourceLocation(),
4586 SpecifiedType, MD->getLocation());
4587}
4588
4589void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4590 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4591 I != N; ++I)
4592 CheckExplicitlyDefaultedMemberExceptionSpec(
4593 DelayedDefaultedMemberExceptionSpecs[I].first,
4594 DelayedDefaultedMemberExceptionSpecs[I].second);
4595
4596 DelayedDefaultedMemberExceptionSpecs.clear();
4597}
4598
Richard Smith7d5088a2012-02-18 02:02:13 +00004599namespace {
4600struct SpecialMemberDeletionInfo {
4601 Sema &S;
4602 CXXMethodDecl *MD;
4603 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004604 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004605
4606 // Properties of the special member, computed for convenience.
4607 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4608 SourceLocation Loc;
4609
4610 bool AllFieldsAreConst;
4611
4612 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004613 Sema::CXXSpecialMember CSM, bool Diagnose)
4614 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004615 IsConstructor(false), IsAssignment(false), IsMove(false),
4616 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4617 AllFieldsAreConst(true) {
4618 switch (CSM) {
4619 case Sema::CXXDefaultConstructor:
4620 case Sema::CXXCopyConstructor:
4621 IsConstructor = true;
4622 break;
4623 case Sema::CXXMoveConstructor:
4624 IsConstructor = true;
4625 IsMove = true;
4626 break;
4627 case Sema::CXXCopyAssignment:
4628 IsAssignment = true;
4629 break;
4630 case Sema::CXXMoveAssignment:
4631 IsAssignment = true;
4632 IsMove = true;
4633 break;
4634 case Sema::CXXDestructor:
4635 break;
4636 case Sema::CXXInvalid:
4637 llvm_unreachable("invalid special member kind");
4638 }
4639
4640 if (MD->getNumParams()) {
4641 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4642 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4643 }
4644 }
4645
4646 bool inUnion() const { return MD->getParent()->isUnion(); }
4647
4648 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004649 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4650 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004651 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004652 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4653 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4654 Quals = 0;
4655 return S.LookupSpecialMember(Class, CSM,
4656 ConstArg || (Quals & Qualifiers::Const),
4657 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004658 MD->getRefQualifier() == RQ_RValue,
4659 TQ & Qualifiers::Const,
4660 TQ & Qualifiers::Volatile);
4661 }
4662
Richard Smith6c4c36c2012-03-30 20:53:28 +00004663 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004664
Richard Smith6c4c36c2012-03-30 20:53:28 +00004665 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004666 bool shouldDeleteForField(FieldDecl *FD);
4667 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004668
Richard Smith517bb842012-07-18 03:51:16 +00004669 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4670 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004671 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4672 Sema::SpecialMemberOverloadResult *SMOR,
4673 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004674
4675 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004676};
4677}
4678
John McCall12d8d802012-04-09 20:53:23 +00004679/// Is the given special member inaccessible when used on the given
4680/// sub-object.
4681bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4682 CXXMethodDecl *target) {
4683 /// If we're operating on a base class, the object type is the
4684 /// type of this special member.
4685 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004686 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004687 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4688 objectTy = S.Context.getTypeDeclType(MD->getParent());
4689 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4690
4691 // If we're operating on a field, the object type is the type of the field.
4692 } else {
4693 objectTy = S.Context.getTypeDeclType(target->getParent());
4694 }
4695
4696 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4697}
4698
Richard Smith6c4c36c2012-03-30 20:53:28 +00004699/// Check whether we should delete a special member due to the implicit
4700/// definition containing a call to a special member of a subobject.
4701bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4702 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4703 bool IsDtorCallInCtor) {
4704 CXXMethodDecl *Decl = SMOR->getMethod();
4705 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4706
4707 int DiagKind = -1;
4708
4709 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4710 DiagKind = !Decl ? 0 : 1;
4711 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4712 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004713 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004714 DiagKind = 3;
4715 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4716 !Decl->isTrivial()) {
4717 // A member of a union must have a trivial corresponding special member.
4718 // As a weird special case, a destructor call from a union's constructor
4719 // must be accessible and non-deleted, but need not be trivial. Such a
4720 // destructor is never actually called, but is semantically checked as
4721 // if it were.
4722 DiagKind = 4;
4723 }
4724
4725 if (DiagKind == -1)
4726 return false;
4727
4728 if (Diagnose) {
4729 if (Field) {
4730 S.Diag(Field->getLocation(),
4731 diag::note_deleted_special_member_class_subobject)
4732 << CSM << MD->getParent() << /*IsField*/true
4733 << Field << DiagKind << IsDtorCallInCtor;
4734 } else {
4735 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4736 S.Diag(Base->getLocStart(),
4737 diag::note_deleted_special_member_class_subobject)
4738 << CSM << MD->getParent() << /*IsField*/false
4739 << Base->getType() << DiagKind << IsDtorCallInCtor;
4740 }
4741
4742 if (DiagKind == 1)
4743 S.NoteDeletedFunction(Decl);
4744 // FIXME: Explain inaccessibility if DiagKind == 3.
4745 }
4746
4747 return true;
4748}
4749
Richard Smith9a561d52012-02-26 09:11:52 +00004750/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004751/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004752bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004753 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004754 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004755
4756 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004757 // -- any direct or virtual base class, or non-static data member with no
4758 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004759 // either M has no default constructor or overload resolution as applied
4760 // to M's default constructor results in an ambiguity or in a function
4761 // that is deleted or inaccessible
4762 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4763 // -- a direct or virtual base class B that cannot be copied/moved because
4764 // overload resolution, as applied to B's corresponding special member,
4765 // results in an ambiguity or a function that is deleted or inaccessible
4766 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004767 // C++11 [class.dtor]p5:
4768 // -- any direct or virtual base class [...] has a type with a destructor
4769 // that is deleted or inaccessible
4770 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004771 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004772 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004773 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004774
Richard Smith6c4c36c2012-03-30 20:53:28 +00004775 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4776 // -- any direct or virtual base class or non-static data member has a
4777 // type with a destructor that is deleted or inaccessible
4778 if (IsConstructor) {
4779 Sema::SpecialMemberOverloadResult *SMOR =
4780 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4781 false, false, false, false, false);
4782 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4783 return true;
4784 }
4785
Richard Smith9a561d52012-02-26 09:11:52 +00004786 return false;
4787}
4788
4789/// Check whether we should delete a special member function due to the class
4790/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004791bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004792 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004793 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004794}
4795
4796/// Check whether we should delete a special member function due to the class
4797/// having a particular non-static data member.
4798bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4799 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4800 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4801
4802 if (CSM == Sema::CXXDefaultConstructor) {
4803 // For a default constructor, all references must be initialized in-class
4804 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004805 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4806 if (Diagnose)
4807 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4808 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004809 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004810 }
Richard Smith79363f52012-02-27 06:07:25 +00004811 // C++11 [class.ctor]p5: any non-variant non-static data member of
4812 // const-qualified type (or array thereof) with no
4813 // brace-or-equal-initializer does not have a user-provided default
4814 // constructor.
4815 if (!inUnion() && FieldType.isConstQualified() &&
4816 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004817 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4818 if (Diagnose)
4819 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004820 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004821 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004822 }
4823
4824 if (inUnion() && !FieldType.isConstQualified())
4825 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004826 } else if (CSM == Sema::CXXCopyConstructor) {
4827 // For a copy constructor, data members must not be of rvalue reference
4828 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004829 if (FieldType->isRValueReferenceType()) {
4830 if (Diagnose)
4831 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4832 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004833 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004834 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004835 } else if (IsAssignment) {
4836 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004837 if (FieldType->isReferenceType()) {
4838 if (Diagnose)
4839 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4840 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004841 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004842 }
4843 if (!FieldRecord && FieldType.isConstQualified()) {
4844 // C++11 [class.copy]p23:
4845 // -- a non-static data member of const non-class type (or array thereof)
4846 if (Diagnose)
4847 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004848 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004849 return true;
4850 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004851 }
4852
4853 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004854 // Some additional restrictions exist on the variant members.
4855 if (!inUnion() && FieldRecord->isUnion() &&
4856 FieldRecord->isAnonymousStructOrUnion()) {
4857 bool AllVariantFieldsAreConst = true;
4858
Richard Smithdf8dc862012-03-29 19:00:10 +00004859 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004860 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4861 UE = FieldRecord->field_end();
4862 UI != UE; ++UI) {
4863 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004864
4865 if (!UnionFieldType.isConstQualified())
4866 AllVariantFieldsAreConst = false;
4867
Richard Smith9a561d52012-02-26 09:11:52 +00004868 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4869 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004870 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4871 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004872 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004873 }
4874
4875 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004876 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004877 FieldRecord->field_begin() != FieldRecord->field_end()) {
4878 if (Diagnose)
4879 S.Diag(FieldRecord->getLocation(),
4880 diag::note_deleted_default_ctor_all_const)
4881 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004882 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004883 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004884
Richard Smithdf8dc862012-03-29 19:00:10 +00004885 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004886 // This is technically non-conformant, but sanity demands it.
4887 return false;
4888 }
4889
Richard Smith517bb842012-07-18 03:51:16 +00004890 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4891 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004892 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004893 }
4894
4895 return false;
4896}
4897
4898/// C++11 [class.ctor] p5:
4899/// A defaulted default constructor for a class X is defined as deleted if
4900/// X is a union and all of its variant members are of const-qualified type.
4901bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004902 // This is a silly definition, because it gives an empty union a deleted
4903 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004904 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4905 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4906 if (Diagnose)
4907 S.Diag(MD->getParent()->getLocation(),
4908 diag::note_deleted_default_ctor_all_const)
4909 << MD->getParent() << /*not anonymous union*/0;
4910 return true;
4911 }
4912 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004913}
4914
4915/// Determine whether a defaulted special member function should be defined as
4916/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4917/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004918bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4919 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004920 if (MD->isInvalidDecl())
4921 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004922 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004923 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004924 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004925 return false;
4926
Richard Smith7d5088a2012-02-18 02:02:13 +00004927 // C++11 [expr.lambda.prim]p19:
4928 // The closure type associated with a lambda-expression has a
4929 // deleted (8.4.3) default constructor and a deleted copy
4930 // assignment operator.
4931 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004932 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4933 if (Diagnose)
4934 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004935 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004936 }
4937
Richard Smith5bdaac52012-04-02 20:59:25 +00004938 // For an anonymous struct or union, the copy and assignment special members
4939 // will never be used, so skip the check. For an anonymous union declared at
4940 // namespace scope, the constructor and destructor are used.
4941 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4942 RD->isAnonymousStructOrUnion())
4943 return false;
4944
Richard Smith6c4c36c2012-03-30 20:53:28 +00004945 // C++11 [class.copy]p7, p18:
4946 // If the class definition declares a move constructor or move assignment
4947 // operator, an implicitly declared copy constructor or copy assignment
4948 // operator is defined as deleted.
4949 if (MD->isImplicit() &&
4950 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4951 CXXMethodDecl *UserDeclaredMove = 0;
4952
4953 // In Microsoft mode, a user-declared move only causes the deletion of the
4954 // corresponding copy operation, not both copy operations.
4955 if (RD->hasUserDeclaredMoveConstructor() &&
4956 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4957 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004958
4959 // Find any user-declared move constructor.
4960 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4961 E = RD->ctor_end(); I != E; ++I) {
4962 if (I->isMoveConstructor()) {
4963 UserDeclaredMove = *I;
4964 break;
4965 }
4966 }
Richard Smith1c931be2012-04-02 18:40:40 +00004967 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004968 } else if (RD->hasUserDeclaredMoveAssignment() &&
4969 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4970 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004971
4972 // Find any user-declared move assignment operator.
4973 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4974 E = RD->method_end(); I != E; ++I) {
4975 if (I->isMoveAssignmentOperator()) {
4976 UserDeclaredMove = *I;
4977 break;
4978 }
4979 }
Richard Smith1c931be2012-04-02 18:40:40 +00004980 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004981 }
4982
4983 if (UserDeclaredMove) {
4984 Diag(UserDeclaredMove->getLocation(),
4985 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004986 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004987 << UserDeclaredMove->isMoveAssignmentOperator();
4988 return true;
4989 }
4990 }
Sean Hunte16da072011-10-10 06:18:57 +00004991
Richard Smith5bdaac52012-04-02 20:59:25 +00004992 // Do access control from the special member function
4993 ContextRAII MethodContext(*this, MD);
4994
Richard Smith9a561d52012-02-26 09:11:52 +00004995 // C++11 [class.dtor]p5:
4996 // -- for a virtual destructor, lookup of the non-array deallocation function
4997 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004998 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004999 FunctionDecl *OperatorDelete = 0;
5000 DeclarationName Name =
5001 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5002 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005003 OperatorDelete, false)) {
5004 if (Diagnose)
5005 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005006 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005007 }
Richard Smith9a561d52012-02-26 09:11:52 +00005008 }
5009
Richard Smith6c4c36c2012-03-30 20:53:28 +00005010 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005011
Sean Huntcdee3fe2011-05-11 22:34:38 +00005012 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005013 BE = RD->bases_end(); BI != BE; ++BI)
5014 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005015 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005016 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005017
5018 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005019 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00005020 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005021 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005022
5023 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005024 FE = RD->field_end(); FI != FE; ++FI)
5025 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005026 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005027 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005028
Richard Smith7d5088a2012-02-18 02:02:13 +00005029 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005030 return true;
5031
5032 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005033}
5034
Richard Smithac713512012-12-08 02:53:02 +00005035/// Perform lookup for a special member of the specified kind, and determine
5036/// whether it is trivial. If the triviality can be determined without the
5037/// lookup, skip it. This is intended for use when determining whether a
5038/// special member of a containing object is trivial, and thus does not ever
5039/// perform overload resolution for default constructors.
5040///
5041/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5042/// member that was most likely to be intended to be trivial, if any.
5043static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5044 Sema::CXXSpecialMember CSM, unsigned Quals,
5045 CXXMethodDecl **Selected) {
5046 if (Selected)
5047 *Selected = 0;
5048
5049 switch (CSM) {
5050 case Sema::CXXInvalid:
5051 llvm_unreachable("not a special member");
5052
5053 case Sema::CXXDefaultConstructor:
5054 // C++11 [class.ctor]p5:
5055 // A default constructor is trivial if:
5056 // - all the [direct subobjects] have trivial default constructors
5057 //
5058 // Note, no overload resolution is performed in this case.
5059 if (RD->hasTrivialDefaultConstructor())
5060 return true;
5061
5062 if (Selected) {
5063 // If there's a default constructor which could have been trivial, dig it
5064 // out. Otherwise, if there's any user-provided default constructor, point
5065 // to that as an example of why there's not a trivial one.
5066 CXXConstructorDecl *DefCtor = 0;
5067 if (RD->needsImplicitDefaultConstructor())
5068 S.DeclareImplicitDefaultConstructor(RD);
5069 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5070 CE = RD->ctor_end(); CI != CE; ++CI) {
5071 if (!CI->isDefaultConstructor())
5072 continue;
5073 DefCtor = *CI;
5074 if (!DefCtor->isUserProvided())
5075 break;
5076 }
5077
5078 *Selected = DefCtor;
5079 }
5080
5081 return false;
5082
5083 case Sema::CXXDestructor:
5084 // C++11 [class.dtor]p5:
5085 // A destructor is trivial if:
5086 // - all the direct [subobjects] have trivial destructors
5087 if (RD->hasTrivialDestructor())
5088 return true;
5089
5090 if (Selected) {
5091 if (RD->needsImplicitDestructor())
5092 S.DeclareImplicitDestructor(RD);
5093 *Selected = RD->getDestructor();
5094 }
5095
5096 return false;
5097
5098 case Sema::CXXCopyConstructor:
5099 // C++11 [class.copy]p12:
5100 // A copy constructor is trivial if:
5101 // - the constructor selected to copy each direct [subobject] is trivial
5102 if (RD->hasTrivialCopyConstructor()) {
5103 if (Quals == Qualifiers::Const)
5104 // We must either select the trivial copy constructor or reach an
5105 // ambiguity; no need to actually perform overload resolution.
5106 return true;
5107 } else if (!Selected) {
5108 return false;
5109 }
5110 // In C++98, we are not supposed to perform overload resolution here, but we
5111 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5112 // cases like B as having a non-trivial copy constructor:
5113 // struct A { template<typename T> A(T&); };
5114 // struct B { mutable A a; };
5115 goto NeedOverloadResolution;
5116
5117 case Sema::CXXCopyAssignment:
5118 // C++11 [class.copy]p25:
5119 // A copy assignment operator is trivial if:
5120 // - the assignment operator selected to copy each direct [subobject] is
5121 // trivial
5122 if (RD->hasTrivialCopyAssignment()) {
5123 if (Quals == Qualifiers::Const)
5124 return true;
5125 } else if (!Selected) {
5126 return false;
5127 }
5128 // In C++98, we are not supposed to perform overload resolution here, but we
5129 // treat that as a language defect.
5130 goto NeedOverloadResolution;
5131
5132 case Sema::CXXMoveConstructor:
5133 case Sema::CXXMoveAssignment:
5134 NeedOverloadResolution:
5135 Sema::SpecialMemberOverloadResult *SMOR =
5136 S.LookupSpecialMember(RD, CSM,
5137 Quals & Qualifiers::Const,
5138 Quals & Qualifiers::Volatile,
5139 /*RValueThis*/false, /*ConstThis*/false,
5140 /*VolatileThis*/false);
5141
5142 // The standard doesn't describe how to behave if the lookup is ambiguous.
5143 // We treat it as not making the member non-trivial, just like the standard
5144 // mandates for the default constructor. This should rarely matter, because
5145 // the member will also be deleted.
5146 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5147 return true;
5148
5149 if (!SMOR->getMethod()) {
5150 assert(SMOR->getKind() ==
5151 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5152 return false;
5153 }
5154
5155 // We deliberately don't check if we found a deleted special member. We're
5156 // not supposed to!
5157 if (Selected)
5158 *Selected = SMOR->getMethod();
5159 return SMOR->getMethod()->isTrivial();
5160 }
5161
5162 llvm_unreachable("unknown special method kind");
5163}
5164
Benjamin Kramera574c892013-02-15 12:30:38 +00005165static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005166 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5167 CI != CE; ++CI)
5168 if (!CI->isImplicit())
5169 return *CI;
5170
5171 // Look for constructor templates.
5172 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5173 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5174 if (CXXConstructorDecl *CD =
5175 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5176 return CD;
5177 }
5178
5179 return 0;
5180}
5181
5182/// The kind of subobject we are checking for triviality. The values of this
5183/// enumeration are used in diagnostics.
5184enum TrivialSubobjectKind {
5185 /// The subobject is a base class.
5186 TSK_BaseClass,
5187 /// The subobject is a non-static data member.
5188 TSK_Field,
5189 /// The object is actually the complete object.
5190 TSK_CompleteObject
5191};
5192
5193/// Check whether the special member selected for a given type would be trivial.
5194static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5195 QualType SubType,
5196 Sema::CXXSpecialMember CSM,
5197 TrivialSubobjectKind Kind,
5198 bool Diagnose) {
5199 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5200 if (!SubRD)
5201 return true;
5202
5203 CXXMethodDecl *Selected;
5204 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5205 Diagnose ? &Selected : 0))
5206 return true;
5207
5208 if (Diagnose) {
5209 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5210 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5211 << Kind << SubType.getUnqualifiedType();
5212 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5213 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5214 } else if (!Selected)
5215 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5216 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5217 else if (Selected->isUserProvided()) {
5218 if (Kind == TSK_CompleteObject)
5219 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5220 << Kind << SubType.getUnqualifiedType() << CSM;
5221 else {
5222 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5223 << Kind << SubType.getUnqualifiedType() << CSM;
5224 S.Diag(Selected->getLocation(), diag::note_declared_at);
5225 }
5226 } else {
5227 if (Kind != TSK_CompleteObject)
5228 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5229 << Kind << SubType.getUnqualifiedType() << CSM;
5230
5231 // Explain why the defaulted or deleted special member isn't trivial.
5232 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5233 }
5234 }
5235
5236 return false;
5237}
5238
5239/// Check whether the members of a class type allow a special member to be
5240/// trivial.
5241static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5242 Sema::CXXSpecialMember CSM,
5243 bool ConstArg, bool Diagnose) {
5244 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5245 FE = RD->field_end(); FI != FE; ++FI) {
5246 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5247 continue;
5248
5249 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5250
5251 // Pretend anonymous struct or union members are members of this class.
5252 if (FI->isAnonymousStructOrUnion()) {
5253 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5254 CSM, ConstArg, Diagnose))
5255 return false;
5256 continue;
5257 }
5258
5259 // C++11 [class.ctor]p5:
5260 // A default constructor is trivial if [...]
5261 // -- no non-static data member of its class has a
5262 // brace-or-equal-initializer
5263 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5264 if (Diagnose)
5265 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5266 return false;
5267 }
5268
5269 // Objective C ARC 4.3.5:
5270 // [...] nontrivally ownership-qualified types are [...] not trivially
5271 // default constructible, copy constructible, move constructible, copy
5272 // assignable, move assignable, or destructible [...]
5273 if (S.getLangOpts().ObjCAutoRefCount &&
5274 FieldType.hasNonTrivialObjCLifetime()) {
5275 if (Diagnose)
5276 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5277 << RD << FieldType.getObjCLifetime();
5278 return false;
5279 }
5280
5281 if (ConstArg && !FI->isMutable())
5282 FieldType.addConst();
5283 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5284 TSK_Field, Diagnose))
5285 return false;
5286 }
5287
5288 return true;
5289}
5290
5291/// Diagnose why the specified class does not have a trivial special member of
5292/// the given kind.
5293void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5294 QualType Ty = Context.getRecordType(RD);
5295 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5296 Ty.addConst();
5297
5298 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5299 TSK_CompleteObject, /*Diagnose*/true);
5300}
5301
5302/// Determine whether a defaulted or deleted special member function is trivial,
5303/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5304/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5305bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5306 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005307 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5308
5309 CXXRecordDecl *RD = MD->getParent();
5310
5311 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005312
5313 // C++11 [class.copy]p12, p25:
5314 // A [special member] is trivial if its declared parameter type is the same
5315 // as if it had been implicitly declared [...]
5316 switch (CSM) {
5317 case CXXDefaultConstructor:
5318 case CXXDestructor:
5319 // Trivial default constructors and destructors cannot have parameters.
5320 break;
5321
5322 case CXXCopyConstructor:
5323 case CXXCopyAssignment: {
5324 // Trivial copy operations always have const, non-volatile parameter types.
5325 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005326 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005327 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5328 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5329 if (Diagnose)
5330 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5331 << Param0->getSourceRange() << Param0->getType()
5332 << Context.getLValueReferenceType(
5333 Context.getRecordType(RD).withConst());
5334 return false;
5335 }
5336 break;
5337 }
5338
5339 case CXXMoveConstructor:
5340 case CXXMoveAssignment: {
5341 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005342 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005343 const RValueReferenceType *RT =
5344 Param0->getType()->getAs<RValueReferenceType>();
5345 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5346 if (Diagnose)
5347 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5348 << Param0->getSourceRange() << Param0->getType()
5349 << Context.getRValueReferenceType(Context.getRecordType(RD));
5350 return false;
5351 }
5352 break;
5353 }
5354
5355 case CXXInvalid:
5356 llvm_unreachable("not a special member");
5357 }
5358
5359 // FIXME: We require that the parameter-declaration-clause is equivalent to
5360 // that of an implicit declaration, not just that the declared parameter type
5361 // matches, in order to prevent absuridities like a function simultaneously
5362 // being a trivial copy constructor and a non-trivial default constructor.
5363 // This issue has not yet been assigned a core issue number.
5364 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5365 if (Diagnose)
5366 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5367 diag::note_nontrivial_default_arg)
5368 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5369 return false;
5370 }
5371 if (MD->isVariadic()) {
5372 if (Diagnose)
5373 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5374 return false;
5375 }
5376
5377 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5378 // A copy/move [constructor or assignment operator] is trivial if
5379 // -- the [member] selected to copy/move each direct base class subobject
5380 // is trivial
5381 //
5382 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5383 // A [default constructor or destructor] is trivial if
5384 // -- all the direct base classes have trivial [default constructors or
5385 // destructors]
5386 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5387 BE = RD->bases_end(); BI != BE; ++BI)
5388 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5389 ConstArg ? BI->getType().withConst()
5390 : BI->getType(),
5391 CSM, TSK_BaseClass, Diagnose))
5392 return false;
5393
5394 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5395 // A copy/move [constructor or assignment operator] for a class X is
5396 // trivial if
5397 // -- for each non-static data member of X that is of class type (or array
5398 // thereof), the constructor selected to copy/move that member is
5399 // trivial
5400 //
5401 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5402 // A [default constructor or destructor] is trivial if
5403 // -- for all of the non-static data members of its class that are of class
5404 // type (or array thereof), each such class has a trivial [default
5405 // constructor or destructor]
5406 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5407 return false;
5408
5409 // C++11 [class.dtor]p5:
5410 // A destructor is trivial if [...]
5411 // -- the destructor is not virtual
5412 if (CSM == CXXDestructor && MD->isVirtual()) {
5413 if (Diagnose)
5414 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5415 return false;
5416 }
5417
5418 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5419 // A [special member] for class X is trivial if [...]
5420 // -- class X has no virtual functions and no virtual base classes
5421 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5422 if (!Diagnose)
5423 return false;
5424
5425 if (RD->getNumVBases()) {
5426 // Check for virtual bases. We already know that the corresponding
5427 // member in all bases is trivial, so vbases must all be direct.
5428 CXXBaseSpecifier &BS = *RD->vbases_begin();
5429 assert(BS.isVirtual());
5430 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5431 return false;
5432 }
5433
5434 // Must have a virtual method.
5435 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5436 ME = RD->method_end(); MI != ME; ++MI) {
5437 if (MI->isVirtual()) {
5438 SourceLocation MLoc = MI->getLocStart();
5439 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5440 return false;
5441 }
5442 }
5443
5444 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5445 }
5446
5447 // Looks like it's trivial!
5448 return true;
5449}
5450
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005451/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005452namespace {
5453 struct FindHiddenVirtualMethodData {
5454 Sema *S;
5455 CXXMethodDecl *Method;
5456 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005457 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005458 };
5459}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005460
David Blaikie5f750682012-10-19 00:53:08 +00005461/// \brief Check whether any most overriden method from MD in Methods
5462static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5463 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5464 if (MD->size_overridden_methods() == 0)
5465 return Methods.count(MD->getCanonicalDecl());
5466 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5467 E = MD->end_overridden_methods();
5468 I != E; ++I)
5469 if (CheckMostOverridenMethods(*I, Methods))
5470 return true;
5471 return false;
5472}
5473
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005474/// \brief Member lookup function that determines whether a given C++
5475/// method overloads virtual methods in a base class without overriding any,
5476/// to be used with CXXRecordDecl::lookupInBases().
5477static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5478 CXXBasePath &Path,
5479 void *UserData) {
5480 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5481
5482 FindHiddenVirtualMethodData &Data
5483 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5484
5485 DeclarationName Name = Data.Method->getDeclName();
5486 assert(Name.getNameKind() == DeclarationName::Identifier);
5487
5488 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005489 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005490 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005491 !Path.Decls.empty();
5492 Path.Decls = Path.Decls.slice(1)) {
5493 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005494 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005495 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005496 foundSameNameMethod = true;
5497 // Interested only in hidden virtual methods.
5498 if (!MD->isVirtual())
5499 continue;
5500 // If the method we are checking overrides a method from its base
5501 // don't warn about the other overloaded methods.
5502 if (!Data.S->IsOverload(Data.Method, MD, false))
5503 return true;
5504 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005505 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005506 overloadedMethods.push_back(MD);
5507 }
5508 }
5509
5510 if (foundSameNameMethod)
5511 Data.OverloadedMethods.append(overloadedMethods.begin(),
5512 overloadedMethods.end());
5513 return foundSameNameMethod;
5514}
5515
David Blaikie5f750682012-10-19 00:53:08 +00005516/// \brief Add the most overriden methods from MD to Methods
5517static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5518 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5519 if (MD->size_overridden_methods() == 0)
5520 Methods.insert(MD->getCanonicalDecl());
5521 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5522 E = MD->end_overridden_methods();
5523 I != E; ++I)
5524 AddMostOverridenMethods(*I, Methods);
5525}
5526
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005527/// \brief See if a method overloads virtual methods in a base class without
5528/// overriding any.
5529void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5530 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005531 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005532 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005533 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005534 return;
5535
5536 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5537 /*bool RecordPaths=*/false,
5538 /*bool DetectVirtual=*/false);
5539 FindHiddenVirtualMethodData Data;
5540 Data.Method = MD;
5541 Data.S = this;
5542
5543 // Keep the base methods that were overriden or introduced in the subclass
5544 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005545 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5546 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5547 NamedDecl *ND = *I;
5548 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005549 ND = shad->getTargetDecl();
5550 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5551 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005552 }
5553
5554 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5555 !Data.OverloadedMethods.empty()) {
5556 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5557 << MD << (Data.OverloadedMethods.size() > 1);
5558
5559 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5560 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005561 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005562 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005563 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5564 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005565 }
5566 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005567}
5568
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005569void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005570 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005571 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005572 SourceLocation RBrac,
5573 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005574 if (!TagDecl)
5575 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005576
Douglas Gregor42af25f2009-05-11 19:58:34 +00005577 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005578
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005579 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5580 if (l->getKind() != AttributeList::AT_Visibility)
5581 continue;
5582 l->setInvalid();
5583 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5584 l->getName();
5585 }
5586
David Blaikie77b6de02011-09-22 02:58:26 +00005587 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005588 // strict aliasing violation!
5589 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005590 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005591
Douglas Gregor23c94db2010-07-02 17:43:08 +00005592 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005593 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005594}
5595
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005596/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5597/// special functions, such as the default constructor, copy
5598/// constructor, or destructor, to the given C++ class (C++
5599/// [special]p1). This routine can only be executed just before the
5600/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005601void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005602 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005603 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005604
Richard Smithbc2a35d2012-12-08 08:32:28 +00005605 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005606 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005607
Richard Smithbc2a35d2012-12-08 08:32:28 +00005608 // If the properties or semantics of the copy constructor couldn't be
5609 // determined while the class was being declared, force a declaration
5610 // of it now.
5611 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5612 DeclareImplicitCopyConstructor(ClassDecl);
5613 }
5614
Richard Smith80ad52f2013-01-02 11:42:31 +00005615 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005616 ++ASTContext::NumImplicitMoveConstructors;
5617
Richard Smithbc2a35d2012-12-08 08:32:28 +00005618 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5619 DeclareImplicitMoveConstructor(ClassDecl);
5620 }
5621
Douglas Gregora376d102010-07-02 21:50:04 +00005622 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5623 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005624
5625 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005626 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005627 // it shows up in the right place in the vtable and that we diagnose
5628 // problems with the implicit exception specification.
5629 if (ClassDecl->isDynamicClass() ||
5630 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005631 DeclareImplicitCopyAssignment(ClassDecl);
5632 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005633
Richard Smith80ad52f2013-01-02 11:42:31 +00005634 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005635 ++ASTContext::NumImplicitMoveAssignmentOperators;
5636
5637 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005638 if (ClassDecl->isDynamicClass() ||
5639 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005640 DeclareImplicitMoveAssignment(ClassDecl);
5641 }
5642
Douglas Gregor4923aa22010-07-02 20:37:36 +00005643 if (!ClassDecl->hasUserDeclaredDestructor()) {
5644 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005645
5646 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005647 // have to declare the destructor immediately. This ensures that, e.g., it
5648 // shows up in the right place in the vtable and that we diagnose problems
5649 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005650 if (ClassDecl->isDynamicClass() ||
5651 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005652 DeclareImplicitDestructor(ClassDecl);
5653 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005654}
5655
Francois Pichet8387e2a2011-04-22 22:18:13 +00005656void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5657 if (!D)
5658 return;
5659
5660 int NumParamList = D->getNumTemplateParameterLists();
5661 for (int i = 0; i < NumParamList; i++) {
5662 TemplateParameterList* Params = D->getTemplateParameterList(i);
5663 for (TemplateParameterList::iterator Param = Params->begin(),
5664 ParamEnd = Params->end();
5665 Param != ParamEnd; ++Param) {
5666 NamedDecl *Named = cast<NamedDecl>(*Param);
5667 if (Named->getDeclName()) {
5668 S->AddDecl(Named);
5669 IdResolver.AddDecl(Named);
5670 }
5671 }
5672 }
5673}
5674
John McCalld226f652010-08-21 09:40:31 +00005675void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005676 if (!D)
5677 return;
5678
5679 TemplateParameterList *Params = 0;
5680 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5681 Params = Template->getTemplateParameters();
5682 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5683 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5684 Params = PartialSpec->getTemplateParameters();
5685 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005686 return;
5687
Douglas Gregor6569d682009-05-27 23:11:45 +00005688 for (TemplateParameterList::iterator Param = Params->begin(),
5689 ParamEnd = Params->end();
5690 Param != ParamEnd; ++Param) {
5691 NamedDecl *Named = cast<NamedDecl>(*Param);
5692 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005693 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005694 IdResolver.AddDecl(Named);
5695 }
5696 }
5697}
5698
John McCalld226f652010-08-21 09:40:31 +00005699void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005700 if (!RecordD) return;
5701 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005702 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005703 PushDeclContext(S, Record);
5704}
5705
John McCalld226f652010-08-21 09:40:31 +00005706void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005707 if (!RecordD) return;
5708 PopDeclContext();
5709}
5710
Douglas Gregor72b505b2008-12-16 21:30:33 +00005711/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5712/// parsing a top-level (non-nested) C++ class, and we are now
5713/// parsing those parts of the given Method declaration that could
5714/// not be parsed earlier (C++ [class.mem]p2), such as default
5715/// arguments. This action should enter the scope of the given
5716/// Method declaration as if we had just parsed the qualified method
5717/// name. However, it should not bring the parameters into scope;
5718/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005719void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005720}
5721
5722/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5723/// C++ method declaration. We're (re-)introducing the given
5724/// function parameter into scope for use in parsing later parts of
5725/// the method declaration. For example, we could see an
5726/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005727void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005728 if (!ParamD)
5729 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005730
John McCalld226f652010-08-21 09:40:31 +00005731 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005732
5733 // If this parameter has an unparsed default argument, clear it out
5734 // to make way for the parsed default argument.
5735 if (Param->hasUnparsedDefaultArg())
5736 Param->setDefaultArg(0);
5737
John McCalld226f652010-08-21 09:40:31 +00005738 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005739 if (Param->getDeclName())
5740 IdResolver.AddDecl(Param);
5741}
5742
5743/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5744/// processing the delayed method declaration for Method. The method
5745/// declaration is now considered finished. There may be a separate
5746/// ActOnStartOfFunctionDef action later (not necessarily
5747/// immediately!) for this method, if it was also defined inside the
5748/// class body.
John McCalld226f652010-08-21 09:40:31 +00005749void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005750 if (!MethodD)
5751 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005752
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005753 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005754
John McCalld226f652010-08-21 09:40:31 +00005755 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005756
5757 // Now that we have our default arguments, check the constructor
5758 // again. It could produce additional diagnostics or affect whether
5759 // the class has implicitly-declared destructors, among other
5760 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005761 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5762 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005763
5764 // Check the default arguments, which we may have added.
5765 if (!Method->isInvalidDecl())
5766 CheckCXXDefaultArguments(Method);
5767}
5768
Douglas Gregor42a552f2008-11-05 20:51:48 +00005769/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005770/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005771/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005772/// emit diagnostics and set the invalid bit to true. In any case, the type
5773/// will be updated to reflect a well-formed type for the constructor and
5774/// returned.
5775QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005776 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005777 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005778
5779 // C++ [class.ctor]p3:
5780 // A constructor shall not be virtual (10.3) or static (9.4). A
5781 // constructor can be invoked for a const, volatile or const
5782 // volatile object. A constructor shall not be declared const,
5783 // volatile, or const volatile (9.3.2).
5784 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005785 if (!D.isInvalidType())
5786 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5787 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5788 << SourceRange(D.getIdentifierLoc());
5789 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005790 }
John McCalld931b082010-08-26 03:08:43 +00005791 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005792 if (!D.isInvalidType())
5793 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5794 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5795 << SourceRange(D.getIdentifierLoc());
5796 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005797 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005798 }
Mike Stump1eb44332009-09-09 15:08:12 +00005799
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005800 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005801 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005802 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005803 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5804 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005805 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005806 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5807 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005808 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005809 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5810 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005811 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005812 }
Mike Stump1eb44332009-09-09 15:08:12 +00005813
Douglas Gregorc938c162011-01-26 05:01:58 +00005814 // C++0x [class.ctor]p4:
5815 // A constructor shall not be declared with a ref-qualifier.
5816 if (FTI.hasRefQualifier()) {
5817 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5818 << FTI.RefQualifierIsLValueRef
5819 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5820 D.setInvalidType();
5821 }
5822
Douglas Gregor42a552f2008-11-05 20:51:48 +00005823 // Rebuild the function type "R" without any type qualifiers (in
5824 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005825 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005826 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005827 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5828 return R;
5829
5830 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5831 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005832 EPI.RefQualifier = RQ_None;
5833
Richard Smith07b0fdc2013-03-18 21:12:30 +00005834 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005835}
5836
Douglas Gregor72b505b2008-12-16 21:30:33 +00005837/// CheckConstructor - Checks a fully-formed constructor for
5838/// well-formedness, issuing any diagnostics required. Returns true if
5839/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005840void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005841 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005842 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5843 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005844 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005845
5846 // C++ [class.copy]p3:
5847 // A declaration of a constructor for a class X is ill-formed if
5848 // its first parameter is of type (optionally cv-qualified) X and
5849 // either there are no other parameters or else all other
5850 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005851 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005852 ((Constructor->getNumParams() == 1) ||
5853 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005854 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5855 Constructor->getTemplateSpecializationKind()
5856 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005857 QualType ParamType = Constructor->getParamDecl(0)->getType();
5858 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5859 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005860 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005861 const char *ConstRef
5862 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5863 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005864 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005865 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005866
5867 // FIXME: Rather that making the constructor invalid, we should endeavor
5868 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005869 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005870 }
5871 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005872}
5873
John McCall15442822010-08-04 01:04:25 +00005874/// CheckDestructor - Checks a fully-formed destructor definition for
5875/// well-formedness, issuing any diagnostics required. Returns true
5876/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005877bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005878 CXXRecordDecl *RD = Destructor->getParent();
5879
5880 if (Destructor->isVirtual()) {
5881 SourceLocation Loc;
5882
5883 if (!Destructor->isImplicit())
5884 Loc = Destructor->getLocation();
5885 else
5886 Loc = RD->getLocation();
5887
5888 // If we have a virtual destructor, look up the deallocation function
5889 FunctionDecl *OperatorDelete = 0;
5890 DeclarationName Name =
5891 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005892 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005893 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005894
Eli Friedman5f2987c2012-02-02 03:46:19 +00005895 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005896
5897 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005898 }
Anders Carlsson37909802009-11-30 21:24:50 +00005899
5900 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005901}
5902
Mike Stump1eb44332009-09-09 15:08:12 +00005903static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005904FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5905 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5906 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005907 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005908}
5909
Douglas Gregor42a552f2008-11-05 20:51:48 +00005910/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5911/// the well-formednes of the destructor declarator @p D with type @p
5912/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005913/// emit diagnostics and set the declarator to invalid. Even if this happens,
5914/// will be updated to reflect a well-formed type for the destructor and
5915/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005916QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005917 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005918 // C++ [class.dtor]p1:
5919 // [...] A typedef-name that names a class is a class-name
5920 // (7.1.3); however, a typedef-name that names a class shall not
5921 // be used as the identifier in the declarator for a destructor
5922 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005923 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005924 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005925 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005926 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005927 else if (const TemplateSpecializationType *TST =
5928 DeclaratorType->getAs<TemplateSpecializationType>())
5929 if (TST->isTypeAlias())
5930 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5931 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005932
5933 // C++ [class.dtor]p2:
5934 // A destructor is used to destroy objects of its class type. A
5935 // destructor takes no parameters, and no return type can be
5936 // specified for it (not even void). The address of a destructor
5937 // shall not be taken. A destructor shall not be static. A
5938 // destructor can be invoked for a const, volatile or const
5939 // volatile object. A destructor shall not be declared const,
5940 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005941 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005942 if (!D.isInvalidType())
5943 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5944 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005945 << SourceRange(D.getIdentifierLoc())
5946 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5947
John McCalld931b082010-08-26 03:08:43 +00005948 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005949 }
Chris Lattner65401802009-04-25 08:28:21 +00005950 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005951 // Destructors don't have return types, but the parser will
5952 // happily parse something like:
5953 //
5954 // class X {
5955 // float ~X();
5956 // };
5957 //
5958 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005959 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5960 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5961 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005962 }
Mike Stump1eb44332009-09-09 15:08:12 +00005963
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005964 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005965 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005966 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005967 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5968 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005969 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005970 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5971 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005972 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005973 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5974 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005975 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005976 }
5977
Douglas Gregorc938c162011-01-26 05:01:58 +00005978 // C++0x [class.dtor]p2:
5979 // A destructor shall not be declared with a ref-qualifier.
5980 if (FTI.hasRefQualifier()) {
5981 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5982 << FTI.RefQualifierIsLValueRef
5983 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5984 D.setInvalidType();
5985 }
5986
Douglas Gregor42a552f2008-11-05 20:51:48 +00005987 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005988 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005989 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5990
5991 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005992 FTI.freeArgs();
5993 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005994 }
5995
Mike Stump1eb44332009-09-09 15:08:12 +00005996 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005997 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005998 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005999 D.setInvalidType();
6000 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006001
6002 // Rebuild the function type "R" without any type qualifiers or
6003 // parameters (in case any of the errors above fired) and with
6004 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006005 // types.
John McCalle23cf432010-12-14 08:05:40 +00006006 if (!D.isInvalidType())
6007 return R;
6008
Douglas Gregord92ec472010-07-01 05:10:53 +00006009 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006010 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6011 EPI.Variadic = false;
6012 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006013 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006014 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006015}
6016
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006017/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6018/// well-formednes of the conversion function declarator @p D with
6019/// type @p R. If there are any errors in the declarator, this routine
6020/// will emit diagnostics and return true. Otherwise, it will return
6021/// false. Either way, the type @p R will be updated to reflect a
6022/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006023void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006024 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006025 // C++ [class.conv.fct]p1:
6026 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006027 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006028 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006029 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006030 if (!D.isInvalidType())
6031 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6032 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6033 << SourceRange(D.getIdentifierLoc());
6034 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006035 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006036 }
John McCalla3f81372010-04-13 00:04:31 +00006037
6038 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6039
Chris Lattner6e475012009-04-25 08:35:12 +00006040 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006041 // Conversion functions don't have return types, but the parser will
6042 // happily parse something like:
6043 //
6044 // class X {
6045 // float operator bool();
6046 // };
6047 //
6048 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006049 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6050 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6051 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006052 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006053 }
6054
John McCalla3f81372010-04-13 00:04:31 +00006055 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6056
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006057 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006058 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006059 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6060
6061 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006062 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006063 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006064 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006065 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006066 D.setInvalidType();
6067 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006068
John McCalla3f81372010-04-13 00:04:31 +00006069 // Diagnose "&operator bool()" and other such nonsense. This
6070 // is actually a gcc extension which we don't support.
6071 if (Proto->getResultType() != ConvType) {
6072 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6073 << Proto->getResultType();
6074 D.setInvalidType();
6075 ConvType = Proto->getResultType();
6076 }
6077
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006078 // C++ [class.conv.fct]p4:
6079 // The conversion-type-id shall not represent a function type nor
6080 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006081 if (ConvType->isArrayType()) {
6082 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6083 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006084 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006085 } else if (ConvType->isFunctionType()) {
6086 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6087 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006088 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006089 }
6090
6091 // Rebuild the function type "R" without any parameters (in case any
6092 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006093 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006094 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006095 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006096
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006097 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006098 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006099 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006100 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006101 diag::warn_cxx98_compat_explicit_conversion_functions :
6102 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006103 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006104}
6105
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006106/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6107/// the declaration of the given C++ conversion function. This routine
6108/// is responsible for recording the conversion function in the C++
6109/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006110Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006111 assert(Conversion && "Expected to receive a conversion function declaration");
6112
Douglas Gregor9d350972008-12-12 08:25:50 +00006113 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006114
6115 // Make sure we aren't redeclaring the conversion function.
6116 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006117
6118 // C++ [class.conv.fct]p1:
6119 // [...] A conversion function is never used to convert a
6120 // (possibly cv-qualified) object to the (possibly cv-qualified)
6121 // same object type (or a reference to it), to a (possibly
6122 // cv-qualified) base class of that type (or a reference to it),
6123 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006124 // FIXME: Suppress this warning if the conversion function ends up being a
6125 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006126 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006127 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006128 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006129 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006130 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6131 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006132 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006133 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006134 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6135 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006136 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006137 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006138 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006139 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006140 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006141 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006142 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006143 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006144 }
6145
Douglas Gregore80622f2010-09-29 04:25:11 +00006146 if (FunctionTemplateDecl *ConversionTemplate
6147 = Conversion->getDescribedFunctionTemplate())
6148 return ConversionTemplate;
6149
John McCalld226f652010-08-21 09:40:31 +00006150 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006151}
6152
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006153//===----------------------------------------------------------------------===//
6154// Namespace Handling
6155//===----------------------------------------------------------------------===//
6156
Richard Smithd1a55a62012-10-04 22:13:39 +00006157/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6158/// reopened.
6159static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6160 SourceLocation Loc,
6161 IdentifierInfo *II, bool *IsInline,
6162 NamespaceDecl *PrevNS) {
6163 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006164
Richard Smithc969e6a2012-10-05 01:46:25 +00006165 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6166 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6167 // inline namespaces, with the intention of bringing names into namespace std.
6168 //
6169 // We support this just well enough to get that case working; this is not
6170 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006171 if (*IsInline && II && II->getName().startswith("__atomic") &&
6172 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006173 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006174 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6175 NS = NS->getPreviousDecl())
6176 NS->setInline(*IsInline);
6177 // Patch up the lookup table for the containing namespace. This isn't really
6178 // correct, but it's good enough for this particular case.
6179 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6180 E = PrevNS->decls_end(); I != E; ++I)
6181 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6182 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6183 return;
6184 }
6185
6186 if (PrevNS->isInline())
6187 // The user probably just forgot the 'inline', so suggest that it
6188 // be added back.
6189 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6190 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6191 else
6192 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6193 << IsInline;
6194
6195 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6196 *IsInline = PrevNS->isInline();
6197}
John McCallea318642010-08-26 09:15:37 +00006198
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006199/// ActOnStartNamespaceDef - This is called at the start of a namespace
6200/// definition.
John McCalld226f652010-08-21 09:40:31 +00006201Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006202 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006203 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006204 SourceLocation IdentLoc,
6205 IdentifierInfo *II,
6206 SourceLocation LBrace,
6207 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006208 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6209 // For anonymous namespace, take the location of the left brace.
6210 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006211 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006212 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006213 bool IsStd = false;
6214 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006215 Scope *DeclRegionScope = NamespcScope->getParent();
6216
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006217 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006218 if (II) {
6219 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006220 // The identifier in an original-namespace-definition shall not
6221 // have been previously defined in the declarative region in
6222 // which the original-namespace-definition appears. The
6223 // identifier in an original-namespace-definition is the name of
6224 // the namespace. Subsequently in that declarative region, it is
6225 // treated as an original-namespace-name.
6226 //
6227 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006228 // look through using directives, just look for any ordinary names.
6229
6230 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006231 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6232 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006233 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006234 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6235 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6236 ++I) {
6237 if ((*I)->getIdentifierNamespace() & IDNS) {
6238 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006239 break;
6240 }
6241 }
6242
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006243 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6244
6245 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006246 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006247 if (IsInline != PrevNS->isInline())
6248 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6249 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006250 } else if (PrevDecl) {
6251 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006252 Diag(Loc, diag::err_redefinition_different_kind)
6253 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006254 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006255 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006256 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006257 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006258 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006259 // This is the first "real" definition of the namespace "std", so update
6260 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006261 PrevNS = getStdNamespace();
6262 IsStd = true;
6263 AddToKnown = !IsInline;
6264 } else {
6265 // We've seen this namespace for the first time.
6266 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006267 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006268 } else {
John McCall9aeed322009-10-01 00:25:31 +00006269 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006270
6271 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006272 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006273 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006274 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006275 } else {
6276 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006277 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006278 }
6279
Richard Smithd1a55a62012-10-04 22:13:39 +00006280 if (PrevNS && IsInline != PrevNS->isInline())
6281 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6282 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006283 }
6284
6285 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6286 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006287 if (IsInvalid)
6288 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006289
6290 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006291
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006292 // FIXME: Should we be merging attributes?
6293 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006294 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006295
6296 if (IsStd)
6297 StdNamespace = Namespc;
6298 if (AddToKnown)
6299 KnownNamespaces[Namespc] = false;
6300
6301 if (II) {
6302 PushOnScopeChains(Namespc, DeclRegionScope);
6303 } else {
6304 // Link the anonymous namespace into its parent.
6305 DeclContext *Parent = CurContext->getRedeclContext();
6306 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6307 TU->setAnonymousNamespace(Namespc);
6308 } else {
6309 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006310 }
John McCall9aeed322009-10-01 00:25:31 +00006311
Douglas Gregora4181472010-03-24 00:46:35 +00006312 CurContext->addDecl(Namespc);
6313
John McCall9aeed322009-10-01 00:25:31 +00006314 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6315 // behaves as if it were replaced by
6316 // namespace unique { /* empty body */ }
6317 // using namespace unique;
6318 // namespace unique { namespace-body }
6319 // where all occurrences of 'unique' in a translation unit are
6320 // replaced by the same identifier and this identifier differs
6321 // from all other identifiers in the entire program.
6322
6323 // We just create the namespace with an empty name and then add an
6324 // implicit using declaration, just like the standard suggests.
6325 //
6326 // CodeGen enforces the "universally unique" aspect by giving all
6327 // declarations semantically contained within an anonymous
6328 // namespace internal linkage.
6329
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006330 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006331 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006332 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006333 /* 'using' */ LBrace,
6334 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006335 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006336 /* identifier */ SourceLocation(),
6337 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006338 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006339 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006340 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006341 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006342 }
6343
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006344 ActOnDocumentableDecl(Namespc);
6345
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006346 // Although we could have an invalid decl (i.e. the namespace name is a
6347 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006348 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6349 // for the namespace has the declarations that showed up in that particular
6350 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006351 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006352 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006353}
6354
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006355/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6356/// is a namespace alias, returns the namespace it points to.
6357static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6358 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6359 return AD->getNamespace();
6360 return dyn_cast_or_null<NamespaceDecl>(D);
6361}
6362
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006363/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6364/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006365void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006366 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6367 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006368 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006369 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006370 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006371 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006372}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006373
John McCall384aff82010-08-25 07:42:41 +00006374CXXRecordDecl *Sema::getStdBadAlloc() const {
6375 return cast_or_null<CXXRecordDecl>(
6376 StdBadAlloc.get(Context.getExternalSource()));
6377}
6378
6379NamespaceDecl *Sema::getStdNamespace() const {
6380 return cast_or_null<NamespaceDecl>(
6381 StdNamespace.get(Context.getExternalSource()));
6382}
6383
Douglas Gregor66992202010-06-29 17:53:46 +00006384/// \brief Retrieve the special "std" namespace, which may require us to
6385/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006386NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006387 if (!StdNamespace) {
6388 // The "std" namespace has not yet been defined, so build one implicitly.
6389 StdNamespace = NamespaceDecl::Create(Context,
6390 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006391 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006392 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006393 &PP.getIdentifierTable().get("std"),
6394 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006395 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006396 }
6397
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006398 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006399}
6400
Sebastian Redl395e04d2012-01-17 22:49:33 +00006401bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006402 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006403 "Looking for std::initializer_list outside of C++.");
6404
6405 // We're looking for implicit instantiations of
6406 // template <typename E> class std::initializer_list.
6407
6408 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6409 return false;
6410
Sebastian Redl84760e32012-01-17 22:49:58 +00006411 ClassTemplateDecl *Template = 0;
6412 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006413
Sebastian Redl84760e32012-01-17 22:49:58 +00006414 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006415
Sebastian Redl84760e32012-01-17 22:49:58 +00006416 ClassTemplateSpecializationDecl *Specialization =
6417 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6418 if (!Specialization)
6419 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006420
Sebastian Redl84760e32012-01-17 22:49:58 +00006421 Template = Specialization->getSpecializedTemplate();
6422 Arguments = Specialization->getTemplateArgs().data();
6423 } else if (const TemplateSpecializationType *TST =
6424 Ty->getAs<TemplateSpecializationType>()) {
6425 Template = dyn_cast_or_null<ClassTemplateDecl>(
6426 TST->getTemplateName().getAsTemplateDecl());
6427 Arguments = TST->getArgs();
6428 }
6429 if (!Template)
6430 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006431
6432 if (!StdInitializerList) {
6433 // Haven't recognized std::initializer_list yet, maybe this is it.
6434 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6435 if (TemplateClass->getIdentifier() !=
6436 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006437 !getStdNamespace()->InEnclosingNamespaceSetOf(
6438 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006439 return false;
6440 // This is a template called std::initializer_list, but is it the right
6441 // template?
6442 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006443 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006444 return false;
6445 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6446 return false;
6447
6448 // It's the right template.
6449 StdInitializerList = Template;
6450 }
6451
6452 if (Template != StdInitializerList)
6453 return false;
6454
6455 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006456 if (Element)
6457 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006458 return true;
6459}
6460
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006461static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6462 NamespaceDecl *Std = S.getStdNamespace();
6463 if (!Std) {
6464 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6465 return 0;
6466 }
6467
6468 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6469 Loc, Sema::LookupOrdinaryName);
6470 if (!S.LookupQualifiedName(Result, Std)) {
6471 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6472 return 0;
6473 }
6474 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6475 if (!Template) {
6476 Result.suppressDiagnostics();
6477 // We found something weird. Complain about the first thing we found.
6478 NamedDecl *Found = *Result.begin();
6479 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6480 return 0;
6481 }
6482
6483 // We found some template called std::initializer_list. Now verify that it's
6484 // correct.
6485 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006486 if (Params->getMinRequiredArguments() != 1 ||
6487 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006488 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6489 return 0;
6490 }
6491
6492 return Template;
6493}
6494
6495QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6496 if (!StdInitializerList) {
6497 StdInitializerList = LookupStdInitializerList(*this, Loc);
6498 if (!StdInitializerList)
6499 return QualType();
6500 }
6501
6502 TemplateArgumentListInfo Args(Loc, Loc);
6503 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6504 Context.getTrivialTypeSourceInfo(Element,
6505 Loc)));
6506 return Context.getCanonicalType(
6507 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6508}
6509
Sebastian Redl98d36062012-01-17 22:50:14 +00006510bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6511 // C++ [dcl.init.list]p2:
6512 // A constructor is an initializer-list constructor if its first parameter
6513 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6514 // std::initializer_list<E> for some type E, and either there are no other
6515 // parameters or else all other parameters have default arguments.
6516 if (Ctor->getNumParams() < 1 ||
6517 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6518 return false;
6519
6520 QualType ArgType = Ctor->getParamDecl(0)->getType();
6521 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6522 ArgType = RT->getPointeeType().getUnqualifiedType();
6523
6524 return isStdInitializerList(ArgType, 0);
6525}
6526
Douglas Gregor9172aa62011-03-26 22:25:30 +00006527/// \brief Determine whether a using statement is in a context where it will be
6528/// apply in all contexts.
6529static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6530 switch (CurContext->getDeclKind()) {
6531 case Decl::TranslationUnit:
6532 return true;
6533 case Decl::LinkageSpec:
6534 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6535 default:
6536 return false;
6537 }
6538}
6539
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006540namespace {
6541
6542// Callback to only accept typo corrections that are namespaces.
6543class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6544 public:
6545 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6546 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6547 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6548 }
6549 return false;
6550 }
6551};
6552
6553}
6554
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006555static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6556 CXXScopeSpec &SS,
6557 SourceLocation IdentLoc,
6558 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006559 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006560 R.clear();
6561 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006562 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006563 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006564 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6565 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006566 if (DeclContext *DC = S.computeDeclContext(SS, false))
6567 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6568 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006569 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6570 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006571 else
6572 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6573 << Ident << CorrectedQuotedStr
6574 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006575
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006576 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6577 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006578
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006579 R.addDecl(Corrected.getCorrectionDecl());
6580 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006581 }
6582 return false;
6583}
6584
John McCalld226f652010-08-21 09:40:31 +00006585Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006586 SourceLocation UsingLoc,
6587 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006588 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006589 SourceLocation IdentLoc,
6590 IdentifierInfo *NamespcName,
6591 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006592 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6593 assert(NamespcName && "Invalid NamespcName.");
6594 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006595
6596 // This can only happen along a recovery path.
6597 while (S->getFlags() & Scope::TemplateParamScope)
6598 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006599 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006600
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006601 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006602 NestedNameSpecifier *Qualifier = 0;
6603 if (SS.isSet())
6604 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6605
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006606 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006607 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6608 LookupParsedName(R, S, &SS);
6609 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006610 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006611
Douglas Gregor66992202010-06-29 17:53:46 +00006612 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006613 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006614 // Allow "using namespace std;" or "using namespace ::std;" even if
6615 // "std" hasn't been defined yet, for GCC compatibility.
6616 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6617 NamespcName->isStr("std")) {
6618 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006619 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006620 R.resolveKind();
6621 }
6622 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006623 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006624 }
6625
John McCallf36e02d2009-10-09 21:13:30 +00006626 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006627 NamedDecl *Named = R.getFoundDecl();
6628 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6629 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006630 // C++ [namespace.udir]p1:
6631 // A using-directive specifies that the names in the nominated
6632 // namespace can be used in the scope in which the
6633 // using-directive appears after the using-directive. During
6634 // unqualified name lookup (3.4.1), the names appear as if they
6635 // were declared in the nearest enclosing namespace which
6636 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006637 // namespace. [Note: in this context, "contains" means "contains
6638 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006639
6640 // Find enclosing context containing both using-directive and
6641 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006642 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006643 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6644 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6645 CommonAncestor = CommonAncestor->getParent();
6646
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006647 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006648 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006649 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006650
Douglas Gregor9172aa62011-03-26 22:25:30 +00006651 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006652 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006653 Diag(IdentLoc, diag::warn_using_directive_in_header);
6654 }
6655
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006656 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006657 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006658 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006659 }
6660
Richard Smith6b3d3e52013-02-20 19:22:51 +00006661 if (UDir)
6662 ProcessDeclAttributeList(S, UDir, AttrList);
6663
John McCalld226f652010-08-21 09:40:31 +00006664 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006665}
6666
6667void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006668 // If the scope has an associated entity and the using directive is at
6669 // namespace or translation unit scope, add the UsingDirectiveDecl into
6670 // its lookup structure so qualified name lookup can find it.
6671 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6672 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006673 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006674 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006675 // Otherwise, it is at block sope. The using-directives will affect lookup
6676 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006677 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006678}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006679
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006680
John McCalld226f652010-08-21 09:40:31 +00006681Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006682 AccessSpecifier AS,
6683 bool HasUsingKeyword,
6684 SourceLocation UsingLoc,
6685 CXXScopeSpec &SS,
6686 UnqualifiedId &Name,
6687 AttributeList *AttrList,
6688 bool IsTypeName,
6689 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006690 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006691
Douglas Gregor12c118a2009-11-04 16:30:06 +00006692 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006693 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006694 case UnqualifiedId::IK_Identifier:
6695 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006696 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006697 case UnqualifiedId::IK_ConversionFunctionId:
6698 break;
6699
6700 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006701 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006702 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006703 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006704 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006705 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006706 diag::err_using_decl_constructor)
6707 << SS.getRange();
6708
Richard Smith80ad52f2013-01-02 11:42:31 +00006709 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006710
John McCalld226f652010-08-21 09:40:31 +00006711 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006712
6713 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006714 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006715 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006716 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006717
6718 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006719 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006720 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006721 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006722 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006723
6724 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6725 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006726 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006727 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006728
Richard Smith07b0fdc2013-03-18 21:12:30 +00006729 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006730 // TODO: store that the declaration was written without 'using' and
6731 // talk about access decls instead of using decls in the
6732 // diagnostics.
6733 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006734 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006735
6736 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006737 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006738 }
6739
Douglas Gregor56c04582010-12-16 00:46:58 +00006740 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6741 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6742 return 0;
6743
John McCall9488ea12009-11-17 05:59:44 +00006744 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006745 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006746 /* IsInstantiation */ false,
6747 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006748 if (UD)
6749 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006750
John McCalld226f652010-08-21 09:40:31 +00006751 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006752}
6753
Douglas Gregor09acc982010-07-07 23:08:52 +00006754/// \brief Determine whether a using declaration considers the given
6755/// declarations as "equivalent", e.g., if they are redeclarations of
6756/// the same entity or are both typedefs of the same type.
6757static bool
6758IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6759 bool &SuppressRedeclaration) {
6760 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6761 SuppressRedeclaration = false;
6762 return true;
6763 }
6764
Richard Smith162e1c12011-04-15 14:24:37 +00006765 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6766 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006767 SuppressRedeclaration = true;
6768 return Context.hasSameType(TD1->getUnderlyingType(),
6769 TD2->getUnderlyingType());
6770 }
6771
6772 return false;
6773}
6774
6775
John McCall9f54ad42009-12-10 09:41:52 +00006776/// Determines whether to create a using shadow decl for a particular
6777/// decl, given the set of decls existing prior to this using lookup.
6778bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6779 const LookupResult &Previous) {
6780 // Diagnose finding a decl which is not from a base class of the
6781 // current class. We do this now because there are cases where this
6782 // function will silently decide not to build a shadow decl, which
6783 // will pre-empt further diagnostics.
6784 //
6785 // We don't need to do this in C++0x because we do the check once on
6786 // the qualifier.
6787 //
6788 // FIXME: diagnose the following if we care enough:
6789 // struct A { int foo; };
6790 // struct B : A { using A::foo; };
6791 // template <class T> struct C : A {};
6792 // template <class T> struct D : C<T> { using B::foo; } // <---
6793 // This is invalid (during instantiation) in C++03 because B::foo
6794 // resolves to the using decl in B, which is not a base class of D<T>.
6795 // We can't diagnose it immediately because C<T> is an unknown
6796 // specialization. The UsingShadowDecl in D<T> then points directly
6797 // to A::foo, which will look well-formed when we instantiate.
6798 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006799 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006800 DeclContext *OrigDC = Orig->getDeclContext();
6801
6802 // Handle enums and anonymous structs.
6803 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6804 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6805 while (OrigRec->isAnonymousStructOrUnion())
6806 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6807
6808 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6809 if (OrigDC == CurContext) {
6810 Diag(Using->getLocation(),
6811 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006812 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006813 Diag(Orig->getLocation(), diag::note_using_decl_target);
6814 return true;
6815 }
6816
Douglas Gregordc355712011-02-25 00:36:19 +00006817 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006818 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006819 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006820 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006821 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006822 Diag(Orig->getLocation(), diag::note_using_decl_target);
6823 return true;
6824 }
6825 }
6826
6827 if (Previous.empty()) return false;
6828
6829 NamedDecl *Target = Orig;
6830 if (isa<UsingShadowDecl>(Target))
6831 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6832
John McCalld7533ec2009-12-11 02:33:26 +00006833 // If the target happens to be one of the previous declarations, we
6834 // don't have a conflict.
6835 //
6836 // FIXME: but we might be increasing its access, in which case we
6837 // should redeclare it.
6838 NamedDecl *NonTag = 0, *Tag = 0;
6839 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6840 I != E; ++I) {
6841 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006842 bool Result;
6843 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6844 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006845
6846 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6847 }
6848
John McCall9f54ad42009-12-10 09:41:52 +00006849 if (Target->isFunctionOrFunctionTemplate()) {
6850 FunctionDecl *FD;
6851 if (isa<FunctionTemplateDecl>(Target))
6852 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6853 else
6854 FD = cast<FunctionDecl>(Target);
6855
6856 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006857 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006858 case Ovl_Overload:
6859 return false;
6860
6861 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006862 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006863 break;
6864
6865 // We found a decl with the exact signature.
6866 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006867 // If we're in a record, we want to hide the target, so we
6868 // return true (without a diagnostic) to tell the caller not to
6869 // build a shadow decl.
6870 if (CurContext->isRecord())
6871 return true;
6872
6873 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006874 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006875 break;
6876 }
6877
6878 Diag(Target->getLocation(), diag::note_using_decl_target);
6879 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6880 return true;
6881 }
6882
6883 // Target is not a function.
6884
John McCall9f54ad42009-12-10 09:41:52 +00006885 if (isa<TagDecl>(Target)) {
6886 // No conflict between a tag and a non-tag.
6887 if (!Tag) return false;
6888
John McCall41ce66f2009-12-10 19:51:03 +00006889 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006890 Diag(Target->getLocation(), diag::note_using_decl_target);
6891 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6892 return true;
6893 }
6894
6895 // No conflict between a tag and a non-tag.
6896 if (!NonTag) return false;
6897
John McCall41ce66f2009-12-10 19:51:03 +00006898 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006899 Diag(Target->getLocation(), diag::note_using_decl_target);
6900 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6901 return true;
6902}
6903
John McCall9488ea12009-11-17 05:59:44 +00006904/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006905UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006906 UsingDecl *UD,
6907 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006908
6909 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006910 NamedDecl *Target = Orig;
6911 if (isa<UsingShadowDecl>(Target)) {
6912 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6913 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006914 }
6915
6916 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006917 = UsingShadowDecl::Create(Context, CurContext,
6918 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006919 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006920
6921 Shadow->setAccess(UD->getAccess());
6922 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6923 Shadow->setInvalidDecl();
6924
John McCall9488ea12009-11-17 05:59:44 +00006925 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006926 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006927 else
John McCall604e7f12009-12-08 07:46:18 +00006928 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006929
John McCall604e7f12009-12-08 07:46:18 +00006930
John McCall9f54ad42009-12-10 09:41:52 +00006931 return Shadow;
6932}
John McCall604e7f12009-12-08 07:46:18 +00006933
John McCall9f54ad42009-12-10 09:41:52 +00006934/// Hides a using shadow declaration. This is required by the current
6935/// using-decl implementation when a resolvable using declaration in a
6936/// class is followed by a declaration which would hide or override
6937/// one or more of the using decl's targets; for example:
6938///
6939/// struct Base { void foo(int); };
6940/// struct Derived : Base {
6941/// using Base::foo;
6942/// void foo(int);
6943/// };
6944///
6945/// The governing language is C++03 [namespace.udecl]p12:
6946///
6947/// When a using-declaration brings names from a base class into a
6948/// derived class scope, member functions in the derived class
6949/// override and/or hide member functions with the same name and
6950/// parameter types in a base class (rather than conflicting).
6951///
6952/// There are two ways to implement this:
6953/// (1) optimistically create shadow decls when they're not hidden
6954/// by existing declarations, or
6955/// (2) don't create any shadow decls (or at least don't make them
6956/// visible) until we've fully parsed/instantiated the class.
6957/// The problem with (1) is that we might have to retroactively remove
6958/// a shadow decl, which requires several O(n) operations because the
6959/// decl structures are (very reasonably) not designed for removal.
6960/// (2) avoids this but is very fiddly and phase-dependent.
6961void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006962 if (Shadow->getDeclName().getNameKind() ==
6963 DeclarationName::CXXConversionFunctionName)
6964 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6965
John McCall9f54ad42009-12-10 09:41:52 +00006966 // Remove it from the DeclContext...
6967 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006968
John McCall9f54ad42009-12-10 09:41:52 +00006969 // ...and the scope, if applicable...
6970 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006971 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006972 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006973 }
6974
John McCall9f54ad42009-12-10 09:41:52 +00006975 // ...and the using decl.
6976 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6977
6978 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006979 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006980}
6981
John McCall7ba107a2009-11-18 02:36:19 +00006982/// Builds a using declaration.
6983///
6984/// \param IsInstantiation - Whether this call arises from an
6985/// instantiation of an unresolved using declaration. We treat
6986/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006987NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6988 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006989 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006990 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006991 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006992 bool IsInstantiation,
6993 bool IsTypeName,
6994 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006995 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006996 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006997 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006998
Anders Carlsson550b14b2009-08-28 05:49:21 +00006999 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007000
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007001 if (SS.isEmpty()) {
7002 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007003 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007004 }
Mike Stump1eb44332009-09-09 15:08:12 +00007005
John McCall9f54ad42009-12-10 09:41:52 +00007006 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007007 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007008 ForRedeclaration);
7009 Previous.setHideTags(false);
7010 if (S) {
7011 LookupName(Previous, S);
7012
7013 // It is really dumb that we have to do this.
7014 LookupResult::Filter F = Previous.makeFilter();
7015 while (F.hasNext()) {
7016 NamedDecl *D = F.next();
7017 if (!isDeclInScope(D, CurContext, S))
7018 F.erase();
7019 }
7020 F.done();
7021 } else {
7022 assert(IsInstantiation && "no scope in non-instantiation");
7023 assert(CurContext->isRecord() && "scope not record in instantiation");
7024 LookupQualifiedName(Previous, CurContext);
7025 }
7026
John McCall9f54ad42009-12-10 09:41:52 +00007027 // Check for invalid redeclarations.
7028 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
7029 return 0;
7030
7031 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007032 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7033 return 0;
7034
John McCallaf8e6ed2009-11-12 03:15:40 +00007035 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007036 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007037 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007038 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00007039 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00007040 // FIXME: not all declaration name kinds are legal here
7041 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7042 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007043 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007044 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007045 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007046 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7047 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007048 }
John McCalled976492009-12-04 22:46:56 +00007049 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007050 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7051 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007052 }
John McCalled976492009-12-04 22:46:56 +00007053 D->setAccess(AS);
7054 CurContext->addDecl(D);
7055
7056 if (!LookupContext) return D;
7057 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007058
John McCall77bb1aa2010-05-01 00:40:08 +00007059 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007060 UD->setInvalidDecl();
7061 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007062 }
7063
Richard Smithc5a89a12012-04-02 01:30:27 +00007064 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007065 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007066 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007067 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007068 return UD;
7069 }
7070
7071 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007072
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007073 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007074
John McCall604e7f12009-12-08 07:46:18 +00007075 // Unlike most lookups, we don't always want to hide tag
7076 // declarations: tag names are visible through the using declaration
7077 // even if hidden by ordinary names, *except* in a dependent context
7078 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007079 if (!IsInstantiation)
7080 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007081
John McCallb9abd8722012-04-07 03:04:20 +00007082 // For the purposes of this lookup, we have a base object type
7083 // equal to that of the current context.
7084 if (CurContext->isRecord()) {
7085 R.setBaseObjectType(
7086 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7087 }
7088
John McCalla24dc2e2009-11-17 02:14:36 +00007089 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007090
John McCallf36e02d2009-10-09 21:13:30 +00007091 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00007092 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007093 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007094 UD->setInvalidDecl();
7095 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007096 }
7097
John McCalled976492009-12-04 22:46:56 +00007098 if (R.isAmbiguous()) {
7099 UD->setInvalidDecl();
7100 return UD;
7101 }
Mike Stump1eb44332009-09-09 15:08:12 +00007102
John McCall7ba107a2009-11-18 02:36:19 +00007103 if (IsTypeName) {
7104 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007105 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007106 Diag(IdentLoc, diag::err_using_typename_non_type);
7107 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7108 Diag((*I)->getUnderlyingDecl()->getLocation(),
7109 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007110 UD->setInvalidDecl();
7111 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007112 }
7113 } else {
7114 // If we asked for a non-typename and we got a type, error out,
7115 // but only if this is an instantiation of an unresolved using
7116 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007117 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007118 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7119 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007120 UD->setInvalidDecl();
7121 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007122 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007123 }
7124
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007125 // C++0x N2914 [namespace.udecl]p6:
7126 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007127 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007128 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7129 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007130 UD->setInvalidDecl();
7131 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007132 }
Mike Stump1eb44332009-09-09 15:08:12 +00007133
John McCall9f54ad42009-12-10 09:41:52 +00007134 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7135 if (!CheckUsingShadowDecl(UD, *I, Previous))
7136 BuildUsingShadowDecl(S, UD, *I);
7137 }
John McCall9488ea12009-11-17 05:59:44 +00007138
7139 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007140}
7141
Sebastian Redlf677ea32011-02-05 19:23:19 +00007142/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007143bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7144 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007145
Douglas Gregordc355712011-02-25 00:36:19 +00007146 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007147 assert(SourceType &&
7148 "Using decl naming constructor doesn't have type in scope spec.");
7149 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7150
7151 // Check whether the named type is a direct base class.
7152 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7153 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7154 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7155 BaseIt != BaseE; ++BaseIt) {
7156 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7157 if (CanonicalSourceType == BaseType)
7158 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007159 if (BaseIt->getType()->isDependentType())
7160 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007161 }
7162
7163 if (BaseIt == BaseE) {
7164 // Did not find SourceType in the bases.
7165 Diag(UD->getUsingLocation(),
7166 diag::err_using_decl_constructor_not_in_direct_base)
7167 << UD->getNameInfo().getSourceRange()
7168 << QualType(SourceType, 0) << TargetClass;
7169 return true;
7170 }
7171
Richard Smithc5a89a12012-04-02 01:30:27 +00007172 if (!CurContext->isDependentContext())
7173 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007174
7175 return false;
7176}
7177
John McCall9f54ad42009-12-10 09:41:52 +00007178/// Checks that the given using declaration is not an invalid
7179/// redeclaration. Note that this is checking only for the using decl
7180/// itself, not for any ill-formedness among the UsingShadowDecls.
7181bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7182 bool isTypeName,
7183 const CXXScopeSpec &SS,
7184 SourceLocation NameLoc,
7185 const LookupResult &Prev) {
7186 // C++03 [namespace.udecl]p8:
7187 // C++0x [namespace.udecl]p10:
7188 // A using-declaration is a declaration and can therefore be used
7189 // repeatedly where (and only where) multiple declarations are
7190 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007191 //
John McCall8a726212010-11-29 18:01:58 +00007192 // That's in non-member contexts.
7193 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007194 return false;
7195
7196 NestedNameSpecifier *Qual
7197 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7198
7199 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7200 NamedDecl *D = *I;
7201
7202 bool DTypename;
7203 NestedNameSpecifier *DQual;
7204 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7205 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007206 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007207 } else if (UnresolvedUsingValueDecl *UD
7208 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7209 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007210 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007211 } else if (UnresolvedUsingTypenameDecl *UD
7212 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7213 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007214 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007215 } else continue;
7216
7217 // using decls differ if one says 'typename' and the other doesn't.
7218 // FIXME: non-dependent using decls?
7219 if (isTypeName != DTypename) continue;
7220
7221 // using decls differ if they name different scopes (but note that
7222 // template instantiation can cause this check to trigger when it
7223 // didn't before instantiation).
7224 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7225 Context.getCanonicalNestedNameSpecifier(DQual))
7226 continue;
7227
7228 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007229 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007230 return true;
7231 }
7232
7233 return false;
7234}
7235
John McCall604e7f12009-12-08 07:46:18 +00007236
John McCalled976492009-12-04 22:46:56 +00007237/// Checks that the given nested-name qualifier used in a using decl
7238/// in the current context is appropriately related to the current
7239/// scope. If an error is found, diagnoses it and returns true.
7240bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7241 const CXXScopeSpec &SS,
7242 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007243 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007244
John McCall604e7f12009-12-08 07:46:18 +00007245 if (!CurContext->isRecord()) {
7246 // C++03 [namespace.udecl]p3:
7247 // C++0x [namespace.udecl]p8:
7248 // A using-declaration for a class member shall be a member-declaration.
7249
7250 // If we weren't able to compute a valid scope, it must be a
7251 // dependent class scope.
7252 if (!NamedContext || NamedContext->isRecord()) {
7253 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7254 << SS.getRange();
7255 return true;
7256 }
7257
7258 // Otherwise, everything is known to be fine.
7259 return false;
7260 }
7261
7262 // The current scope is a record.
7263
7264 // If the named context is dependent, we can't decide much.
7265 if (!NamedContext) {
7266 // FIXME: in C++0x, we can diagnose if we can prove that the
7267 // nested-name-specifier does not refer to a base class, which is
7268 // still possible in some cases.
7269
7270 // Otherwise we have to conservatively report that things might be
7271 // okay.
7272 return false;
7273 }
7274
7275 if (!NamedContext->isRecord()) {
7276 // Ideally this would point at the last name in the specifier,
7277 // but we don't have that level of source info.
7278 Diag(SS.getRange().getBegin(),
7279 diag::err_using_decl_nested_name_specifier_is_not_class)
7280 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7281 return true;
7282 }
7283
Douglas Gregor6fb07292010-12-21 07:41:49 +00007284 if (!NamedContext->isDependentContext() &&
7285 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7286 return true;
7287
Richard Smith80ad52f2013-01-02 11:42:31 +00007288 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007289 // C++0x [namespace.udecl]p3:
7290 // In a using-declaration used as a member-declaration, the
7291 // nested-name-specifier shall name a base class of the class
7292 // being defined.
7293
7294 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7295 cast<CXXRecordDecl>(NamedContext))) {
7296 if (CurContext == NamedContext) {
7297 Diag(NameLoc,
7298 diag::err_using_decl_nested_name_specifier_is_current_class)
7299 << SS.getRange();
7300 return true;
7301 }
7302
7303 Diag(SS.getRange().getBegin(),
7304 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7305 << (NestedNameSpecifier*) SS.getScopeRep()
7306 << cast<CXXRecordDecl>(CurContext)
7307 << SS.getRange();
7308 return true;
7309 }
7310
7311 return false;
7312 }
7313
7314 // C++03 [namespace.udecl]p4:
7315 // A using-declaration used as a member-declaration shall refer
7316 // to a member of a base class of the class being defined [etc.].
7317
7318 // Salient point: SS doesn't have to name a base class as long as
7319 // lookup only finds members from base classes. Therefore we can
7320 // diagnose here only if we can prove that that can't happen,
7321 // i.e. if the class hierarchies provably don't intersect.
7322
7323 // TODO: it would be nice if "definitely valid" results were cached
7324 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7325 // need to be repeated.
7326
7327 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007328 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007329
7330 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7331 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7332 Data->Bases.insert(Base);
7333 return true;
7334 }
7335
7336 bool hasDependentBases(const CXXRecordDecl *Class) {
7337 return !Class->forallBases(collect, this);
7338 }
7339
7340 /// Returns true if the base is dependent or is one of the
7341 /// accumulated base classes.
7342 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7343 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7344 return !Data->Bases.count(Base);
7345 }
7346
7347 bool mightShareBases(const CXXRecordDecl *Class) {
7348 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7349 }
7350 };
7351
7352 UserData Data;
7353
7354 // Returns false if we find a dependent base.
7355 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7356 return false;
7357
7358 // Returns false if the class has a dependent base or if it or one
7359 // of its bases is present in the base set of the current context.
7360 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7361 return false;
7362
7363 Diag(SS.getRange().getBegin(),
7364 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7365 << (NestedNameSpecifier*) SS.getScopeRep()
7366 << cast<CXXRecordDecl>(CurContext)
7367 << SS.getRange();
7368
7369 return true;
John McCalled976492009-12-04 22:46:56 +00007370}
7371
Richard Smith162e1c12011-04-15 14:24:37 +00007372Decl *Sema::ActOnAliasDeclaration(Scope *S,
7373 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007374 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007375 SourceLocation UsingLoc,
7376 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007377 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007378 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007379 // Skip up to the relevant declaration scope.
7380 while (S->getFlags() & Scope::TemplateParamScope)
7381 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007382 assert((S->getFlags() & Scope::DeclScope) &&
7383 "got alias-declaration outside of declaration scope");
7384
7385 if (Type.isInvalid())
7386 return 0;
7387
7388 bool Invalid = false;
7389 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7390 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007391 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007392
7393 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7394 return 0;
7395
7396 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007397 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007398 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007399 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7400 TInfo->getTypeLoc().getBeginLoc());
7401 }
Richard Smith162e1c12011-04-15 14:24:37 +00007402
7403 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7404 LookupName(Previous, S);
7405
7406 // Warn about shadowing the name of a template parameter.
7407 if (Previous.isSingleResult() &&
7408 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007409 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007410 Previous.clear();
7411 }
7412
7413 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7414 "name in alias declaration must be an identifier");
7415 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7416 Name.StartLocation,
7417 Name.Identifier, TInfo);
7418
7419 NewTD->setAccess(AS);
7420
7421 if (Invalid)
7422 NewTD->setInvalidDecl();
7423
Richard Smith6b3d3e52013-02-20 19:22:51 +00007424 ProcessDeclAttributeList(S, NewTD, AttrList);
7425
Richard Smith3e4c6c42011-05-05 21:57:07 +00007426 CheckTypedefForVariablyModifiedType(S, NewTD);
7427 Invalid |= NewTD->isInvalidDecl();
7428
Richard Smith162e1c12011-04-15 14:24:37 +00007429 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007430
7431 NamedDecl *NewND;
7432 if (TemplateParamLists.size()) {
7433 TypeAliasTemplateDecl *OldDecl = 0;
7434 TemplateParameterList *OldTemplateParams = 0;
7435
7436 if (TemplateParamLists.size() != 1) {
7437 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007438 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7439 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007440 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007441 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007442
7443 // Only consider previous declarations in the same scope.
7444 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7445 /*ExplicitInstantiationOrSpecialization*/false);
7446 if (!Previous.empty()) {
7447 Redeclaration = true;
7448
7449 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7450 if (!OldDecl && !Invalid) {
7451 Diag(UsingLoc, diag::err_redefinition_different_kind)
7452 << Name.Identifier;
7453
7454 NamedDecl *OldD = Previous.getRepresentativeDecl();
7455 if (OldD->getLocation().isValid())
7456 Diag(OldD->getLocation(), diag::note_previous_definition);
7457
7458 Invalid = true;
7459 }
7460
7461 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7462 if (TemplateParameterListsAreEqual(TemplateParams,
7463 OldDecl->getTemplateParameters(),
7464 /*Complain=*/true,
7465 TPL_TemplateMatch))
7466 OldTemplateParams = OldDecl->getTemplateParameters();
7467 else
7468 Invalid = true;
7469
7470 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7471 if (!Invalid &&
7472 !Context.hasSameType(OldTD->getUnderlyingType(),
7473 NewTD->getUnderlyingType())) {
7474 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7475 // but we can't reasonably accept it.
7476 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7477 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7478 if (OldTD->getLocation().isValid())
7479 Diag(OldTD->getLocation(), diag::note_previous_definition);
7480 Invalid = true;
7481 }
7482 }
7483 }
7484
7485 // Merge any previous default template arguments into our parameters,
7486 // and check the parameter list.
7487 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7488 TPC_TypeAliasTemplate))
7489 return 0;
7490
7491 TypeAliasTemplateDecl *NewDecl =
7492 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7493 Name.Identifier, TemplateParams,
7494 NewTD);
7495
7496 NewDecl->setAccess(AS);
7497
7498 if (Invalid)
7499 NewDecl->setInvalidDecl();
7500 else if (OldDecl)
7501 NewDecl->setPreviousDeclaration(OldDecl);
7502
7503 NewND = NewDecl;
7504 } else {
7505 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7506 NewND = NewTD;
7507 }
Richard Smith162e1c12011-04-15 14:24:37 +00007508
7509 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007510 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007511
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007512 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007513 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007514}
7515
John McCalld226f652010-08-21 09:40:31 +00007516Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007517 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007518 SourceLocation AliasLoc,
7519 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007520 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007521 SourceLocation IdentLoc,
7522 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007523
Anders Carlsson81c85c42009-03-28 23:53:49 +00007524 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007525 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7526 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007527
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007528 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007529 NamedDecl *PrevDecl
7530 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7531 ForRedeclaration);
7532 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7533 PrevDecl = 0;
7534
7535 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007536 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007537 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007538 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007539 // FIXME: At some point, we'll want to create the (redundant)
7540 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007541 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007542 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007543 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007544 }
Mike Stump1eb44332009-09-09 15:08:12 +00007545
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007546 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7547 diag::err_redefinition_different_kind;
7548 Diag(AliasLoc, DiagID) << Alias;
7549 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007550 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007551 }
7552
John McCalla24dc2e2009-11-17 02:14:36 +00007553 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007554 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007555
John McCallf36e02d2009-10-09 21:13:30 +00007556 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007557 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007558 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007559 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007560 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007561 }
Mike Stump1eb44332009-09-09 15:08:12 +00007562
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007563 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007564 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007565 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007566 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007567
John McCall3dbd3d52010-02-16 06:53:13 +00007568 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007569 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007570}
7571
Sean Hunt001cad92011-05-10 00:49:42 +00007572Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007573Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7574 CXXMethodDecl *MD) {
7575 CXXRecordDecl *ClassDecl = MD->getParent();
7576
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007577 // C++ [except.spec]p14:
7578 // An implicitly declared special member function (Clause 12) shall have an
7579 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007580 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007581 if (ClassDecl->isInvalidDecl())
7582 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007583
Sebastian Redl60618fa2011-03-12 11:50:43 +00007584 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007585 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7586 BEnd = ClassDecl->bases_end();
7587 B != BEnd; ++B) {
7588 if (B->isVirtual()) // Handled below.
7589 continue;
7590
Douglas Gregor18274032010-07-03 00:47:00 +00007591 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7592 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007593 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7594 // If this is a deleted function, add it anyway. This might be conformant
7595 // with the standard. This might not. I'm not sure. It might not matter.
7596 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007597 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007598 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007599 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007600
7601 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007602 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7603 BEnd = ClassDecl->vbases_end();
7604 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007605 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7606 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007607 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7608 // If this is a deleted function, add it anyway. This might be conformant
7609 // with the standard. This might not. I'm not sure. It might not matter.
7610 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007611 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007612 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007613 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007614
7615 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007616 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7617 FEnd = ClassDecl->field_end();
7618 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007619 if (F->hasInClassInitializer()) {
7620 if (Expr *E = F->getInClassInitializer())
7621 ExceptSpec.CalledExpr(E);
7622 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007623 // DR1351:
7624 // If the brace-or-equal-initializer of a non-static data member
7625 // invokes a defaulted default constructor of its class or of an
7626 // enclosing class in a potentially evaluated subexpression, the
7627 // program is ill-formed.
7628 //
7629 // This resolution is unworkable: the exception specification of the
7630 // default constructor can be needed in an unevaluated context, in
7631 // particular, in the operand of a noexcept-expression, and we can be
7632 // unable to compute an exception specification for an enclosed class.
7633 //
7634 // We do not allow an in-class initializer to require the evaluation
7635 // of the exception specification for any in-class initializer whose
7636 // definition is not lexically complete.
7637 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007638 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007639 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007640 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7641 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7642 // If this is a deleted function, add it anyway. This might be conformant
7643 // with the standard. This might not. I'm not sure. It might not matter.
7644 // In particular, the problem is that this function never gets called. It
7645 // might just be ill-formed because this function attempts to refer to
7646 // a deleted function here.
7647 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007648 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007649 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007650 }
John McCalle23cf432010-12-14 08:05:40 +00007651
Sean Hunt001cad92011-05-10 00:49:42 +00007652 return ExceptSpec;
7653}
7654
Richard Smith07b0fdc2013-03-18 21:12:30 +00007655Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007656Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7657 CXXRecordDecl *ClassDecl = CD->getParent();
7658
7659 // C++ [except.spec]p14:
7660 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007661 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007662 if (ClassDecl->isInvalidDecl())
7663 return ExceptSpec;
7664
7665 // Inherited constructor.
7666 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7667 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7668 // FIXME: Copying or moving the parameters could add extra exceptions to the
7669 // set, as could the default arguments for the inherited constructor. This
7670 // will be addressed when we implement the resolution of core issue 1351.
7671 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7672
7673 // Direct base-class constructors.
7674 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7675 BEnd = ClassDecl->bases_end();
7676 B != BEnd; ++B) {
7677 if (B->isVirtual()) // Handled below.
7678 continue;
7679
7680 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7681 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7682 if (BaseClassDecl == InheritedDecl)
7683 continue;
7684 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7685 if (Constructor)
7686 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7687 }
7688 }
7689
7690 // Virtual base-class constructors.
7691 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7692 BEnd = ClassDecl->vbases_end();
7693 B != BEnd; ++B) {
7694 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7695 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7696 if (BaseClassDecl == InheritedDecl)
7697 continue;
7698 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7699 if (Constructor)
7700 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7701 }
7702 }
7703
7704 // Field constructors.
7705 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7706 FEnd = ClassDecl->field_end();
7707 F != FEnd; ++F) {
7708 if (F->hasInClassInitializer()) {
7709 if (Expr *E = F->getInClassInitializer())
7710 ExceptSpec.CalledExpr(E);
7711 else if (!F->isInvalidDecl())
7712 Diag(CD->getLocation(),
7713 diag::err_in_class_initializer_references_def_ctor) << CD;
7714 } else if (const RecordType *RecordTy
7715 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7716 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7717 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7718 if (Constructor)
7719 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7720 }
7721 }
7722
Richard Smith07b0fdc2013-03-18 21:12:30 +00007723 return ExceptSpec;
7724}
7725
Richard Smithafb49182012-11-29 01:34:07 +00007726namespace {
7727/// RAII object to register a special member as being currently declared.
7728struct DeclaringSpecialMember {
7729 Sema &S;
7730 Sema::SpecialMemberDecl D;
7731 bool WasAlreadyBeingDeclared;
7732
7733 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7734 : S(S), D(RD, CSM) {
7735 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7736 if (WasAlreadyBeingDeclared)
7737 // This almost never happens, but if it does, ensure that our cache
7738 // doesn't contain a stale result.
7739 S.SpecialMemberCache.clear();
7740
7741 // FIXME: Register a note to be produced if we encounter an error while
7742 // declaring the special member.
7743 }
7744 ~DeclaringSpecialMember() {
7745 if (!WasAlreadyBeingDeclared)
7746 S.SpecialMembersBeingDeclared.erase(D);
7747 }
7748
7749 /// \brief Are we already trying to declare this special member?
7750 bool isAlreadyBeingDeclared() const {
7751 return WasAlreadyBeingDeclared;
7752 }
7753};
7754}
7755
Sean Hunt001cad92011-05-10 00:49:42 +00007756CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7757 CXXRecordDecl *ClassDecl) {
7758 // C++ [class.ctor]p5:
7759 // A default constructor for a class X is a constructor of class X
7760 // that can be called without an argument. If there is no
7761 // user-declared constructor for class X, a default constructor is
7762 // implicitly declared. An implicitly-declared default constructor
7763 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007764 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007765 "Should not build implicit default constructor!");
7766
Richard Smithafb49182012-11-29 01:34:07 +00007767 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7768 if (DSM.isAlreadyBeingDeclared())
7769 return 0;
7770
Richard Smith7756afa2012-06-10 05:43:50 +00007771 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7772 CXXDefaultConstructor,
7773 false);
7774
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007775 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007776 CanQualType ClassType
7777 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007778 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007779 DeclarationName Name
7780 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007781 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007782 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007783 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007784 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007785 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007786 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007787 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007788 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007789
7790 // Build an exception specification pointing back at this constructor.
7791 FunctionProtoType::ExtProtoInfo EPI;
7792 EPI.ExceptionSpecType = EST_Unevaluated;
7793 EPI.ExceptionSpecDecl = DefaultCon;
Dmitri Gribenko55431692013-05-05 00:41:58 +00007794 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007795
Richard Smithbc2a35d2012-12-08 08:32:28 +00007796 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7797 // constructors is easy to compute.
7798 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7799
7800 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007801 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007802
Douglas Gregor18274032010-07-03 00:47:00 +00007803 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007804 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007805
Douglas Gregor23c94db2010-07-02 17:43:08 +00007806 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007807 PushOnScopeChains(DefaultCon, S, false);
7808 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007809
Douglas Gregor32df23e2010-07-01 22:02:46 +00007810 return DefaultCon;
7811}
7812
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007813void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7814 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007815 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007816 !Constructor->doesThisDeclarationHaveABody() &&
7817 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007818 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007819
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007820 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007821 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007822
Eli Friedman9a14db32012-10-18 20:14:08 +00007823 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007824 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007825 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007826 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007827 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007828 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007829 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007830 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007831 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007832
7833 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007834 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007835
7836 Constructor->setUsed();
7837 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007838
7839 if (ASTMutationListener *L = getASTMutationListener()) {
7840 L->CompletedImplicitDefinition(Constructor);
7841 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007842}
7843
Richard Smith7a614d82011-06-11 17:19:42 +00007844void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007845 // Check that any explicitly-defaulted methods have exception specifications
7846 // compatible with their implicit exception specifications.
7847 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007848}
7849
Richard Smith4841ca52013-04-10 05:48:59 +00007850namespace {
7851/// Information on inheriting constructors to declare.
7852class InheritingConstructorInfo {
7853public:
7854 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7855 : SemaRef(SemaRef), Derived(Derived) {
7856 // Mark the constructors that we already have in the derived class.
7857 //
7858 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7859 // unless there is a user-declared constructor with the same signature in
7860 // the class where the using-declaration appears.
7861 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7862 }
7863
7864 void inheritAll(CXXRecordDecl *RD) {
7865 visitAll(RD, &InheritingConstructorInfo::inherit);
7866 }
7867
7868private:
7869 /// Information about an inheriting constructor.
7870 struct InheritingConstructor {
7871 InheritingConstructor()
7872 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7873
7874 /// If \c true, a constructor with this signature is already declared
7875 /// in the derived class.
7876 bool DeclaredInDerived;
7877
7878 /// The constructor which is inherited.
7879 const CXXConstructorDecl *BaseCtor;
7880
7881 /// The derived constructor we declared.
7882 CXXConstructorDecl *DerivedCtor;
7883 };
7884
7885 /// Inheriting constructors with a given canonical type. There can be at
7886 /// most one such non-template constructor, and any number of templated
7887 /// constructors.
7888 struct InheritingConstructorsForType {
7889 InheritingConstructor NonTemplate;
7890 llvm::SmallVector<
7891 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7892
7893 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7894 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7895 TemplateParameterList *ParamList = FTD->getTemplateParameters();
7896 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7897 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7898 false, S.TPL_TemplateMatch))
7899 return Templates[I].second;
7900 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7901 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007902 }
Richard Smith4841ca52013-04-10 05:48:59 +00007903
7904 return NonTemplate;
7905 }
7906 };
7907
7908 /// Get or create the inheriting constructor record for a constructor.
7909 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7910 QualType CtorType) {
7911 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7912 .getEntry(SemaRef, Ctor);
7913 }
7914
7915 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7916
7917 /// Process all constructors for a class.
7918 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7919 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7920 CtorE = RD->ctor_end();
7921 CtorIt != CtorE; ++CtorIt)
7922 (this->*Callback)(*CtorIt);
7923 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7924 I(RD->decls_begin()), E(RD->decls_end());
7925 I != E; ++I) {
7926 const FunctionDecl *FD = (*I)->getTemplatedDecl();
7927 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7928 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007929 }
7930 }
Richard Smith4841ca52013-04-10 05:48:59 +00007931
7932 /// Note that a constructor (or constructor template) was declared in Derived.
7933 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7934 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7935 }
7936
7937 /// Inherit a single constructor.
7938 void inherit(const CXXConstructorDecl *Ctor) {
7939 const FunctionProtoType *CtorType =
7940 Ctor->getType()->castAs<FunctionProtoType>();
7941 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7942 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7943
7944 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7945
7946 // Core issue (no number yet): the ellipsis is always discarded.
7947 if (EPI.Variadic) {
7948 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7949 SemaRef.Diag(Ctor->getLocation(),
7950 diag::note_using_decl_constructor_ellipsis);
7951 EPI.Variadic = false;
7952 }
7953
7954 // Declare a constructor for each number of parameters.
7955 //
7956 // C++11 [class.inhctor]p1:
7957 // The candidate set of inherited constructors from the class X named in
7958 // the using-declaration consists of [... modulo defects ...] for each
7959 // constructor or constructor template of X, the set of constructors or
7960 // constructor templates that results from omitting any ellipsis parameter
7961 // specification and successively omitting parameters with a default
7962 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00007963 unsigned MinParams = minParamsToInherit(Ctor);
7964 unsigned Params = Ctor->getNumParams();
7965 if (Params >= MinParams) {
7966 do
7967 declareCtor(UsingLoc, Ctor,
7968 SemaRef.Context.getFunctionType(
7969 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7970 while (Params > MinParams &&
7971 Ctor->getParamDecl(--Params)->hasDefaultArg());
7972 }
Richard Smith4841ca52013-04-10 05:48:59 +00007973 }
7974
7975 /// Find the using-declaration which specified that we should inherit the
7976 /// constructors of \p Base.
7977 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
7978 // No fancy lookup required; just look for the base constructor name
7979 // directly within the derived class.
7980 ASTContext &Context = SemaRef.Context;
7981 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
7982 Context.getCanonicalType(Context.getRecordType(Base)));
7983 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
7984 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
7985 }
7986
7987 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
7988 // C++11 [class.inhctor]p3:
7989 // [F]or each constructor template in the candidate set of inherited
7990 // constructors, a constructor template is implicitly declared
7991 if (Ctor->getDescribedFunctionTemplate())
7992 return 0;
7993
7994 // For each non-template constructor in the candidate set of inherited
7995 // constructors other than a constructor having no parameters or a
7996 // copy/move constructor having a single parameter, a constructor is
7997 // implicitly declared [...]
7998 if (Ctor->getNumParams() == 0)
7999 return 1;
8000 if (Ctor->isCopyOrMoveConstructor())
8001 return 2;
8002
8003 // Per discussion on core reflector, never inherit a constructor which
8004 // would become a default, copy, or move constructor of Derived either.
8005 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8006 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8007 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8008 }
8009
8010 /// Declare a single inheriting constructor, inheriting the specified
8011 /// constructor, with the given type.
8012 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8013 QualType DerivedType) {
8014 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8015
8016 // C++11 [class.inhctor]p3:
8017 // ... a constructor is implicitly declared with the same constructor
8018 // characteristics unless there is a user-declared constructor with
8019 // the same signature in the class where the using-declaration appears
8020 if (Entry.DeclaredInDerived)
8021 return;
8022
8023 // C++11 [class.inhctor]p7:
8024 // If two using-declarations declare inheriting constructors with the
8025 // same signature, the program is ill-formed
8026 if (Entry.DerivedCtor) {
8027 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8028 // Only diagnose this once per constructor.
8029 if (Entry.DerivedCtor->isInvalidDecl())
8030 return;
8031 Entry.DerivedCtor->setInvalidDecl();
8032
8033 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8034 SemaRef.Diag(BaseCtor->getLocation(),
8035 diag::note_using_decl_constructor_conflict_current_ctor);
8036 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8037 diag::note_using_decl_constructor_conflict_previous_ctor);
8038 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8039 diag::note_using_decl_constructor_conflict_previous_using);
8040 } else {
8041 // Core issue (no number): if the same inheriting constructor is
8042 // produced by multiple base class constructors from the same base
8043 // class, the inheriting constructor is defined as deleted.
8044 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8045 }
8046
8047 return;
8048 }
8049
8050 ASTContext &Context = SemaRef.Context;
8051 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8052 Context.getCanonicalType(Context.getRecordType(Derived)));
8053 DeclarationNameInfo NameInfo(Name, UsingLoc);
8054
8055 TemplateParameterList *TemplateParams = 0;
8056 if (const FunctionTemplateDecl *FTD =
8057 BaseCtor->getDescribedFunctionTemplate()) {
8058 TemplateParams = FTD->getTemplateParameters();
8059 // We're reusing template parameters from a different DeclContext. This
8060 // is questionable at best, but works out because the template depth in
8061 // both places is guaranteed to be 0.
8062 // FIXME: Rebuild the template parameters in the new context, and
8063 // transform the function type to refer to them.
8064 }
8065
8066 // Build type source info pointing at the using-declaration. This is
8067 // required by template instantiation.
8068 TypeSourceInfo *TInfo =
8069 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8070 FunctionProtoTypeLoc ProtoLoc =
8071 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8072
8073 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8074 Context, Derived, UsingLoc, NameInfo, DerivedType,
8075 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8076 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8077
8078 // Build an unevaluated exception specification for this constructor.
8079 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8080 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8081 EPI.ExceptionSpecType = EST_Unevaluated;
8082 EPI.ExceptionSpecDecl = DerivedCtor;
8083 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8084 FPT->getArgTypes(), EPI));
8085
8086 // Build the parameter declarations.
8087 SmallVector<ParmVarDecl *, 16> ParamDecls;
8088 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8089 TypeSourceInfo *TInfo =
8090 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8091 ParmVarDecl *PD = ParmVarDecl::Create(
8092 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8093 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8094 PD->setScopeInfo(0, I);
8095 PD->setImplicit();
8096 ParamDecls.push_back(PD);
8097 ProtoLoc.setArg(I, PD);
8098 }
8099
8100 // Set up the new constructor.
8101 DerivedCtor->setAccess(BaseCtor->getAccess());
8102 DerivedCtor->setParams(ParamDecls);
8103 DerivedCtor->setInheritedConstructor(BaseCtor);
8104 if (BaseCtor->isDeleted())
8105 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8106
8107 // If this is a constructor template, build the template declaration.
8108 if (TemplateParams) {
8109 FunctionTemplateDecl *DerivedTemplate =
8110 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8111 TemplateParams, DerivedCtor);
8112 DerivedTemplate->setAccess(BaseCtor->getAccess());
8113 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8114 Derived->addDecl(DerivedTemplate);
8115 } else {
8116 Derived->addDecl(DerivedCtor);
8117 }
8118
8119 Entry.BaseCtor = BaseCtor;
8120 Entry.DerivedCtor = DerivedCtor;
8121 }
8122
8123 Sema &SemaRef;
8124 CXXRecordDecl *Derived;
8125 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8126 MapType Map;
8127};
8128}
8129
8130void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8131 // Defer declaring the inheriting constructors until the class is
8132 // instantiated.
8133 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008134 return;
8135
Richard Smith4841ca52013-04-10 05:48:59 +00008136 // Find base classes from which we might inherit constructors.
8137 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8138 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8139 BaseE = ClassDecl->bases_end();
8140 BaseIt != BaseE; ++BaseIt)
8141 if (BaseIt->getInheritConstructors())
8142 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008143
Richard Smith4841ca52013-04-10 05:48:59 +00008144 // Go no further if we're not inheriting any constructors.
8145 if (InheritedBases.empty())
8146 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008147
Richard Smith4841ca52013-04-10 05:48:59 +00008148 // Declare the inherited constructors.
8149 InheritingConstructorInfo ICI(*this, ClassDecl);
8150 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8151 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008152}
8153
Richard Smith07b0fdc2013-03-18 21:12:30 +00008154void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8155 CXXConstructorDecl *Constructor) {
8156 CXXRecordDecl *ClassDecl = Constructor->getParent();
8157 assert(Constructor->getInheritedConstructor() &&
8158 !Constructor->doesThisDeclarationHaveABody() &&
8159 !Constructor->isDeleted());
8160
8161 SynthesizedFunctionScope Scope(*this, Constructor);
8162 DiagnosticErrorTrap Trap(Diags);
8163 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8164 Trap.hasErrorOccurred()) {
8165 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8166 << Context.getTagDeclType(ClassDecl);
8167 Constructor->setInvalidDecl();
8168 return;
8169 }
8170
8171 SourceLocation Loc = Constructor->getLocation();
8172 Constructor->setBody(new (Context) CompoundStmt(Loc));
8173
8174 Constructor->setUsed();
8175 MarkVTableUsed(CurrentLocation, ClassDecl);
8176
8177 if (ASTMutationListener *L = getASTMutationListener()) {
8178 L->CompletedImplicitDefinition(Constructor);
8179 }
8180}
8181
8182
Sean Huntcb45a0f2011-05-12 22:46:25 +00008183Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008184Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8185 CXXRecordDecl *ClassDecl = MD->getParent();
8186
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008187 // C++ [except.spec]p14:
8188 // An implicitly declared special member function (Clause 12) shall have
8189 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008190 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008191 if (ClassDecl->isInvalidDecl())
8192 return ExceptSpec;
8193
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008194 // Direct base-class destructors.
8195 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8196 BEnd = ClassDecl->bases_end();
8197 B != BEnd; ++B) {
8198 if (B->isVirtual()) // Handled below.
8199 continue;
8200
8201 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008202 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008203 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008204 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008205
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008206 // Virtual base-class destructors.
8207 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8208 BEnd = ClassDecl->vbases_end();
8209 B != BEnd; ++B) {
8210 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008211 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008212 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008213 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008214
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008215 // Field destructors.
8216 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8217 FEnd = ClassDecl->field_end();
8218 F != FEnd; ++F) {
8219 if (const RecordType *RecordTy
8220 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008221 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008222 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008223 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008224
Sean Huntcb45a0f2011-05-12 22:46:25 +00008225 return ExceptSpec;
8226}
8227
8228CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8229 // C++ [class.dtor]p2:
8230 // If a class has no user-declared destructor, a destructor is
8231 // declared implicitly. An implicitly-declared destructor is an
8232 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008233 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008234
Richard Smithafb49182012-11-29 01:34:07 +00008235 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8236 if (DSM.isAlreadyBeingDeclared())
8237 return 0;
8238
Douglas Gregor4923aa22010-07-02 20:37:36 +00008239 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008240 CanQualType ClassType
8241 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008242 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008243 DeclarationName Name
8244 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008245 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008246 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008247 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8248 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008249 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008250 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008251 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008252 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008253
8254 // Build an exception specification pointing back at this destructor.
8255 FunctionProtoType::ExtProtoInfo EPI;
8256 EPI.ExceptionSpecType = EST_Unevaluated;
8257 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008258 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008259
Richard Smithbc2a35d2012-12-08 08:32:28 +00008260 AddOverriddenMethods(ClassDecl, Destructor);
8261
8262 // We don't need to use SpecialMemberIsTrivial here; triviality for
8263 // destructors is easy to compute.
8264 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8265
8266 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008267 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008268
Douglas Gregor4923aa22010-07-02 20:37:36 +00008269 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008270 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008271
Douglas Gregor4923aa22010-07-02 20:37:36 +00008272 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008273 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008274 PushOnScopeChains(Destructor, S, false);
8275 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008276
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008277 return Destructor;
8278}
8279
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008280void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008281 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008282 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008283 !Destructor->doesThisDeclarationHaveABody() &&
8284 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008285 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008286 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008287 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008288
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008289 if (Destructor->isInvalidDecl())
8290 return;
8291
Eli Friedman9a14db32012-10-18 20:14:08 +00008292 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008293
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008294 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008295 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8296 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008297
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008298 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008299 Diag(CurrentLocation, diag::note_member_synthesized_at)
8300 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8301
8302 Destructor->setInvalidDecl();
8303 return;
8304 }
8305
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008306 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008307 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008308 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008309 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008310 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008311
8312 if (ASTMutationListener *L = getASTMutationListener()) {
8313 L->CompletedImplicitDefinition(Destructor);
8314 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008315}
8316
Richard Smitha4156b82012-04-21 18:42:51 +00008317/// \brief Perform any semantic analysis which needs to be delayed until all
8318/// pending class member declarations have been parsed.
8319void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008320 // If the context is an invalid C++ class, just suppress these checks.
8321 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8322 if (Record->isInvalidDecl()) {
8323 DelayedDestructorExceptionSpecChecks.clear();
8324 return;
8325 }
8326 }
8327
Richard Smitha4156b82012-04-21 18:42:51 +00008328 // Perform any deferred checking of exception specifications for virtual
8329 // destructors.
8330 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8331 i != e; ++i) {
8332 const CXXDestructorDecl *Dtor =
8333 DelayedDestructorExceptionSpecChecks[i].first;
8334 assert(!Dtor->getParent()->isDependentType() &&
8335 "Should not ever add destructors of templates into the list.");
8336 CheckOverridingFunctionExceptionSpec(Dtor,
8337 DelayedDestructorExceptionSpecChecks[i].second);
8338 }
8339 DelayedDestructorExceptionSpecChecks.clear();
8340}
8341
Richard Smithb9d0b762012-07-27 04:22:15 +00008342void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8343 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008344 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008345 "adjusting dtor exception specs was introduced in c++11");
8346
Sebastian Redl0ee33912011-05-19 05:13:44 +00008347 // C++11 [class.dtor]p3:
8348 // A declaration of a destructor that does not have an exception-
8349 // specification is implicitly considered to have the same exception-
8350 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008351 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008352 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008353 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008354 return;
8355
Chandler Carruth3f224b22011-09-20 04:55:26 +00008356 // Replace the destructor's type, building off the existing one. Fortunately,
8357 // the only thing of interest in the destructor type is its extended info.
8358 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008359 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8360 EPI.ExceptionSpecType = EST_Unevaluated;
8361 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008362 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008363
Sebastian Redl0ee33912011-05-19 05:13:44 +00008364 // FIXME: If the destructor has a body that could throw, and the newly created
8365 // spec doesn't allow exceptions, we should emit a warning, because this
8366 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008367 // However, we don't have a body or an exception specification yet, so it
8368 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008369}
8370
Richard Smith8c889532012-11-14 00:50:40 +00008371/// When generating a defaulted copy or move assignment operator, if a field
8372/// should be copied with __builtin_memcpy rather than via explicit assignments,
8373/// do so. This optimization only applies for arrays of scalars, and for arrays
8374/// of class type where the selected copy/move-assignment operator is trivial.
8375static StmtResult
8376buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8377 Expr *To, Expr *From) {
8378 // Compute the size of the memory buffer to be copied.
8379 QualType SizeType = S.Context.getSizeType();
8380 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8381 S.Context.getTypeSizeInChars(T).getQuantity());
8382
8383 // Take the address of the field references for "from" and "to". We
8384 // directly construct UnaryOperators here because semantic analysis
8385 // does not permit us to take the address of an xvalue.
8386 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8387 S.Context.getPointerType(From->getType()),
8388 VK_RValue, OK_Ordinary, Loc);
8389 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8390 S.Context.getPointerType(To->getType()),
8391 VK_RValue, OK_Ordinary, Loc);
8392
8393 const Type *E = T->getBaseElementTypeUnsafe();
8394 bool NeedsCollectableMemCpy =
8395 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8396
8397 // Create a reference to the __builtin_objc_memmove_collectable function
8398 StringRef MemCpyName = NeedsCollectableMemCpy ?
8399 "__builtin_objc_memmove_collectable" :
8400 "__builtin_memcpy";
8401 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8402 Sema::LookupOrdinaryName);
8403 S.LookupName(R, S.TUScope, true);
8404
8405 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8406 if (!MemCpy)
8407 // Something went horribly wrong earlier, and we will have complained
8408 // about it.
8409 return StmtError();
8410
8411 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8412 VK_RValue, Loc, 0);
8413 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8414
8415 Expr *CallArgs[] = {
8416 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8417 };
8418 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8419 Loc, CallArgs, Loc);
8420
8421 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8422 return S.Owned(Call.takeAs<Stmt>());
8423}
8424
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008425/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008426/// \c To.
8427///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008428/// This routine is used to copy/move the members of a class with an
8429/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008430/// copied are arrays, this routine builds for loops to copy them.
8431///
8432/// \param S The Sema object used for type-checking.
8433///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008434/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008435///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008436/// \param T The type of the expressions being copied/moved. Both expressions
8437/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008438///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008439/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008440///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008441/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008442///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008443/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008444/// Otherwise, it's a non-static member subobject.
8445///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008446/// \param Copying Whether we're copying or moving.
8447///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008448/// \param Depth Internal parameter recording the depth of the recursion.
8449///
Richard Smith8c889532012-11-14 00:50:40 +00008450/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8451/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008452static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008453buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8454 Expr *To, Expr *From,
8455 bool CopyingBaseSubobject, bool Copying,
8456 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008457 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008458 // Each subobject is assigned in the manner appropriate to its type:
8459 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008460 // - if the subobject is of class type, as if by a call to operator= with
8461 // the subobject as the object expression and the corresponding
8462 // subobject of x as a single function argument (as if by explicit
8463 // qualification; that is, ignoring any possible virtual overriding
8464 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008465 //
8466 // C++03 [class.copy]p13:
8467 // - if the subobject is of class type, the copy assignment operator for
8468 // the class is used (as if by explicit qualification; that is,
8469 // ignoring any possible virtual overriding functions in more derived
8470 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008471 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8472 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008473
Douglas Gregor06a9f362010-05-01 20:49:11 +00008474 // Look for operator=.
8475 DeclarationName Name
8476 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8477 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8478 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008479
Richard Smith044c8aa2012-11-13 00:54:12 +00008480 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8481 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008482 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008483 LookupResult::Filter F = OpLookup.makeFilter();
8484 while (F.hasNext()) {
8485 NamedDecl *D = F.next();
8486 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8487 if (Method->isCopyAssignmentOperator() ||
8488 (!Copying && Method->isMoveAssignmentOperator()))
8489 continue;
8490
8491 F.erase();
8492 }
8493 F.done();
John McCallb0207482010-03-16 06:11:48 +00008494 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008495
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008496 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008497 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008498 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008499 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008500 // ambiguities), we need to cast "this" to that subobject type; to
8501 // ensure that we don't go through the virtual call mechanism, we need
8502 // to qualify the operator= name with the base class (see below). However,
8503 // this means that if the base class has a protected copy assignment
8504 // operator, the protected member access check will fail. So, we
8505 // rewrite "protected" access to "public" access in this case, since we
8506 // know by construction that we're calling from a derived class.
8507 if (CopyingBaseSubobject) {
8508 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8509 L != LEnd; ++L) {
8510 if (L.getAccess() == AS_protected)
8511 L.setAccess(AS_public);
8512 }
8513 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008514
Douglas Gregor06a9f362010-05-01 20:49:11 +00008515 // Create the nested-name-specifier that will be used to qualify the
8516 // reference to operator=; this is required to suppress the virtual
8517 // call mechanism.
8518 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008519 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008520 SS.MakeTrivial(S.Context,
8521 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008522 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008523 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008524
Douglas Gregor06a9f362010-05-01 20:49:11 +00008525 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008526 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008527 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008528 /*TemplateKWLoc=*/SourceLocation(),
8529 /*FirstQualifierInScope=*/0,
8530 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008531 /*TemplateArgs=*/0,
8532 /*SuppressQualifierCheck=*/true);
8533 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008534 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008535
Douglas Gregor06a9f362010-05-01 20:49:11 +00008536 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008537
Richard Smith044c8aa2012-11-13 00:54:12 +00008538 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008539 OpEqualRef.takeAs<Expr>(),
8540 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008541 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008542 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008543
Richard Smith8c889532012-11-14 00:50:40 +00008544 // If we built a call to a trivial 'operator=' while copying an array,
8545 // bail out. We'll replace the whole shebang with a memcpy.
8546 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8547 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8548 return StmtResult((Stmt*)0);
8549
Richard Smith044c8aa2012-11-13 00:54:12 +00008550 // Convert to an expression-statement, and clean up any produced
8551 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008552 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008553 }
John McCallb0207482010-03-16 06:11:48 +00008554
Richard Smith044c8aa2012-11-13 00:54:12 +00008555 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008556 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008557 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008558 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008559 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008560 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008561 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008562 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008563 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008564
8565 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008566 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008567
Douglas Gregor06a9f362010-05-01 20:49:11 +00008568 // Construct a loop over the array bounds, e.g.,
8569 //
8570 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8571 //
8572 // that will copy each of the array elements.
8573 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008574
Douglas Gregor06a9f362010-05-01 20:49:11 +00008575 // Create the iteration variable.
8576 IdentifierInfo *IterationVarName = 0;
8577 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008578 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008579 llvm::raw_svector_ostream OS(Str);
8580 OS << "__i" << Depth;
8581 IterationVarName = &S.Context.Idents.get(OS.str());
8582 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008583 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008584 IterationVarName, SizeType,
8585 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008586 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008587
Douglas Gregor06a9f362010-05-01 20:49:11 +00008588 // Initialize the iteration variable to zero.
8589 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008590 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008591
8592 // Create a reference to the iteration variable; we'll use this several
8593 // times throughout.
8594 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008595 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008596 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008597 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8598 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8599
Douglas Gregor06a9f362010-05-01 20:49:11 +00008600 // Create the DeclStmt that holds the iteration variable.
8601 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008602
Douglas Gregor06a9f362010-05-01 20:49:11 +00008603 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008604 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008605 IterationVarRefRVal,
8606 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008607 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008608 IterationVarRefRVal,
8609 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008610 if (!Copying) // Cast to rvalue
8611 From = CastForMoving(S, From);
8612
8613 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008614 StmtResult Copy =
8615 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8616 To, From, CopyingBaseSubobject,
8617 Copying, Depth + 1);
8618 // Bail out if copying fails or if we determined that we should use memcpy.
8619 if (Copy.isInvalid() || !Copy.get())
8620 return Copy;
8621
8622 // Create the comparison against the array bound.
8623 llvm::APInt Upper
8624 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8625 Expr *Comparison
8626 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8627 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8628 BO_NE, S.Context.BoolTy,
8629 VK_RValue, OK_Ordinary, Loc, false);
8630
8631 // Create the pre-increment of the iteration variable.
8632 Expr *Increment
8633 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8634 VK_LValue, OK_Ordinary, Loc);
8635
Douglas Gregor06a9f362010-05-01 20:49:11 +00008636 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008637 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008638 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008639 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008640 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008641}
8642
Richard Smith8c889532012-11-14 00:50:40 +00008643static StmtResult
8644buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8645 Expr *To, Expr *From,
8646 bool CopyingBaseSubobject, bool Copying) {
8647 // Maybe we should use a memcpy?
8648 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8649 T.isTriviallyCopyableType(S.Context))
8650 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8651
8652 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8653 CopyingBaseSubobject,
8654 Copying, 0));
8655
8656 // If we ended up picking a trivial assignment operator for an array of a
8657 // non-trivially-copyable class type, just emit a memcpy.
8658 if (!Result.isInvalid() && !Result.get())
8659 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8660
8661 return Result;
8662}
8663
Richard Smithb9d0b762012-07-27 04:22:15 +00008664Sema::ImplicitExceptionSpecification
8665Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8666 CXXRecordDecl *ClassDecl = MD->getParent();
8667
8668 ImplicitExceptionSpecification ExceptSpec(*this);
8669 if (ClassDecl->isInvalidDecl())
8670 return ExceptSpec;
8671
8672 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8673 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8674 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8675
Douglas Gregorb87786f2010-07-01 17:48:08 +00008676 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008677 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008678 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008679
8680 // It is unspecified whether or not an implicit copy assignment operator
8681 // attempts to deduplicate calls to assignment operators of virtual bases are
8682 // made. As such, this exception specification is effectively unspecified.
8683 // Based on a similar decision made for constness in C++0x, we're erring on
8684 // the side of assuming such calls to be made regardless of whether they
8685 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008686 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8687 BaseEnd = ClassDecl->bases_end();
8688 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008689 if (Base->isVirtual())
8690 continue;
8691
Douglas Gregora376d102010-07-02 21:50:04 +00008692 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008693 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008694 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8695 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008696 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008697 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008698
8699 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8700 BaseEnd = ClassDecl->vbases_end();
8701 Base != BaseEnd; ++Base) {
8702 CXXRecordDecl *BaseClassDecl
8703 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8704 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8705 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008706 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008707 }
8708
Douglas Gregorb87786f2010-07-01 17:48:08 +00008709 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8710 FieldEnd = ClassDecl->field_end();
8711 Field != FieldEnd;
8712 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008713 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008714 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8715 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008716 LookupCopyingAssignment(FieldClassDecl,
8717 ArgQuals | FieldType.getCVRQualifiers(),
8718 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008719 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008720 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008721 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008722
Richard Smithb9d0b762012-07-27 04:22:15 +00008723 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008724}
8725
8726CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8727 // Note: The following rules are largely analoguous to the copy
8728 // constructor rules. Note that virtual bases are not taken into account
8729 // for determining the argument type of the operator. Note also that
8730 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008731 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008732
Richard Smithafb49182012-11-29 01:34:07 +00008733 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8734 if (DSM.isAlreadyBeingDeclared())
8735 return 0;
8736
Sean Hunt30de05c2011-05-14 05:23:20 +00008737 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8738 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008739 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008740 ArgType = ArgType.withConst();
8741 ArgType = Context.getLValueReferenceType(ArgType);
8742
Douglas Gregord3c35902010-07-01 16:36:15 +00008743 // An implicitly-declared copy assignment operator is an inline public
8744 // member of its class.
8745 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008746 SourceLocation ClassLoc = ClassDecl->getLocation();
8747 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008748 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008749 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008750 /*TInfo=*/0,
8751 /*StorageClass=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008752 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008753 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008754 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008755 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008756 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008757
8758 // Build an exception specification pointing back at this member.
8759 FunctionProtoType::ExtProtoInfo EPI;
8760 EPI.ExceptionSpecType = EST_Unevaluated;
8761 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008762 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008763
Douglas Gregord3c35902010-07-01 16:36:15 +00008764 // Add the parameter to the operator.
8765 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008766 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008767 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008768 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008769 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008770
Richard Smithbc2a35d2012-12-08 08:32:28 +00008771 AddOverriddenMethods(ClassDecl, CopyAssignment);
8772
8773 CopyAssignment->setTrivial(
8774 ClassDecl->needsOverloadResolutionForCopyAssignment()
8775 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8776 : ClassDecl->hasTrivialCopyAssignment());
8777
Nico Weberafcc96a2012-01-23 03:19:29 +00008778 // C++0x [class.copy]p19:
8779 // .... If the class definition does not explicitly declare a copy
8780 // assignment operator, there is no user-declared move constructor, and
8781 // there is no user-declared move assignment operator, a copy assignment
8782 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008783 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008784 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008785
Richard Smithbc2a35d2012-12-08 08:32:28 +00008786 // Note that we have added this copy-assignment operator.
8787 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8788
8789 if (Scope *S = getScopeForContext(ClassDecl))
8790 PushOnScopeChains(CopyAssignment, S, false);
8791 ClassDecl->addDecl(CopyAssignment);
8792
Douglas Gregord3c35902010-07-01 16:36:15 +00008793 return CopyAssignment;
8794}
8795
Douglas Gregor06a9f362010-05-01 20:49:11 +00008796void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8797 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008798 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008799 CopyAssignOperator->isOverloadedOperator() &&
8800 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008801 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8802 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008803 "DefineImplicitCopyAssignment called for wrong function");
8804
8805 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8806
8807 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8808 CopyAssignOperator->setInvalidDecl();
8809 return;
8810 }
8811
8812 CopyAssignOperator->setUsed();
8813
Eli Friedman9a14db32012-10-18 20:14:08 +00008814 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008815 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008816
8817 // C++0x [class.copy]p30:
8818 // The implicitly-defined or explicitly-defaulted copy assignment operator
8819 // for a non-union class X performs memberwise copy assignment of its
8820 // subobjects. The direct base classes of X are assigned first, in the
8821 // order of their declaration in the base-specifier-list, and then the
8822 // immediate non-static data members of X are assigned, in the order in
8823 // which they were declared in the class definition.
8824
8825 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008826 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008827
8828 // The parameter for the "other" object, which we are copying from.
8829 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8830 Qualifiers OtherQuals = Other->getType().getQualifiers();
8831 QualType OtherRefType = Other->getType();
8832 if (const LValueReferenceType *OtherRef
8833 = OtherRefType->getAs<LValueReferenceType>()) {
8834 OtherRefType = OtherRef->getPointeeType();
8835 OtherQuals = OtherRefType.getQualifiers();
8836 }
8837
8838 // Our location for everything implicitly-generated.
8839 SourceLocation Loc = CopyAssignOperator->getLocation();
8840
8841 // Construct a reference to the "other" object. We'll be using this
8842 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008843 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008844 assert(OtherRef && "Reference to parameter cannot fail!");
8845
8846 // Construct the "this" pointer. We'll be using this throughout the generated
8847 // ASTs.
8848 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8849 assert(This && "Reference to this cannot fail!");
8850
8851 // Assign base classes.
8852 bool Invalid = false;
8853 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8854 E = ClassDecl->bases_end(); Base != E; ++Base) {
8855 // Form the assignment:
8856 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8857 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008858 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008859 Invalid = true;
8860 continue;
8861 }
8862
John McCallf871d0c2010-08-07 06:22:56 +00008863 CXXCastPath BasePath;
8864 BasePath.push_back(Base);
8865
Douglas Gregor06a9f362010-05-01 20:49:11 +00008866 // Construct the "from" expression, which is an implicit cast to the
8867 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008868 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008869 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8870 CK_UncheckedDerivedToBase,
8871 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008872
8873 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008874 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008875
8876 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008877 To = ImpCastExprToType(To.take(),
8878 Context.getCVRQualifiedType(BaseType,
8879 CopyAssignOperator->getTypeQualifiers()),
8880 CK_UncheckedDerivedToBase,
8881 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008882
8883 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008884 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008885 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008886 /*CopyingBaseSubobject=*/true,
8887 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008888 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008889 Diag(CurrentLocation, diag::note_member_synthesized_at)
8890 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8891 CopyAssignOperator->setInvalidDecl();
8892 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008893 }
8894
8895 // Success! Record the copy.
8896 Statements.push_back(Copy.takeAs<Expr>());
8897 }
8898
Douglas Gregor06a9f362010-05-01 20:49:11 +00008899 // Assign non-static members.
8900 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8901 FieldEnd = ClassDecl->field_end();
8902 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008903 if (Field->isUnnamedBitfield())
8904 continue;
8905
Douglas Gregor06a9f362010-05-01 20:49:11 +00008906 // Check for members of reference type; we can't copy those.
8907 if (Field->getType()->isReferenceType()) {
8908 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8909 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8910 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008911 Diag(CurrentLocation, diag::note_member_synthesized_at)
8912 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008913 Invalid = true;
8914 continue;
8915 }
8916
8917 // Check for members of const-qualified, non-class type.
8918 QualType BaseType = Context.getBaseElementType(Field->getType());
8919 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8920 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8921 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8922 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008923 Diag(CurrentLocation, diag::note_member_synthesized_at)
8924 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008925 Invalid = true;
8926 continue;
8927 }
John McCallb77115d2011-06-17 00:18:42 +00008928
8929 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008930 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8931 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008932
8933 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008934 if (FieldType->isIncompleteArrayType()) {
8935 assert(ClassDecl->hasFlexibleArrayMember() &&
8936 "Incomplete array type is not valid");
8937 continue;
8938 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008939
8940 // Build references to the field in the object we're copying from and to.
8941 CXXScopeSpec SS; // Intentionally empty
8942 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8943 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008944 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008945 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008946 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008947 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008948 SS, SourceLocation(), 0,
8949 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008950 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008951 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008952 SS, SourceLocation(), 0,
8953 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008954 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8955 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008956
Douglas Gregor06a9f362010-05-01 20:49:11 +00008957 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008958 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008959 To.get(), From.get(),
8960 /*CopyingBaseSubobject=*/false,
8961 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008962 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008963 Diag(CurrentLocation, diag::note_member_synthesized_at)
8964 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8965 CopyAssignOperator->setInvalidDecl();
8966 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008967 }
8968
8969 // Success! Record the copy.
8970 Statements.push_back(Copy.takeAs<Stmt>());
8971 }
8972
8973 if (!Invalid) {
8974 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008975 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008976
John McCall60d7b3a2010-08-24 06:29:42 +00008977 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008978 if (Return.isInvalid())
8979 Invalid = true;
8980 else {
8981 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008982
8983 if (Trap.hasErrorOccurred()) {
8984 Diag(CurrentLocation, diag::note_member_synthesized_at)
8985 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8986 Invalid = true;
8987 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008988 }
8989 }
8990
8991 if (Invalid) {
8992 CopyAssignOperator->setInvalidDecl();
8993 return;
8994 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008995
8996 StmtResult Body;
8997 {
8998 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008999 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009000 /*isStmtExpr=*/false);
9001 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9002 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009003 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009004
9005 if (ASTMutationListener *L = getASTMutationListener()) {
9006 L->CompletedImplicitDefinition(CopyAssignOperator);
9007 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009008}
9009
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009010Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009011Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9012 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009013
Richard Smithb9d0b762012-07-27 04:22:15 +00009014 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009015 if (ClassDecl->isInvalidDecl())
9016 return ExceptSpec;
9017
9018 // C++0x [except.spec]p14:
9019 // An implicitly declared special member function (Clause 12) shall have an
9020 // exception-specification. [...]
9021
9022 // It is unspecified whether or not an implicit move assignment operator
9023 // attempts to deduplicate calls to assignment operators of virtual bases are
9024 // made. As such, this exception specification is effectively unspecified.
9025 // Based on a similar decision made for constness in C++0x, we're erring on
9026 // the side of assuming such calls to be made regardless of whether they
9027 // actually happen.
9028 // Note that a move constructor is not implicitly declared when there are
9029 // virtual bases, but it can still be user-declared and explicitly defaulted.
9030 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9031 BaseEnd = ClassDecl->bases_end();
9032 Base != BaseEnd; ++Base) {
9033 if (Base->isVirtual())
9034 continue;
9035
9036 CXXRecordDecl *BaseClassDecl
9037 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9038 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009039 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009040 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009041 }
9042
9043 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9044 BaseEnd = ClassDecl->vbases_end();
9045 Base != BaseEnd; ++Base) {
9046 CXXRecordDecl *BaseClassDecl
9047 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9048 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009049 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009050 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009051 }
9052
9053 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9054 FieldEnd = ClassDecl->field_end();
9055 Field != FieldEnd;
9056 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009057 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009058 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009059 if (CXXMethodDecl *MoveAssign =
9060 LookupMovingAssignment(FieldClassDecl,
9061 FieldType.getCVRQualifiers(),
9062 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009063 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009064 }
9065 }
9066
9067 return ExceptSpec;
9068}
9069
Richard Smith1c931be2012-04-02 18:40:40 +00009070/// Determine whether the class type has any direct or indirect virtual base
9071/// classes which have a non-trivial move assignment operator.
9072static bool
9073hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9074 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9075 BaseEnd = ClassDecl->vbases_end();
9076 Base != BaseEnd; ++Base) {
9077 CXXRecordDecl *BaseClass =
9078 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9079
9080 // Try to declare the move assignment. If it would be deleted, then the
9081 // class does not have a non-trivial move assignment.
9082 if (BaseClass->needsImplicitMoveAssignment())
9083 S.DeclareImplicitMoveAssignment(BaseClass);
9084
Richard Smith426391c2012-11-16 00:53:38 +00009085 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009086 return true;
9087 }
9088
9089 return false;
9090}
9091
9092/// Determine whether the given type either has a move constructor or is
9093/// trivially copyable.
9094static bool
9095hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9096 Type = S.Context.getBaseElementType(Type);
9097
9098 // FIXME: Technically, non-trivially-copyable non-class types, such as
9099 // reference types, are supposed to return false here, but that appears
9100 // to be a standard defect.
9101 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009102 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009103 return true;
9104
9105 if (Type.isTriviallyCopyableType(S.Context))
9106 return true;
9107
9108 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009109 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9110 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009111 if (ClassDecl->needsImplicitMoveConstructor())
9112 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009113 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009114 }
9115
Richard Smithe5411b72012-12-01 02:35:44 +00009116 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9117 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009118 if (ClassDecl->needsImplicitMoveAssignment())
9119 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009120 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009121}
9122
9123/// Determine whether all non-static data members and direct or virtual bases
9124/// of class \p ClassDecl have either a move operation, or are trivially
9125/// copyable.
9126static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9127 bool IsConstructor) {
9128 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9129 BaseEnd = ClassDecl->bases_end();
9130 Base != BaseEnd; ++Base) {
9131 if (Base->isVirtual())
9132 continue;
9133
9134 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9135 return false;
9136 }
9137
9138 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9139 BaseEnd = ClassDecl->vbases_end();
9140 Base != BaseEnd; ++Base) {
9141 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9142 return false;
9143 }
9144
9145 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9146 FieldEnd = ClassDecl->field_end();
9147 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009148 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009149 return false;
9150 }
9151
9152 return true;
9153}
9154
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009155CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009156 // C++11 [class.copy]p20:
9157 // If the definition of a class X does not explicitly declare a move
9158 // assignment operator, one will be implicitly declared as defaulted
9159 // if and only if:
9160 //
9161 // - [first 4 bullets]
9162 assert(ClassDecl->needsImplicitMoveAssignment());
9163
Richard Smithafb49182012-11-29 01:34:07 +00009164 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9165 if (DSM.isAlreadyBeingDeclared())
9166 return 0;
9167
Richard Smith1c931be2012-04-02 18:40:40 +00009168 // [Checked after we build the declaration]
9169 // - the move assignment operator would not be implicitly defined as
9170 // deleted,
9171
9172 // [DR1402]:
9173 // - X has no direct or indirect virtual base class with a non-trivial
9174 // move assignment operator, and
9175 // - each of X's non-static data members and direct or virtual base classes
9176 // has a type that either has a move assignment operator or is trivially
9177 // copyable.
9178 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9179 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9180 ClassDecl->setFailedImplicitMoveAssignment();
9181 return 0;
9182 }
9183
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009184 // Note: The following rules are largely analoguous to the move
9185 // constructor rules.
9186
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009187 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9188 QualType RetType = Context.getLValueReferenceType(ArgType);
9189 ArgType = Context.getRValueReferenceType(ArgType);
9190
9191 // An implicitly-declared move assignment operator is an inline public
9192 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009193 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9194 SourceLocation ClassLoc = ClassDecl->getLocation();
9195 DeclarationNameInfo NameInfo(Name, ClassLoc);
9196 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00009197 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009198 /*TInfo=*/0,
9199 /*StorageClass=*/SC_None,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009200 /*isInline=*/true,
9201 /*isConstexpr=*/false,
9202 SourceLocation());
9203 MoveAssignment->setAccess(AS_public);
9204 MoveAssignment->setDefaulted();
9205 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009206
Richard Smithb9d0b762012-07-27 04:22:15 +00009207 // Build an exception specification pointing back at this member.
9208 FunctionProtoType::ExtProtoInfo EPI;
9209 EPI.ExceptionSpecType = EST_Unevaluated;
9210 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009211 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009212
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009213 // Add the parameter to the operator.
9214 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9215 ClassLoc, ClassLoc, /*Id=*/0,
9216 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009217 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009218 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009219
Richard Smithbc2a35d2012-12-08 08:32:28 +00009220 AddOverriddenMethods(ClassDecl, MoveAssignment);
9221
9222 MoveAssignment->setTrivial(
9223 ClassDecl->needsOverloadResolutionForMoveAssignment()
9224 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9225 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009226
9227 // C++0x [class.copy]p9:
9228 // If the definition of a class X does not explicitly declare a move
9229 // assignment operator, one will be implicitly declared as defaulted if and
9230 // only if:
9231 // [...]
9232 // - the move assignment operator would not be implicitly defined as
9233 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009234 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009235 // Cache this result so that we don't try to generate this over and over
9236 // on every lookup, leaking memory and wasting time.
9237 ClassDecl->setFailedImplicitMoveAssignment();
9238 return 0;
9239 }
9240
Richard Smithbc2a35d2012-12-08 08:32:28 +00009241 // Note that we have added this copy-assignment operator.
9242 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9243
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009244 if (Scope *S = getScopeForContext(ClassDecl))
9245 PushOnScopeChains(MoveAssignment, S, false);
9246 ClassDecl->addDecl(MoveAssignment);
9247
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009248 return MoveAssignment;
9249}
9250
9251void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9252 CXXMethodDecl *MoveAssignOperator) {
9253 assert((MoveAssignOperator->isDefaulted() &&
9254 MoveAssignOperator->isOverloadedOperator() &&
9255 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009256 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9257 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009258 "DefineImplicitMoveAssignment called for wrong function");
9259
9260 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9261
9262 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9263 MoveAssignOperator->setInvalidDecl();
9264 return;
9265 }
9266
9267 MoveAssignOperator->setUsed();
9268
Eli Friedman9a14db32012-10-18 20:14:08 +00009269 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009270 DiagnosticErrorTrap Trap(Diags);
9271
9272 // C++0x [class.copy]p28:
9273 // The implicitly-defined or move assignment operator for a non-union class
9274 // X performs memberwise move assignment of its subobjects. The direct base
9275 // classes of X are assigned first, in the order of their declaration in the
9276 // base-specifier-list, and then the immediate non-static data members of X
9277 // are assigned, in the order in which they were declared in the class
9278 // definition.
9279
9280 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009281 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009282
9283 // The parameter for the "other" object, which we are move from.
9284 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9285 QualType OtherRefType = Other->getType()->
9286 getAs<RValueReferenceType>()->getPointeeType();
9287 assert(OtherRefType.getQualifiers() == 0 &&
9288 "Bad argument type of defaulted move assignment");
9289
9290 // Our location for everything implicitly-generated.
9291 SourceLocation Loc = MoveAssignOperator->getLocation();
9292
9293 // Construct a reference to the "other" object. We'll be using this
9294 // throughout the generated ASTs.
9295 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9296 assert(OtherRef && "Reference to parameter cannot fail!");
9297 // Cast to rvalue.
9298 OtherRef = CastForMoving(*this, OtherRef);
9299
9300 // Construct the "this" pointer. We'll be using this throughout the generated
9301 // ASTs.
9302 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9303 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009304
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009305 // Assign base classes.
9306 bool Invalid = false;
9307 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9308 E = ClassDecl->bases_end(); Base != E; ++Base) {
9309 // Form the assignment:
9310 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9311 QualType BaseType = Base->getType().getUnqualifiedType();
9312 if (!BaseType->isRecordType()) {
9313 Invalid = true;
9314 continue;
9315 }
9316
9317 CXXCastPath BasePath;
9318 BasePath.push_back(Base);
9319
9320 // Construct the "from" expression, which is an implicit cast to the
9321 // appropriately-qualified base type.
9322 Expr *From = OtherRef;
9323 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009324 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009325
9326 // Dereference "this".
9327 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9328
9329 // Implicitly cast "this" to the appropriately-qualified base type.
9330 To = ImpCastExprToType(To.take(),
9331 Context.getCVRQualifiedType(BaseType,
9332 MoveAssignOperator->getTypeQualifiers()),
9333 CK_UncheckedDerivedToBase,
9334 VK_LValue, &BasePath);
9335
9336 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009337 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009338 To.get(), From,
9339 /*CopyingBaseSubobject=*/true,
9340 /*Copying=*/false);
9341 if (Move.isInvalid()) {
9342 Diag(CurrentLocation, diag::note_member_synthesized_at)
9343 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9344 MoveAssignOperator->setInvalidDecl();
9345 return;
9346 }
9347
9348 // Success! Record the move.
9349 Statements.push_back(Move.takeAs<Expr>());
9350 }
9351
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009352 // Assign non-static members.
9353 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9354 FieldEnd = ClassDecl->field_end();
9355 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009356 if (Field->isUnnamedBitfield())
9357 continue;
9358
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009359 // Check for members of reference type; we can't move those.
9360 if (Field->getType()->isReferenceType()) {
9361 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9362 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9363 Diag(Field->getLocation(), diag::note_declared_at);
9364 Diag(CurrentLocation, diag::note_member_synthesized_at)
9365 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9366 Invalid = true;
9367 continue;
9368 }
9369
9370 // Check for members of const-qualified, non-class type.
9371 QualType BaseType = Context.getBaseElementType(Field->getType());
9372 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9373 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9374 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9375 Diag(Field->getLocation(), diag::note_declared_at);
9376 Diag(CurrentLocation, diag::note_member_synthesized_at)
9377 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9378 Invalid = true;
9379 continue;
9380 }
9381
9382 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009383 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9384 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009385
9386 QualType FieldType = Field->getType().getNonReferenceType();
9387 if (FieldType->isIncompleteArrayType()) {
9388 assert(ClassDecl->hasFlexibleArrayMember() &&
9389 "Incomplete array type is not valid");
9390 continue;
9391 }
9392
9393 // Build references to the field in the object we're copying from and to.
9394 CXXScopeSpec SS; // Intentionally empty
9395 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9396 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009397 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009398 MemberLookup.resolveKind();
9399 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9400 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009401 SS, SourceLocation(), 0,
9402 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009403 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9404 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009405 SS, SourceLocation(), 0,
9406 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009407 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9408 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9409
9410 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9411 "Member reference with rvalue base must be rvalue except for reference "
9412 "members, which aren't allowed for move assignment.");
9413
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009414 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009415 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009416 To.get(), From.get(),
9417 /*CopyingBaseSubobject=*/false,
9418 /*Copying=*/false);
9419 if (Move.isInvalid()) {
9420 Diag(CurrentLocation, diag::note_member_synthesized_at)
9421 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9422 MoveAssignOperator->setInvalidDecl();
9423 return;
9424 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009425
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009426 // Success! Record the copy.
9427 Statements.push_back(Move.takeAs<Stmt>());
9428 }
9429
9430 if (!Invalid) {
9431 // Add a "return *this;"
9432 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9433
9434 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9435 if (Return.isInvalid())
9436 Invalid = true;
9437 else {
9438 Statements.push_back(Return.takeAs<Stmt>());
9439
9440 if (Trap.hasErrorOccurred()) {
9441 Diag(CurrentLocation, diag::note_member_synthesized_at)
9442 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9443 Invalid = true;
9444 }
9445 }
9446 }
9447
9448 if (Invalid) {
9449 MoveAssignOperator->setInvalidDecl();
9450 return;
9451 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009452
9453 StmtResult Body;
9454 {
9455 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009456 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009457 /*isStmtExpr=*/false);
9458 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9459 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009460 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9461
9462 if (ASTMutationListener *L = getASTMutationListener()) {
9463 L->CompletedImplicitDefinition(MoveAssignOperator);
9464 }
9465}
9466
Richard Smithb9d0b762012-07-27 04:22:15 +00009467Sema::ImplicitExceptionSpecification
9468Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9469 CXXRecordDecl *ClassDecl = MD->getParent();
9470
9471 ImplicitExceptionSpecification ExceptSpec(*this);
9472 if (ClassDecl->isInvalidDecl())
9473 return ExceptSpec;
9474
9475 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9476 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9477 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9478
Douglas Gregor0d405db2010-07-01 20:59:04 +00009479 // C++ [except.spec]p14:
9480 // An implicitly declared special member function (Clause 12) shall have an
9481 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009482 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9483 BaseEnd = ClassDecl->bases_end();
9484 Base != BaseEnd;
9485 ++Base) {
9486 // Virtual bases are handled below.
9487 if (Base->isVirtual())
9488 continue;
9489
Douglas Gregor22584312010-07-02 23:41:54 +00009490 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009491 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009492 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009493 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009494 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009495 }
9496 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9497 BaseEnd = ClassDecl->vbases_end();
9498 Base != BaseEnd;
9499 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009500 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009501 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009502 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009503 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009504 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009505 }
9506 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9507 FieldEnd = ClassDecl->field_end();
9508 Field != FieldEnd;
9509 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009510 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009511 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9512 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009513 LookupCopyingConstructor(FieldClassDecl,
9514 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009515 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009516 }
9517 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009518
Richard Smithb9d0b762012-07-27 04:22:15 +00009519 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009520}
9521
9522CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9523 CXXRecordDecl *ClassDecl) {
9524 // C++ [class.copy]p4:
9525 // If the class definition does not explicitly declare a copy
9526 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009527 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009528
Richard Smithafb49182012-11-29 01:34:07 +00009529 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9530 if (DSM.isAlreadyBeingDeclared())
9531 return 0;
9532
Sean Hunt49634cf2011-05-13 06:10:58 +00009533 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9534 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009535 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009536 if (Const)
9537 ArgType = ArgType.withConst();
9538 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009539
Richard Smith7756afa2012-06-10 05:43:50 +00009540 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9541 CXXCopyConstructor,
9542 Const);
9543
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009544 DeclarationName Name
9545 = Context.DeclarationNames.getCXXConstructorName(
9546 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009547 SourceLocation ClassLoc = ClassDecl->getLocation();
9548 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009549
9550 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009551 // member of its class.
9552 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009553 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009554 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009555 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009556 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009557 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009558
Richard Smithb9d0b762012-07-27 04:22:15 +00009559 // Build an exception specification pointing back at this member.
9560 FunctionProtoType::ExtProtoInfo EPI;
9561 EPI.ExceptionSpecType = EST_Unevaluated;
9562 EPI.ExceptionSpecDecl = CopyConstructor;
9563 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009564 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009565
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009566 // Add the parameter to the constructor.
9567 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009568 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009569 /*IdentifierInfo=*/0,
9570 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009571 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009572 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009573
Richard Smithbc2a35d2012-12-08 08:32:28 +00009574 CopyConstructor->setTrivial(
9575 ClassDecl->needsOverloadResolutionForCopyConstructor()
9576 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9577 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009578
Nico Weberafcc96a2012-01-23 03:19:29 +00009579 // C++11 [class.copy]p8:
9580 // ... If the class definition does not explicitly declare a copy
9581 // constructor, there is no user-declared move constructor, and there is no
9582 // user-declared move assignment operator, a copy constructor is implicitly
9583 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009584 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009585 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009586
Richard Smithbc2a35d2012-12-08 08:32:28 +00009587 // Note that we have declared this constructor.
9588 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9589
9590 if (Scope *S = getScopeForContext(ClassDecl))
9591 PushOnScopeChains(CopyConstructor, S, false);
9592 ClassDecl->addDecl(CopyConstructor);
9593
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009594 return CopyConstructor;
9595}
9596
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009597void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009598 CXXConstructorDecl *CopyConstructor) {
9599 assert((CopyConstructor->isDefaulted() &&
9600 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009601 !CopyConstructor->doesThisDeclarationHaveABody() &&
9602 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009603 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009604
Anders Carlsson63010a72010-04-23 16:24:12 +00009605 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009606 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009607
Eli Friedman9a14db32012-10-18 20:14:08 +00009608 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009609 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009610
David Blaikie93c86172013-01-17 05:26:25 +00009611 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009612 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009613 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009614 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009615 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009616 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009617 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009618 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9619 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009620 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009621 /*isStmtExpr=*/false)
9622 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009623 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009624 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009625
9626 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009627 if (ASTMutationListener *L = getASTMutationListener()) {
9628 L->CompletedImplicitDefinition(CopyConstructor);
9629 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009630}
9631
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009632Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009633Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9634 CXXRecordDecl *ClassDecl = MD->getParent();
9635
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009636 // C++ [except.spec]p14:
9637 // An implicitly declared special member function (Clause 12) shall have an
9638 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009639 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009640 if (ClassDecl->isInvalidDecl())
9641 return ExceptSpec;
9642
9643 // Direct base-class constructors.
9644 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9645 BEnd = ClassDecl->bases_end();
9646 B != BEnd; ++B) {
9647 if (B->isVirtual()) // Handled below.
9648 continue;
9649
9650 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9651 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009652 CXXConstructorDecl *Constructor =
9653 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009654 // If this is a deleted function, add it anyway. This might be conformant
9655 // with the standard. This might not. I'm not sure. It might not matter.
9656 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009657 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009658 }
9659 }
9660
9661 // Virtual base-class constructors.
9662 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9663 BEnd = ClassDecl->vbases_end();
9664 B != BEnd; ++B) {
9665 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9666 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009667 CXXConstructorDecl *Constructor =
9668 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009669 // If this is a deleted function, add it anyway. This might be conformant
9670 // with the standard. This might not. I'm not sure. It might not matter.
9671 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009672 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009673 }
9674 }
9675
9676 // Field constructors.
9677 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9678 FEnd = ClassDecl->field_end();
9679 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009680 QualType FieldType = Context.getBaseElementType(F->getType());
9681 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9682 CXXConstructorDecl *Constructor =
9683 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009684 // If this is a deleted function, add it anyway. This might be conformant
9685 // with the standard. This might not. I'm not sure. It might not matter.
9686 // In particular, the problem is that this function never gets called. It
9687 // might just be ill-formed because this function attempts to refer to
9688 // a deleted function here.
9689 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009690 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009691 }
9692 }
9693
9694 return ExceptSpec;
9695}
9696
9697CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9698 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009699 // C++11 [class.copy]p9:
9700 // If the definition of a class X does not explicitly declare a move
9701 // constructor, one will be implicitly declared as defaulted if and only if:
9702 //
9703 // - [first 4 bullets]
9704 assert(ClassDecl->needsImplicitMoveConstructor());
9705
Richard Smithafb49182012-11-29 01:34:07 +00009706 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9707 if (DSM.isAlreadyBeingDeclared())
9708 return 0;
9709
Richard Smith1c931be2012-04-02 18:40:40 +00009710 // [Checked after we build the declaration]
9711 // - the move assignment operator would not be implicitly defined as
9712 // deleted,
9713
9714 // [DR1402]:
9715 // - each of X's non-static data members and direct or virtual base classes
9716 // has a type that either has a move constructor or is trivially copyable.
9717 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9718 ClassDecl->setFailedImplicitMoveConstructor();
9719 return 0;
9720 }
9721
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009722 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9723 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009724
Richard Smith7756afa2012-06-10 05:43:50 +00009725 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9726 CXXMoveConstructor,
9727 false);
9728
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009729 DeclarationName Name
9730 = Context.DeclarationNames.getCXXConstructorName(
9731 Context.getCanonicalType(ClassType));
9732 SourceLocation ClassLoc = ClassDecl->getLocation();
9733 DeclarationNameInfo NameInfo(Name, ClassLoc);
9734
9735 // C++0x [class.copy]p11:
9736 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009737 // member of its class.
9738 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009739 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009740 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009741 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009742 MoveConstructor->setAccess(AS_public);
9743 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009744
Richard Smithb9d0b762012-07-27 04:22:15 +00009745 // Build an exception specification pointing back at this member.
9746 FunctionProtoType::ExtProtoInfo EPI;
9747 EPI.ExceptionSpecType = EST_Unevaluated;
9748 EPI.ExceptionSpecDecl = MoveConstructor;
9749 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009750 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009751
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009752 // Add the parameter to the constructor.
9753 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9754 ClassLoc, ClassLoc,
9755 /*IdentifierInfo=*/0,
9756 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009757 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009758 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009759
Richard Smithbc2a35d2012-12-08 08:32:28 +00009760 MoveConstructor->setTrivial(
9761 ClassDecl->needsOverloadResolutionForMoveConstructor()
9762 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9763 : ClassDecl->hasTrivialMoveConstructor());
9764
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009765 // C++0x [class.copy]p9:
9766 // If the definition of a class X does not explicitly declare a move
9767 // constructor, one will be implicitly declared as defaulted if and only if:
9768 // [...]
9769 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009770 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009771 // Cache this result so that we don't try to generate this over and over
9772 // on every lookup, leaking memory and wasting time.
9773 ClassDecl->setFailedImplicitMoveConstructor();
9774 return 0;
9775 }
9776
9777 // Note that we have declared this constructor.
9778 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9779
9780 if (Scope *S = getScopeForContext(ClassDecl))
9781 PushOnScopeChains(MoveConstructor, S, false);
9782 ClassDecl->addDecl(MoveConstructor);
9783
9784 return MoveConstructor;
9785}
9786
9787void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9788 CXXConstructorDecl *MoveConstructor) {
9789 assert((MoveConstructor->isDefaulted() &&
9790 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009791 !MoveConstructor->doesThisDeclarationHaveABody() &&
9792 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009793 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9794
9795 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9796 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9797
Eli Friedman9a14db32012-10-18 20:14:08 +00009798 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009799 DiagnosticErrorTrap Trap(Diags);
9800
David Blaikie93c86172013-01-17 05:26:25 +00009801 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009802 Trap.hasErrorOccurred()) {
9803 Diag(CurrentLocation, diag::note_member_synthesized_at)
9804 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9805 MoveConstructor->setInvalidDecl();
9806 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009807 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009808 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9809 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009810 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009811 /*isStmtExpr=*/false)
9812 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009813 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009814 }
9815
9816 MoveConstructor->setUsed();
9817
9818 if (ASTMutationListener *L = getASTMutationListener()) {
9819 L->CompletedImplicitDefinition(MoveConstructor);
9820 }
9821}
9822
Douglas Gregore4e68d42012-02-15 19:33:52 +00009823bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9824 return FD->isDeleted() &&
9825 (FD->isDefaulted() || FD->isImplicit()) &&
9826 isa<CXXMethodDecl>(FD);
9827}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009828
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009829/// \brief Mark the call operator of the given lambda closure type as "used".
9830static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9831 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009832 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009833 Lambda->lookup(
9834 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009835 CallOperator->setReferenced();
9836 CallOperator->setUsed();
9837}
9838
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009839void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9840 SourceLocation CurrentLocation,
9841 CXXConversionDecl *Conv)
9842{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009843 CXXRecordDecl *Lambda = Conv->getParent();
9844
9845 // Make sure that the lambda call operator is marked used.
9846 markLambdaCallOperatorUsed(*this, Lambda);
9847
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009848 Conv->setUsed();
9849
Eli Friedman9a14db32012-10-18 20:14:08 +00009850 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009851 DiagnosticErrorTrap Trap(Diags);
9852
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009853 // Return the address of the __invoke function.
9854 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9855 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009856 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009857 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9858 VK_LValue, Conv->getLocation()).take();
9859 assert(FunctionRef && "Can't refer to __invoke function?");
9860 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009861 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009862 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009863 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009864
9865 // Fill in the __invoke function with a dummy implementation. IR generation
9866 // will fill in the actual details.
9867 Invoke->setUsed();
9868 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009869 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009870
9871 if (ASTMutationListener *L = getASTMutationListener()) {
9872 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009873 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009874 }
9875}
9876
9877void Sema::DefineImplicitLambdaToBlockPointerConversion(
9878 SourceLocation CurrentLocation,
9879 CXXConversionDecl *Conv)
9880{
9881 Conv->setUsed();
9882
Eli Friedman9a14db32012-10-18 20:14:08 +00009883 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009884 DiagnosticErrorTrap Trap(Diags);
9885
Douglas Gregorac1303e2012-02-22 05:02:47 +00009886 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009887 Expr *This = ActOnCXXThis(CurrentLocation).take();
9888 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009889
Eli Friedman23f02672012-03-01 04:01:32 +00009890 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9891 Conv->getLocation(),
9892 Conv, DerefThis);
9893
9894 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9895 // behavior. Note that only the general conversion function does this
9896 // (since it's unusable otherwise); in the case where we inline the
9897 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009898 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009899 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9900 CK_CopyAndAutoreleaseBlockObject,
9901 BuildBlock.get(), 0, VK_RValue);
9902
9903 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009904 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009905 Conv->setInvalidDecl();
9906 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009907 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009908
Douglas Gregorac1303e2012-02-22 05:02:47 +00009909 // Create the return statement that returns the block from the conversion
9910 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009911 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009912 if (Return.isInvalid()) {
9913 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9914 Conv->setInvalidDecl();
9915 return;
9916 }
9917
9918 // Set the body of the conversion function.
9919 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009920 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009921 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009922 Conv->getLocation()));
9923
Douglas Gregorac1303e2012-02-22 05:02:47 +00009924 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009925 if (ASTMutationListener *L = getASTMutationListener()) {
9926 L->CompletedImplicitDefinition(Conv);
9927 }
9928}
9929
Douglas Gregorf52757d2012-03-10 06:53:13 +00009930/// \brief Determine whether the given list arguments contains exactly one
9931/// "real" (non-default) argument.
9932static bool hasOneRealArgument(MultiExprArg Args) {
9933 switch (Args.size()) {
9934 case 0:
9935 return false;
9936
9937 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009938 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009939 return false;
9940
9941 // fall through
9942 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009943 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009944 }
9945
9946 return false;
9947}
9948
John McCall60d7b3a2010-08-24 06:29:42 +00009949ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009950Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009951 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009952 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009953 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009954 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009955 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009956 unsigned ConstructKind,
9957 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009958 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009959
Douglas Gregor2f599792010-04-02 18:24:57 +00009960 // C++0x [class.copy]p34:
9961 // When certain criteria are met, an implementation is allowed to
9962 // omit the copy/move construction of a class object, even if the
9963 // copy/move constructor and/or destructor for the object have
9964 // side effects. [...]
9965 // - when a temporary class object that has not been bound to a
9966 // reference (12.2) would be copied/moved to a class object
9967 // with the same cv-unqualified type, the copy/move operation
9968 // can be omitted by constructing the temporary object
9969 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009970 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009971 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009972 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009973 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009974 }
Mike Stump1eb44332009-09-09 15:08:12 +00009975
9976 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009977 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009978 IsListInitialization, RequiresZeroInit,
9979 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009980}
9981
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009982/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9983/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009984ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009985Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9986 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009987 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009988 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009989 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009990 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009991 unsigned ConstructKind,
9992 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009993 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009994 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009995 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +00009996 HadMultipleCandidates,
9997 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009998 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9999 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010000}
10001
John McCall68c6c9a2010-02-02 09:10:11 +000010002void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010003 if (VD->isInvalidDecl()) return;
10004
John McCall68c6c9a2010-02-02 09:10:11 +000010005 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010006 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010007 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010008 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010009
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010010 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010011 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010012 CheckDestructorAccess(VD->getLocation(), Destructor,
10013 PDiag(diag::err_access_dtor_var)
10014 << VD->getDeclName()
10015 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010016 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010017
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010018 if (!VD->hasGlobalStorage()) return;
10019
10020 // Emit warning for non-trivial dtor in global scope (a real global,
10021 // class-static, function-static).
10022 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10023
10024 // TODO: this should be re-enabled for static locals by !CXAAtExit
10025 if (!VD->isStaticLocal())
10026 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010027}
10028
Douglas Gregor39da0b82009-09-09 23:08:42 +000010029/// \brief Given a constructor and the set of arguments provided for the
10030/// constructor, convert the arguments and add any required default arguments
10031/// to form a proper call to this constructor.
10032///
10033/// \returns true if an error occurred, false otherwise.
10034bool
10035Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10036 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010037 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010038 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010039 bool AllowExplicit,
10040 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010041 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10042 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010043 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010044
10045 const FunctionProtoType *Proto
10046 = Constructor->getType()->getAs<FunctionProtoType>();
10047 assert(Proto && "Constructor without a prototype?");
10048 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010049
10050 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010051 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010052 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010053 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010054 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010055
10056 VariadicCallType CallType =
10057 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010058 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010059 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10060 Proto, 0, Args, NumArgs, AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010061 CallType, AllowExplicit,
10062 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010063 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010064
10065 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
10066
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010067 CheckConstructorCall(Constructor,
10068 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10069 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010070 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010071
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010072 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010073}
10074
Anders Carlsson20d45d22009-12-12 00:32:00 +000010075static inline bool
10076CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10077 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010078 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010079 if (isa<NamespaceDecl>(DC)) {
10080 return SemaRef.Diag(FnDecl->getLocation(),
10081 diag::err_operator_new_delete_declared_in_namespace)
10082 << FnDecl->getDeclName();
10083 }
10084
10085 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010086 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010087 return SemaRef.Diag(FnDecl->getLocation(),
10088 diag::err_operator_new_delete_declared_static)
10089 << FnDecl->getDeclName();
10090 }
10091
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010092 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010093}
10094
Anders Carlsson156c78e2009-12-13 17:53:43 +000010095static inline bool
10096CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10097 CanQualType ExpectedResultType,
10098 CanQualType ExpectedFirstParamType,
10099 unsigned DependentParamTypeDiag,
10100 unsigned InvalidParamTypeDiag) {
10101 QualType ResultType =
10102 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10103
10104 // Check that the result type is not dependent.
10105 if (ResultType->isDependentType())
10106 return SemaRef.Diag(FnDecl->getLocation(),
10107 diag::err_operator_new_delete_dependent_result_type)
10108 << FnDecl->getDeclName() << ExpectedResultType;
10109
10110 // Check that the result type is what we expect.
10111 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10112 return SemaRef.Diag(FnDecl->getLocation(),
10113 diag::err_operator_new_delete_invalid_result_type)
10114 << FnDecl->getDeclName() << ExpectedResultType;
10115
10116 // A function template must have at least 2 parameters.
10117 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10118 return SemaRef.Diag(FnDecl->getLocation(),
10119 diag::err_operator_new_delete_template_too_few_parameters)
10120 << FnDecl->getDeclName();
10121
10122 // The function decl must have at least 1 parameter.
10123 if (FnDecl->getNumParams() == 0)
10124 return SemaRef.Diag(FnDecl->getLocation(),
10125 diag::err_operator_new_delete_too_few_parameters)
10126 << FnDecl->getDeclName();
10127
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010128 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010129 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10130 if (FirstParamType->isDependentType())
10131 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10132 << FnDecl->getDeclName() << ExpectedFirstParamType;
10133
10134 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010135 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010136 ExpectedFirstParamType)
10137 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10138 << FnDecl->getDeclName() << ExpectedFirstParamType;
10139
10140 return false;
10141}
10142
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010143static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010144CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010145 // C++ [basic.stc.dynamic.allocation]p1:
10146 // A program is ill-formed if an allocation function is declared in a
10147 // namespace scope other than global scope or declared static in global
10148 // scope.
10149 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10150 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010151
10152 CanQualType SizeTy =
10153 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10154
10155 // C++ [basic.stc.dynamic.allocation]p1:
10156 // The return type shall be void*. The first parameter shall have type
10157 // std::size_t.
10158 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10159 SizeTy,
10160 diag::err_operator_new_dependent_param_type,
10161 diag::err_operator_new_param_type))
10162 return true;
10163
10164 // C++ [basic.stc.dynamic.allocation]p1:
10165 // The first parameter shall not have an associated default argument.
10166 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010167 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010168 diag::err_operator_new_default_arg)
10169 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10170
10171 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010172}
10173
10174static bool
Richard Smith444d3842012-10-20 08:26:51 +000010175CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010176 // C++ [basic.stc.dynamic.deallocation]p1:
10177 // A program is ill-formed if deallocation functions are declared in a
10178 // namespace scope other than global scope or declared static in global
10179 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010180 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10181 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010182
10183 // C++ [basic.stc.dynamic.deallocation]p2:
10184 // Each deallocation function shall return void and its first parameter
10185 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010186 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10187 SemaRef.Context.VoidPtrTy,
10188 diag::err_operator_delete_dependent_param_type,
10189 diag::err_operator_delete_param_type))
10190 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010191
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010192 return false;
10193}
10194
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010195/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10196/// of this overloaded operator is well-formed. If so, returns false;
10197/// otherwise, emits appropriate diagnostics and returns true.
10198bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010199 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010200 "Expected an overloaded operator declaration");
10201
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010202 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10203
Mike Stump1eb44332009-09-09 15:08:12 +000010204 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010205 // The allocation and deallocation functions, operator new,
10206 // operator new[], operator delete and operator delete[], are
10207 // described completely in 3.7.3. The attributes and restrictions
10208 // found in the rest of this subclause do not apply to them unless
10209 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010210 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010211 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010212
Anders Carlssona3ccda52009-12-12 00:26:23 +000010213 if (Op == OO_New || Op == OO_Array_New)
10214 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010215
10216 // C++ [over.oper]p6:
10217 // An operator function shall either be a non-static member
10218 // function or be a non-member function and have at least one
10219 // parameter whose type is a class, a reference to a class, an
10220 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010221 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10222 if (MethodDecl->isStatic())
10223 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010224 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010225 } else {
10226 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010227 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10228 ParamEnd = FnDecl->param_end();
10229 Param != ParamEnd; ++Param) {
10230 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010231 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10232 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010233 ClassOrEnumParam = true;
10234 break;
10235 }
10236 }
10237
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010238 if (!ClassOrEnumParam)
10239 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010240 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010241 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010242 }
10243
10244 // C++ [over.oper]p8:
10245 // An operator function cannot have default arguments (8.3.6),
10246 // except where explicitly stated below.
10247 //
Mike Stump1eb44332009-09-09 15:08:12 +000010248 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010249 // (C++ [over.call]p1).
10250 if (Op != OO_Call) {
10251 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10252 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010253 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010254 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010255 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010256 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010257 }
10258 }
10259
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010260 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10261 { false, false, false }
10262#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10263 , { Unary, Binary, MemberOnly }
10264#include "clang/Basic/OperatorKinds.def"
10265 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010266
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010267 bool CanBeUnaryOperator = OperatorUses[Op][0];
10268 bool CanBeBinaryOperator = OperatorUses[Op][1];
10269 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010270
10271 // C++ [over.oper]p8:
10272 // [...] Operator functions cannot have more or fewer parameters
10273 // than the number required for the corresponding operator, as
10274 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010275 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010276 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010277 if (Op != OO_Call &&
10278 ((NumParams == 1 && !CanBeUnaryOperator) ||
10279 (NumParams == 2 && !CanBeBinaryOperator) ||
10280 (NumParams < 1) || (NumParams > 2))) {
10281 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010282 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010283 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010284 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010285 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010286 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010287 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010288 assert(CanBeBinaryOperator &&
10289 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010290 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010291 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010292
Chris Lattner416e46f2008-11-21 07:57:12 +000010293 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010294 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010295 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010296
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010297 // Overloaded operators other than operator() cannot be variadic.
10298 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010299 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010300 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010301 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010302 }
10303
10304 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010305 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10306 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010307 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010308 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010309 }
10310
10311 // C++ [over.inc]p1:
10312 // The user-defined function called operator++ implements the
10313 // prefix and postfix ++ operator. If this function is a member
10314 // function with no parameters, or a non-member function with one
10315 // parameter of class or enumeration type, it defines the prefix
10316 // increment operator ++ for objects of that type. If the function
10317 // is a member function with one parameter (which shall be of type
10318 // int) or a non-member function with two parameters (the second
10319 // of which shall be of type int), it defines the postfix
10320 // increment operator ++ for objects of that type.
10321 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10322 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10323 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010324 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010325 ParamIsInt = BT->getKind() == BuiltinType::Int;
10326
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010327 if (!ParamIsInt)
10328 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010329 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010330 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010331 }
10332
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010333 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010334}
Chris Lattner5a003a42008-12-17 07:09:26 +000010335
Sean Hunta6c058d2010-01-13 09:01:02 +000010336/// CheckLiteralOperatorDeclaration - Check whether the declaration
10337/// of this literal operator function is well-formed. If so, returns
10338/// false; otherwise, emits appropriate diagnostics and returns true.
10339bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010340 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010341 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10342 << FnDecl->getDeclName();
10343 return true;
10344 }
10345
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010346 if (FnDecl->isExternC()) {
10347 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10348 return true;
10349 }
10350
Sean Hunta6c058d2010-01-13 09:01:02 +000010351 bool Valid = false;
10352
Richard Smith36f5cfe2012-03-09 08:00:36 +000010353 // This might be the definition of a literal operator template.
10354 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10355 // This might be a specialization of a literal operator template.
10356 if (!TpDecl)
10357 TpDecl = FnDecl->getPrimaryTemplate();
10358
Sean Hunt216c2782010-04-07 23:11:06 +000010359 // template <char...> type operator "" name() is the only valid template
10360 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010361 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010362 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010363 // Must have only one template parameter
10364 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10365 if (Params->size() == 1) {
10366 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010367 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010368
Sean Hunt216c2782010-04-07 23:11:06 +000010369 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010370 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10371 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10372 Valid = true;
10373 }
10374 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010375 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010376 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010377 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10378
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010379 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010380
Sean Hunt30019c02010-04-07 22:57:35 +000010381 // unsigned long long int, long double, and any character type are allowed
10382 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010383 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10384 Context.hasSameType(T, Context.LongDoubleTy) ||
10385 Context.hasSameType(T, Context.CharTy) ||
10386 Context.hasSameType(T, Context.WCharTy) ||
10387 Context.hasSameType(T, Context.Char16Ty) ||
10388 Context.hasSameType(T, Context.Char32Ty)) {
10389 if (++Param == FnDecl->param_end())
10390 Valid = true;
10391 goto FinishedParams;
10392 }
10393
Sean Hunt30019c02010-04-07 22:57:35 +000010394 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010395 const PointerType *PT = T->getAs<PointerType>();
10396 if (!PT)
10397 goto FinishedParams;
10398 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010399 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010400 goto FinishedParams;
10401 T = T.getUnqualifiedType();
10402
10403 // Move on to the second parameter;
10404 ++Param;
10405
10406 // If there is no second parameter, the first must be a const char *
10407 if (Param == FnDecl->param_end()) {
10408 if (Context.hasSameType(T, Context.CharTy))
10409 Valid = true;
10410 goto FinishedParams;
10411 }
10412
10413 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10414 // are allowed as the first parameter to a two-parameter function
10415 if (!(Context.hasSameType(T, Context.CharTy) ||
10416 Context.hasSameType(T, Context.WCharTy) ||
10417 Context.hasSameType(T, Context.Char16Ty) ||
10418 Context.hasSameType(T, Context.Char32Ty)))
10419 goto FinishedParams;
10420
10421 // The second and final parameter must be an std::size_t
10422 T = (*Param)->getType().getUnqualifiedType();
10423 if (Context.hasSameType(T, Context.getSizeType()) &&
10424 ++Param == FnDecl->param_end())
10425 Valid = true;
10426 }
10427
10428 // FIXME: This diagnostic is absolutely terrible.
10429FinishedParams:
10430 if (!Valid) {
10431 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10432 << FnDecl->getDeclName();
10433 return true;
10434 }
10435
Richard Smitha9e88b22012-03-09 08:16:22 +000010436 // A parameter-declaration-clause containing a default argument is not
10437 // equivalent to any of the permitted forms.
10438 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10439 ParamEnd = FnDecl->param_end();
10440 Param != ParamEnd; ++Param) {
10441 if ((*Param)->hasDefaultArg()) {
10442 Diag((*Param)->getDefaultArgRange().getBegin(),
10443 diag::err_literal_operator_default_argument)
10444 << (*Param)->getDefaultArgRange();
10445 break;
10446 }
10447 }
10448
Richard Smith2fb4ae32012-03-08 02:39:21 +000010449 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010450 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10451 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010452 // C++11 [usrlit.suffix]p1:
10453 // Literal suffix identifiers that do not start with an underscore
10454 // are reserved for future standardization.
10455 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010456 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010457
Sean Hunta6c058d2010-01-13 09:01:02 +000010458 return false;
10459}
10460
Douglas Gregor074149e2009-01-05 19:45:36 +000010461/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10462/// linkage specification, including the language and (if present)
10463/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10464/// the location of the language string literal, which is provided
10465/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10466/// the '{' brace. Otherwise, this linkage specification does not
10467/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010468Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10469 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010470 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010471 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010472 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010473 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010474 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010475 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010476 Language = LinkageSpecDecl::lang_cxx;
10477 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010478 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010479 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010480 }
Mike Stump1eb44332009-09-09 15:08:12 +000010481
Chris Lattnercc98eac2008-12-17 07:13:27 +000010482 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010483
Douglas Gregor074149e2009-01-05 19:45:36 +000010484 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010485 ExternLoc, LangLoc, Language,
10486 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010487 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010488 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010489 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010490}
10491
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010492/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010493/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10494/// valid, it's the position of the closing '}' brace in a linkage
10495/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010496Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010497 Decl *LinkageSpec,
10498 SourceLocation RBraceLoc) {
10499 if (LinkageSpec) {
10500 if (RBraceLoc.isValid()) {
10501 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10502 LSDecl->setRBraceLoc(RBraceLoc);
10503 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010504 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010505 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010506 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010507}
10508
Michael Han684aa732013-02-22 17:15:32 +000010509Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10510 AttributeList *AttrList,
10511 SourceLocation SemiLoc) {
10512 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10513 // Attribute declarations appertain to empty declaration so we handle
10514 // them here.
10515 if (AttrList)
10516 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010517
Michael Han684aa732013-02-22 17:15:32 +000010518 CurContext->addDecl(ED);
10519 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010520}
10521
Douglas Gregord308e622009-05-18 20:51:54 +000010522/// \brief Perform semantic analysis for the variable declaration that
10523/// occurs within a C++ catch clause, returning the newly-created
10524/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010525VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010526 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010527 SourceLocation StartLoc,
10528 SourceLocation Loc,
10529 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010530 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010531 QualType ExDeclType = TInfo->getType();
10532
Sebastian Redl4b07b292008-12-22 19:15:10 +000010533 // Arrays and functions decay.
10534 if (ExDeclType->isArrayType())
10535 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10536 else if (ExDeclType->isFunctionType())
10537 ExDeclType = Context.getPointerType(ExDeclType);
10538
10539 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10540 // The exception-declaration shall not denote a pointer or reference to an
10541 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010542 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010543 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010544 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010545 Invalid = true;
10546 }
Douglas Gregord308e622009-05-18 20:51:54 +000010547
Sebastian Redl4b07b292008-12-22 19:15:10 +000010548 QualType BaseType = ExDeclType;
10549 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010550 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010551 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010552 BaseType = Ptr->getPointeeType();
10553 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010554 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010555 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010556 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010557 BaseType = Ref->getPointeeType();
10558 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010559 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010560 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010561 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010562 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010563 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010564
Mike Stump1eb44332009-09-09 15:08:12 +000010565 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010566 RequireNonAbstractType(Loc, ExDeclType,
10567 diag::err_abstract_type_in_decl,
10568 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010569 Invalid = true;
10570
John McCall5a180392010-07-24 00:37:23 +000010571 // Only the non-fragile NeXT runtime currently supports C++ catches
10572 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010573 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010574 QualType T = ExDeclType;
10575 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10576 T = RT->getPointeeType();
10577
10578 if (T->isObjCObjectType()) {
10579 Diag(Loc, diag::err_objc_object_catch);
10580 Invalid = true;
10581 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010582 // FIXME: should this be a test for macosx-fragile specifically?
10583 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010584 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010585 }
10586 }
10587
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010588 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010589 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010590 ExDecl->setExceptionVariable(true);
10591
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010592 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010593 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010594 Invalid = true;
10595
Douglas Gregorc41b8782011-07-06 18:14:43 +000010596 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010597 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010598 // Insulate this from anything else we might currently be parsing.
10599 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10600
Douglas Gregor6d182892010-03-05 23:38:39 +000010601 // C++ [except.handle]p16:
10602 // The object declared in an exception-declaration or, if the
10603 // exception-declaration does not specify a name, a temporary (12.2) is
10604 // copy-initialized (8.5) from the exception object. [...]
10605 // The object is destroyed when the handler exits, after the destruction
10606 // of any automatic objects initialized within the handler.
10607 //
10608 // We just pretend to initialize the object with itself, then make sure
10609 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010610 QualType initType = ExDeclType;
10611
10612 InitializedEntity entity =
10613 InitializedEntity::InitializeVariable(ExDecl);
10614 InitializationKind initKind =
10615 InitializationKind::CreateCopy(Loc, SourceLocation());
10616
10617 Expr *opaqueValue =
10618 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000010619 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10620 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000010621 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010622 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010623 else {
10624 // If the constructor used was non-trivial, set this as the
10625 // "initializer".
10626 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10627 if (!construct->getConstructor()->isTrivial()) {
10628 Expr *init = MaybeCreateExprWithCleanups(construct);
10629 ExDecl->setInit(init);
10630 }
10631
10632 // And make sure it's destructable.
10633 FinalizeVarWithDestructor(ExDecl, recordType);
10634 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010635 }
10636 }
10637
Douglas Gregord308e622009-05-18 20:51:54 +000010638 if (Invalid)
10639 ExDecl->setInvalidDecl();
10640
10641 return ExDecl;
10642}
10643
10644/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10645/// handler.
John McCalld226f652010-08-21 09:40:31 +000010646Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010647 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010648 bool Invalid = D.isInvalidType();
10649
10650 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010651 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10652 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010653 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10654 D.getIdentifierLoc());
10655 Invalid = true;
10656 }
10657
Sebastian Redl4b07b292008-12-22 19:15:10 +000010658 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010659 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010660 LookupOrdinaryName,
10661 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010662 // The scope should be freshly made just for us. There is just no way
10663 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010664 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010665 if (PrevDecl->isTemplateParameter()) {
10666 // Maybe we will complain about the shadowed template parameter.
10667 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010668 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010669 }
10670 }
10671
Chris Lattnereaaebc72009-04-25 08:06:05 +000010672 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010673 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10674 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010675 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010676 }
10677
Douglas Gregor83cb9422010-09-09 17:09:21 +000010678 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010679 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010680 D.getIdentifierLoc(),
10681 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010682 if (Invalid)
10683 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010684
Sebastian Redl4b07b292008-12-22 19:15:10 +000010685 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010686 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010687 PushOnScopeChains(ExDecl, S);
10688 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010689 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010690
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010691 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010692 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010693}
Anders Carlssonfb311762009-03-14 00:25:26 +000010694
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010695Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010696 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010697 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010698 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010699 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010700
Richard Smithe3f470a2012-07-11 22:37:56 +000010701 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10702 return 0;
10703
10704 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10705 AssertMessage, RParenLoc, false);
10706}
10707
10708Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10709 Expr *AssertExpr,
10710 StringLiteral *AssertMessage,
10711 SourceLocation RParenLoc,
10712 bool Failed) {
10713 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10714 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010715 // In a static_assert-declaration, the constant-expression shall be a
10716 // constant expression that can be contextually converted to bool.
10717 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10718 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010719 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010720
Richard Smithdaaefc52011-12-14 23:32:26 +000010721 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010722 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010723 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010724 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010725 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010726
Richard Smithe3f470a2012-07-11 22:37:56 +000010727 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010728 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010729 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010730 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010731 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010732 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010733 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010734 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010735 }
Mike Stump1eb44332009-09-09 15:08:12 +000010736
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010737 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010738 AssertExpr, AssertMessage, RParenLoc,
10739 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010740
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010741 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010742 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010743}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010744
Douglas Gregor1d869352010-04-07 16:53:43 +000010745/// \brief Perform semantic analysis of the given friend type declaration.
10746///
10747/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010748FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010749 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010750 TypeSourceInfo *TSInfo) {
10751 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10752
10753 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010754 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010755
Richard Smith6b130222011-10-18 21:39:00 +000010756 // C++03 [class.friend]p2:
10757 // An elaborated-type-specifier shall be used in a friend declaration
10758 // for a class.*
10759 //
10760 // * The class-key of the elaborated-type-specifier is required.
10761 if (!ActiveTemplateInstantiations.empty()) {
10762 // Do not complain about the form of friend template types during
10763 // template instantiation; we will already have complained when the
10764 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010765 } else {
10766 if (!T->isElaboratedTypeSpecifier()) {
10767 // If we evaluated the type to a record type, suggest putting
10768 // a tag in front.
10769 if (const RecordType *RT = T->getAs<RecordType>()) {
10770 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010771
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010772 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010773
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010774 Diag(TypeRange.getBegin(),
10775 getLangOpts().CPlusPlus11 ?
10776 diag::warn_cxx98_compat_unelaborated_friend_type :
10777 diag::ext_unelaborated_friend_type)
10778 << (unsigned) RD->getTagKind()
10779 << T
10780 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10781 InsertionText);
10782 } else {
10783 Diag(FriendLoc,
10784 getLangOpts().CPlusPlus11 ?
10785 diag::warn_cxx98_compat_nonclass_type_friend :
10786 diag::ext_nonclass_type_friend)
10787 << T
10788 << TypeRange;
10789 }
10790 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010791 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010792 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010793 diag::warn_cxx98_compat_enum_friend :
10794 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010795 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010796 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010797 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010798
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010799 // C++11 [class.friend]p3:
10800 // A friend declaration that does not declare a function shall have one
10801 // of the following forms:
10802 // friend elaborated-type-specifier ;
10803 // friend simple-type-specifier ;
10804 // friend typename-specifier ;
10805 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10806 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10807 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010808
Douglas Gregor06245bf2010-04-07 17:57:12 +000010809 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010810 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010811 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010812 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010813}
10814
John McCall9a34edb2010-10-19 01:40:49 +000010815/// Handle a friend tag declaration where the scope specifier was
10816/// templated.
10817Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10818 unsigned TagSpec, SourceLocation TagLoc,
10819 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010820 IdentifierInfo *Name,
10821 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010822 AttributeList *Attr,
10823 MultiTemplateParamsArg TempParamLists) {
10824 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10825
10826 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010827 bool Invalid = false;
10828
10829 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010830 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010831 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010832 TempParamLists.size(),
10833 /*friend*/ true,
10834 isExplicitSpecialization,
10835 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010836 if (TemplateParams->size() > 0) {
10837 // This is a declaration of a class template.
10838 if (Invalid)
10839 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010840
Eric Christopher4110e132011-07-21 05:34:24 +000010841 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10842 SS, Name, NameLoc, Attr,
10843 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010844 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010845 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010846 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010847 } else {
10848 // The "template<>" header is extraneous.
10849 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10850 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10851 isExplicitSpecialization = true;
10852 }
10853 }
10854
10855 if (Invalid) return 0;
10856
John McCall9a34edb2010-10-19 01:40:49 +000010857 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010858 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010859 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010860 isAllExplicitSpecializations = false;
10861 break;
10862 }
10863 }
10864
10865 // FIXME: don't ignore attributes.
10866
10867 // If it's explicit specializations all the way down, just forget
10868 // about the template header and build an appropriate non-templated
10869 // friend. TODO: for source fidelity, remember the headers.
10870 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010871 if (SS.isEmpty()) {
10872 bool Owned = false;
10873 bool IsDependent = false;
10874 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10875 Attr, AS_public,
10876 /*ModulePrivateLoc=*/SourceLocation(),
10877 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010878 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010879 /*ScopedEnumUsesClassTag=*/false,
10880 /*UnderlyingType=*/TypeResult());
10881 }
10882
Douglas Gregor2494dd02011-03-01 01:34:45 +000010883 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010884 ElaboratedTypeKeyword Keyword
10885 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010886 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010887 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010888 if (T.isNull())
10889 return 0;
10890
10891 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10892 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010893 DependentNameTypeLoc TL =
10894 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010895 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010896 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010897 TL.setNameLoc(NameLoc);
10898 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010899 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010900 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010901 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010902 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010903 }
10904
10905 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010906 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010907 Friend->setAccess(AS_public);
10908 CurContext->addDecl(Friend);
10909 return Friend;
10910 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010911
10912 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10913
10914
John McCall9a34edb2010-10-19 01:40:49 +000010915
10916 // Handle the case of a templated-scope friend class. e.g.
10917 // template <class T> class A<T>::B;
10918 // FIXME: we don't support these right now.
10919 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10920 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10921 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000010922 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010923 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010924 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010925 TL.setNameLoc(NameLoc);
10926
10927 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010928 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010929 Friend->setAccess(AS_public);
10930 Friend->setUnsupportedFriend(true);
10931 CurContext->addDecl(Friend);
10932 return Friend;
10933}
10934
10935
John McCalldd4a3b02009-09-16 22:47:08 +000010936/// Handle a friend type declaration. This works in tandem with
10937/// ActOnTag.
10938///
10939/// Notes on friend class templates:
10940///
10941/// We generally treat friend class declarations as if they were
10942/// declaring a class. So, for example, the elaborated type specifier
10943/// in a friend declaration is required to obey the restrictions of a
10944/// class-head (i.e. no typedefs in the scope chain), template
10945/// parameters are required to match up with simple template-ids, &c.
10946/// However, unlike when declaring a template specialization, it's
10947/// okay to refer to a template specialization without an empty
10948/// template parameter declaration, e.g.
10949/// friend class A<T>::B<unsigned>;
10950/// We permit this as a special case; if there are any template
10951/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010952/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010953Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010954 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010955 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010956
10957 assert(DS.isFriendSpecified());
10958 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10959
John McCalldd4a3b02009-09-16 22:47:08 +000010960 // Try to convert the decl specifier to a type. This works for
10961 // friend templates because ActOnTag never produces a ClassTemplateDecl
10962 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010963 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010964 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10965 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010966 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010967 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010968
Douglas Gregor6ccab972010-12-16 01:14:37 +000010969 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10970 return 0;
10971
John McCalldd4a3b02009-09-16 22:47:08 +000010972 // This is definitely an error in C++98. It's probably meant to
10973 // be forbidden in C++0x, too, but the specification is just
10974 // poorly written.
10975 //
10976 // The problem is with declarations like the following:
10977 // template <T> friend A<T>::foo;
10978 // where deciding whether a class C is a friend or not now hinges
10979 // on whether there exists an instantiation of A that causes
10980 // 'foo' to equal C. There are restrictions on class-heads
10981 // (which we declare (by fiat) elaborated friend declarations to
10982 // be) that makes this tractable.
10983 //
10984 // FIXME: handle "template <> friend class A<T>;", which
10985 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010986 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010987 Diag(Loc, diag::err_tagless_friend_type_template)
10988 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010989 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010990 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010991
John McCall02cace72009-08-28 07:59:38 +000010992 // C++98 [class.friend]p1: A friend of a class is a function
10993 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010994 // This is fixed in DR77, which just barely didn't make the C++03
10995 // deadline. It's also a very silly restriction that seriously
10996 // affects inner classes and which nobody else seems to implement;
10997 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010998 //
10999 // But note that we could warn about it: it's always useless to
11000 // friend one of your own members (it's not, however, worthless to
11001 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011002
John McCalldd4a3b02009-09-16 22:47:08 +000011003 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011004 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011005 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011006 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011007 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011008 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011009 DS.getFriendSpecLoc());
11010 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011011 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011012
11013 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011014 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011015
John McCalldd4a3b02009-09-16 22:47:08 +000011016 D->setAccess(AS_public);
11017 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011018
John McCalld226f652010-08-21 09:40:31 +000011019 return D;
John McCall02cace72009-08-28 07:59:38 +000011020}
11021
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011022NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11023 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011024 const DeclSpec &DS = D.getDeclSpec();
11025
11026 assert(DS.isFriendSpecified());
11027 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11028
11029 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011030 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011031
11032 // C++ [class.friend]p1
11033 // A friend of a class is a function or class....
11034 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011035 // It *doesn't* see through dependent types, which is correct
11036 // according to [temp.arg.type]p3:
11037 // If a declaration acquires a function type through a
11038 // type dependent on a template-parameter and this causes
11039 // a declaration that does not use the syntactic form of a
11040 // function declarator to have a function type, the program
11041 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011042 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011043 Diag(Loc, diag::err_unexpected_friend);
11044
11045 // It might be worthwhile to try to recover by creating an
11046 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011047 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011048 }
11049
11050 // C++ [namespace.memdef]p3
11051 // - If a friend declaration in a non-local class first declares a
11052 // class or function, the friend class or function is a member
11053 // of the innermost enclosing namespace.
11054 // - The name of the friend is not found by simple name lookup
11055 // until a matching declaration is provided in that namespace
11056 // scope (either before or after the class declaration granting
11057 // friendship).
11058 // - If a friend function is called, its name may be found by the
11059 // name lookup that considers functions from namespaces and
11060 // classes associated with the types of the function arguments.
11061 // - When looking for a prior declaration of a class or a function
11062 // declared as a friend, scopes outside the innermost enclosing
11063 // namespace scope are not considered.
11064
John McCall337ec3d2010-10-12 23:13:28 +000011065 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011066 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11067 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011068 assert(Name);
11069
Douglas Gregor6ccab972010-12-16 01:14:37 +000011070 // Check for unexpanded parameter packs.
11071 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11072 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11073 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11074 return 0;
11075
John McCall67d1a672009-08-06 02:15:43 +000011076 // The context we found the declaration in, or in which we should
11077 // create the declaration.
11078 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011079 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011080 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011081 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011082
John McCall337ec3d2010-10-12 23:13:28 +000011083 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000011084
John McCall337ec3d2010-10-12 23:13:28 +000011085 // There are four cases here.
11086 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000011087 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000011088 // there as appropriate.
11089 // Recover from invalid scope qualifiers as if they just weren't there.
11090 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000011091 // C++0x [namespace.memdef]p3:
11092 // If the name in a friend declaration is neither qualified nor
11093 // a template-id and the declaration is a function or an
11094 // elaborated-type-specifier, the lookup to determine whether
11095 // the entity has been previously declared shall not consider
11096 // any scopes outside the innermost enclosing namespace.
11097 // C++0x [class.friend]p11:
11098 // If a friend declaration appears in a local class and the name
11099 // specified is an unqualified name, a prior declaration is
11100 // looked up without considering scopes that are outside the
11101 // innermost enclosing non-class scope. For a friend function
11102 // declaration, if there is no prior declaration, the program is
11103 // ill-formed.
11104 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000011105 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011106
John McCall29ae6e52010-10-13 05:45:15 +000011107 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011108 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011109
Rafael Espindola11dc6342013-04-25 20:12:36 +000011110 // Skip class contexts. If someone can cite chapter and verse
11111 // for this behavior, that would be nice --- it's what GCC and
11112 // EDG do, and it seems like a reasonable intent, but the spec
11113 // really only says that checks for unqualified existing
11114 // declarations should stop at the nearest enclosing namespace,
11115 // not that they should only consider the nearest enclosing
11116 // namespace.
11117 while (DC->isRecord())
11118 DC = DC->getParent();
11119
11120 DeclContext *LookupDC = DC;
11121 while (LookupDC->isTransparentContext())
11122 LookupDC = LookupDC->getParent();
11123
11124 while (true) {
11125 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011126
11127 // TODO: decide what we think about using declarations.
Rafael Espindola11dc6342013-04-25 20:12:36 +000011128 if (isLocal)
John McCall67d1a672009-08-06 02:15:43 +000011129 break;
John McCall29ae6e52010-10-13 05:45:15 +000011130
Rafael Espindola11dc6342013-04-25 20:12:36 +000011131 if (!Previous.empty()) {
11132 DC = LookupDC;
11133 break;
John McCall8a407372010-10-14 22:22:28 +000011134 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011135
11136 if (isTemplateId) {
11137 if (isa<TranslationUnitDecl>(LookupDC)) break;
11138 } else {
11139 if (LookupDC->isFileContext()) break;
11140 }
11141 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011142 }
11143
John McCall380aaa42010-10-13 06:22:15 +000011144 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011145
Douglas Gregor883af832011-10-10 01:11:59 +000011146 // C++ [class.friend]p6:
11147 // A function can be defined in a friend declaration of a class if and
11148 // only if the class is a non-local class (9.8), the function name is
11149 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011150 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011151 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11152 }
11153
John McCall337ec3d2010-10-12 23:13:28 +000011154 // - There's a non-dependent scope specifier, in which case we
11155 // compute it and do a previous lookup there for a function
11156 // or function template.
11157 } else if (!SS.getScopeRep()->isDependent()) {
11158 DC = computeDeclContext(SS);
11159 if (!DC) return 0;
11160
11161 if (RequireCompleteDeclContext(SS, DC)) return 0;
11162
11163 LookupQualifiedName(Previous, DC);
11164
11165 // Ignore things found implicitly in the wrong scope.
11166 // TODO: better diagnostics for this case. Suggesting the right
11167 // qualified scope would be nice...
11168 LookupResult::Filter F = Previous.makeFilter();
11169 while (F.hasNext()) {
11170 NamedDecl *D = F.next();
11171 if (!DC->InEnclosingNamespaceSetOf(
11172 D->getDeclContext()->getRedeclContext()))
11173 F.erase();
11174 }
11175 F.done();
11176
11177 if (Previous.empty()) {
11178 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011179 Diag(Loc, diag::err_qualified_friend_not_found)
11180 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011181 return 0;
11182 }
11183
11184 // C++ [class.friend]p1: A friend of a class is a function or
11185 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011186 if (DC->Equals(CurContext))
11187 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011188 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011189 diag::warn_cxx98_compat_friend_is_member :
11190 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011191
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011192 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011193 // C++ [class.friend]p6:
11194 // A function can be defined in a friend declaration of a class if and
11195 // only if the class is a non-local class (9.8), the function name is
11196 // unqualified, and the function has namespace scope.
11197 SemaDiagnosticBuilder DB
11198 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11199
11200 DB << SS.getScopeRep();
11201 if (DC->isFileContext())
11202 DB << FixItHint::CreateRemoval(SS.getRange());
11203 SS.clear();
11204 }
John McCall337ec3d2010-10-12 23:13:28 +000011205
11206 // - There's a scope specifier that does not match any template
11207 // parameter lists, in which case we use some arbitrary context,
11208 // create a method or method template, and wait for instantiation.
11209 // - There's a scope specifier that does match some template
11210 // parameter lists, which we don't handle right now.
11211 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011212 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011213 // C++ [class.friend]p6:
11214 // A function can be defined in a friend declaration of a class if and
11215 // only if the class is a non-local class (9.8), the function name is
11216 // unqualified, and the function has namespace scope.
11217 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11218 << SS.getScopeRep();
11219 }
11220
John McCall337ec3d2010-10-12 23:13:28 +000011221 DC = CurContext;
11222 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011223 }
Douglas Gregor883af832011-10-10 01:11:59 +000011224
John McCall29ae6e52010-10-13 05:45:15 +000011225 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011226 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011227 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11228 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11229 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011230 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011231 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11232 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011233 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011234 }
John McCall67d1a672009-08-06 02:15:43 +000011235 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011236
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011237 // FIXME: This is an egregious hack to cope with cases where the scope stack
11238 // does not contain the declaration context, i.e., in an out-of-line
11239 // definition of a class.
11240 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11241 if (!DCScope) {
11242 FakeDCScope.setEntity(DC);
11243 DCScope = &FakeDCScope;
11244 }
11245
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011246 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011247 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011248 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011249 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011250
Douglas Gregor182ddf02009-09-28 00:08:27 +000011251 assert(ND->getDeclContext() == DC);
11252 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011253
John McCallab88d972009-08-31 22:39:49 +000011254 // Add the function declaration to the appropriate lookup tables,
11255 // adjusting the redeclarations list as necessary. We don't
11256 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011257 //
John McCallab88d972009-08-31 22:39:49 +000011258 // Also update the scope-based lookup if the target context's
11259 // lookup context is in lexical scope.
11260 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011261 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011262 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011263 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011264 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011265 }
John McCall02cace72009-08-28 07:59:38 +000011266
11267 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011268 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011269 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011270 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011271 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011272
John McCall1f2e1a92012-08-10 03:15:35 +000011273 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011274 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011275 } else {
11276 if (DC->isRecord()) CheckFriendAccess(ND);
11277
John McCall6102ca12010-10-16 06:59:13 +000011278 FunctionDecl *FD;
11279 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11280 FD = FTD->getTemplatedDecl();
11281 else
11282 FD = cast<FunctionDecl>(ND);
11283
11284 // Mark templated-scope function declarations as unsupported.
11285 if (FD->getNumTemplateParameterLists())
11286 FrD->setUnsupportedFriend(true);
11287 }
John McCall337ec3d2010-10-12 23:13:28 +000011288
John McCalld226f652010-08-21 09:40:31 +000011289 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011290}
11291
John McCalld226f652010-08-21 09:40:31 +000011292void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11293 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011294
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011295 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011296 if (!Fn) {
11297 Diag(DelLoc, diag::err_deleted_non_function);
11298 return;
11299 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011300
Douglas Gregoref96ee02012-01-14 16:38:05 +000011301 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011302 // Don't consider the implicit declaration we generate for explicit
11303 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011304 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11305 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011306 Diag(DelLoc, diag::err_deleted_decl_not_first);
11307 Diag(Prev->getLocation(), diag::note_previous_declaration);
11308 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011309 // If the declaration wasn't the first, we delete the function anyway for
11310 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011311 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011312 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011313
11314 if (Fn->isDeleted())
11315 return;
11316
11317 // See if we're deleting a function which is already known to override a
11318 // non-deleted virtual function.
11319 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11320 bool IssuedDiagnostic = false;
11321 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11322 E = MD->end_overridden_methods();
11323 I != E; ++I) {
11324 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11325 if (!IssuedDiagnostic) {
11326 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11327 IssuedDiagnostic = true;
11328 }
11329 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11330 }
11331 }
11332 }
11333
Sean Hunt10620eb2011-05-06 20:44:56 +000011334 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011335}
Sebastian Redl13e88542009-04-27 21:33:24 +000011336
Sean Hunte4246a62011-05-12 06:15:49 +000011337void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011338 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011339
11340 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011341 if (MD->getParent()->isDependentType()) {
11342 MD->setDefaulted();
11343 MD->setExplicitlyDefaulted();
11344 return;
11345 }
11346
Sean Hunte4246a62011-05-12 06:15:49 +000011347 CXXSpecialMember Member = getSpecialMember(MD);
11348 if (Member == CXXInvalid) {
11349 Diag(DefaultLoc, diag::err_default_special_members);
11350 return;
11351 }
11352
11353 MD->setDefaulted();
11354 MD->setExplicitlyDefaulted();
11355
Sean Huntcd10dec2011-05-23 23:14:04 +000011356 // If this definition appears within the record, do the checking when
11357 // the record is complete.
11358 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011359 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011360 // Find the uninstantiated declaration that actually had the '= default'
11361 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011362 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011363
Richard Smith12fef492013-03-27 00:22:47 +000011364 // If the method was defaulted on its first declaration, we will have
11365 // already performed the checking in CheckCompletedCXXClass. Such a
11366 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011367 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011368 return;
11369
Richard Smithb9d0b762012-07-27 04:22:15 +000011370 CheckExplicitlyDefaultedSpecialMember(MD);
11371
Richard Smith1d28caf2012-12-11 01:14:52 +000011372 // The exception specification is needed because we are defining the
11373 // function.
11374 ResolveExceptionSpec(DefaultLoc,
11375 MD->getType()->castAs<FunctionProtoType>());
11376
Sean Hunte4246a62011-05-12 06:15:49 +000011377 switch (Member) {
11378 case CXXDefaultConstructor: {
11379 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011380 if (!CD->isInvalidDecl())
11381 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11382 break;
11383 }
11384
11385 case CXXCopyConstructor: {
11386 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011387 if (!CD->isInvalidDecl())
11388 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011389 break;
11390 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011391
Sean Hunt2b188082011-05-14 05:23:28 +000011392 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011393 if (!MD->isInvalidDecl())
11394 DefineImplicitCopyAssignment(DefaultLoc, MD);
11395 break;
11396 }
11397
Sean Huntcb45a0f2011-05-12 22:46:25 +000011398 case CXXDestructor: {
11399 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011400 if (!DD->isInvalidDecl())
11401 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011402 break;
11403 }
11404
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011405 case CXXMoveConstructor: {
11406 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011407 if (!CD->isInvalidDecl())
11408 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011409 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011410 }
Sean Hunt82713172011-05-25 23:16:36 +000011411
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011412 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011413 if (!MD->isInvalidDecl())
11414 DefineImplicitMoveAssignment(DefaultLoc, MD);
11415 break;
11416 }
11417
11418 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011419 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011420 }
11421 } else {
11422 Diag(DefaultLoc, diag::err_default_special_members);
11423 }
11424}
11425
Sebastian Redl13e88542009-04-27 21:33:24 +000011426static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011427 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011428 Stmt *SubStmt = *CI;
11429 if (!SubStmt)
11430 continue;
11431 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011432 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011433 diag::err_return_in_constructor_handler);
11434 if (!isa<Expr>(SubStmt))
11435 SearchForReturnInStmt(Self, SubStmt);
11436 }
11437}
11438
11439void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11440 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11441 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11442 SearchForReturnInStmt(*this, Handler);
11443 }
11444}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011445
David Blaikie299adab2013-01-18 23:03:15 +000011446bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011447 const CXXMethodDecl *Old) {
11448 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11449 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11450
11451 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11452
11453 // If the calling conventions match, everything is fine
11454 if (NewCC == OldCC)
11455 return false;
11456
11457 // If either of the calling conventions are set to "default", we need to pick
11458 // something more sensible based on the target. This supports code where the
11459 // one method explicitly sets thiscall, and another has no explicit calling
11460 // convention.
11461 CallingConv Default =
11462 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11463 if (NewCC == CC_Default)
11464 NewCC = Default;
11465 if (OldCC == CC_Default)
11466 OldCC = Default;
11467
11468 // If the calling conventions still don't match, then report the error
11469 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011470 Diag(New->getLocation(),
11471 diag::err_conflicting_overriding_cc_attributes)
11472 << New->getDeclName() << New->getType() << Old->getType();
11473 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11474 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011475 }
11476
11477 return false;
11478}
11479
Mike Stump1eb44332009-09-09 15:08:12 +000011480bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011481 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011482 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11483 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011484
Chandler Carruth73857792010-02-15 11:53:20 +000011485 if (Context.hasSameType(NewTy, OldTy) ||
11486 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011487 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011488
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011489 // Check if the return types are covariant
11490 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011491
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011492 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011493 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11494 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011495 NewClassTy = NewPT->getPointeeType();
11496 OldClassTy = OldPT->getPointeeType();
11497 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011498 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11499 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11500 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11501 NewClassTy = NewRT->getPointeeType();
11502 OldClassTy = OldRT->getPointeeType();
11503 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011504 }
11505 }
Mike Stump1eb44332009-09-09 15:08:12 +000011506
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011507 // The return types aren't either both pointers or references to a class type.
11508 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011509 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011510 diag::err_different_return_type_for_overriding_virtual_function)
11511 << New->getDeclName() << NewTy << OldTy;
11512 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011513
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011514 return true;
11515 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011516
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011517 // C++ [class.virtual]p6:
11518 // If the return type of D::f differs from the return type of B::f, the
11519 // class type in the return type of D::f shall be complete at the point of
11520 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011521 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11522 if (!RT->isBeingDefined() &&
11523 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011524 diag::err_covariant_return_incomplete,
11525 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011526 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011527 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011528
Douglas Gregora4923eb2009-11-16 21:35:15 +000011529 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011530 // Check if the new class derives from the old class.
11531 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11532 Diag(New->getLocation(),
11533 diag::err_covariant_return_not_derived)
11534 << New->getDeclName() << NewTy << OldTy;
11535 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11536 return true;
11537 }
Mike Stump1eb44332009-09-09 15:08:12 +000011538
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011539 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011540 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011541 diag::err_covariant_return_inaccessible_base,
11542 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11543 // FIXME: Should this point to the return type?
11544 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011545 // FIXME: this note won't trigger for delayed access control
11546 // diagnostics, and it's impossible to get an undelayed error
11547 // here from access control during the original parse because
11548 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011549 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11550 return true;
11551 }
11552 }
Mike Stump1eb44332009-09-09 15:08:12 +000011553
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011554 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011555 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011556 Diag(New->getLocation(),
11557 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011558 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011559 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
11564 // The new class type must have the same or less qualifiers as the old type.
11565 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11566 Diag(New->getLocation(),
11567 diag::err_covariant_return_type_class_type_more_qualified)
11568 << New->getDeclName() << NewTy << OldTy;
11569 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11570 return true;
11571 };
Mike Stump1eb44332009-09-09 15:08:12 +000011572
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011573 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011574}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011575
Douglas Gregor4ba31362009-12-01 17:24:26 +000011576/// \brief Mark the given method pure.
11577///
11578/// \param Method the method to be marked pure.
11579///
11580/// \param InitRange the source range that covers the "0" initializer.
11581bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011582 SourceLocation EndLoc = InitRange.getEnd();
11583 if (EndLoc.isValid())
11584 Method->setRangeEnd(EndLoc);
11585
Douglas Gregor4ba31362009-12-01 17:24:26 +000011586 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11587 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011588 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011589 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011590
11591 if (!Method->isInvalidDecl())
11592 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11593 << Method->getDeclName() << InitRange;
11594 return true;
11595}
11596
Douglas Gregor552e2992012-02-21 02:22:07 +000011597/// \brief Determine whether the given declaration is a static data member.
11598static bool isStaticDataMember(Decl *D) {
11599 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11600 if (!Var)
11601 return false;
11602
11603 return Var->isStaticDataMember();
11604}
John McCall731ad842009-12-19 09:28:58 +000011605/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11606/// an initializer for the out-of-line declaration 'Dcl'. The scope
11607/// is a fresh scope pushed for just this purpose.
11608///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011609/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11610/// static data member of class X, names should be looked up in the scope of
11611/// class X.
John McCalld226f652010-08-21 09:40:31 +000011612void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011613 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011614 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011615
John McCall731ad842009-12-19 09:28:58 +000011616 // We should only get called for declarations with scope specifiers, like:
11617 // int foo::bar;
11618 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011619 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011620
11621 // If we are parsing the initializer for a static data member, push a
11622 // new expression evaluation context that is associated with this static
11623 // data member.
11624 if (isStaticDataMember(D))
11625 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011626}
11627
11628/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011629/// initializer for the out-of-line declaration 'D'.
11630void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011631 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011632 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011633
Douglas Gregor552e2992012-02-21 02:22:07 +000011634 if (isStaticDataMember(D))
11635 PopExpressionEvaluationContext();
11636
John McCall731ad842009-12-19 09:28:58 +000011637 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011638 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011639}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011640
11641/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11642/// C++ if/switch/while/for statement.
11643/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011644DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011645 // C++ 6.4p2:
11646 // The declarator shall not specify a function or an array.
11647 // The type-specifier-seq shall not contain typedef and shall not declare a
11648 // new class or enumeration.
11649 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11650 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011651
11652 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011653 if (!Dcl)
11654 return true;
11655
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011656 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11657 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011658 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011659 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011660 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011661
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011662 return Dcl;
11663}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011664
Douglas Gregordfe65432011-07-28 19:11:31 +000011665void Sema::LoadExternalVTableUses() {
11666 if (!ExternalSource)
11667 return;
11668
11669 SmallVector<ExternalVTableUse, 4> VTables;
11670 ExternalSource->ReadUsedVTables(VTables);
11671 SmallVector<VTableUse, 4> NewUses;
11672 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11673 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11674 = VTablesUsed.find(VTables[I].Record);
11675 // Even if a definition wasn't required before, it may be required now.
11676 if (Pos != VTablesUsed.end()) {
11677 if (!Pos->second && VTables[I].DefinitionRequired)
11678 Pos->second = true;
11679 continue;
11680 }
11681
11682 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11683 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11684 }
11685
11686 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11687}
11688
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011689void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11690 bool DefinitionRequired) {
11691 // Ignore any vtable uses in unevaluated operands or for classes that do
11692 // not have a vtable.
11693 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000011694 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011695 return;
11696
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011697 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011698 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011699 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11700 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11701 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11702 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011703 // If we already had an entry, check to see if we are promoting this vtable
11704 // to required a definition. If so, we need to reappend to the VTableUses
11705 // list, since we may have already processed the first entry.
11706 if (DefinitionRequired && !Pos.first->second) {
11707 Pos.first->second = true;
11708 } else {
11709 // Otherwise, we can early exit.
11710 return;
11711 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011712 }
11713
11714 // Local classes need to have their virtual members marked
11715 // immediately. For all other classes, we mark their virtual members
11716 // at the end of the translation unit.
11717 if (Class->isLocalClass())
11718 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011719 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011720 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011721}
11722
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011723bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011724 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011725 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011726 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011727
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011728 // Note: The VTableUses vector could grow as a result of marking
11729 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011730 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011731 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011732 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011733 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011734 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011735 if (!Class)
11736 continue;
11737
11738 SourceLocation Loc = VTableUses[I].second;
11739
Richard Smithb9d0b762012-07-27 04:22:15 +000011740 bool DefineVTable = true;
11741
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011742 // If this class has a key function, but that key function is
11743 // defined in another translation unit, we don't need to emit the
11744 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011745 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011746 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011747 switch (KeyFunction->getTemplateSpecializationKind()) {
11748 case TSK_Undeclared:
11749 case TSK_ExplicitSpecialization:
11750 case TSK_ExplicitInstantiationDeclaration:
11751 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011752 DefineVTable = false;
11753 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011754
11755 case TSK_ExplicitInstantiationDefinition:
11756 case TSK_ImplicitInstantiation:
11757 // We will be instantiating the key function.
11758 break;
11759 }
11760 } else if (!KeyFunction) {
11761 // If we have a class with no key function that is the subject
11762 // of an explicit instantiation declaration, suppress the
11763 // vtable; it will live with the explicit instantiation
11764 // definition.
11765 bool IsExplicitInstantiationDeclaration
11766 = Class->getTemplateSpecializationKind()
11767 == TSK_ExplicitInstantiationDeclaration;
11768 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11769 REnd = Class->redecls_end();
11770 R != REnd; ++R) {
11771 TemplateSpecializationKind TSK
11772 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11773 if (TSK == TSK_ExplicitInstantiationDeclaration)
11774 IsExplicitInstantiationDeclaration = true;
11775 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11776 IsExplicitInstantiationDeclaration = false;
11777 break;
11778 }
11779 }
11780
11781 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011782 DefineVTable = false;
11783 }
11784
11785 // The exception specifications for all virtual members may be needed even
11786 // if we are not providing an authoritative form of the vtable in this TU.
11787 // We may choose to emit it available_externally anyway.
11788 if (!DefineVTable) {
11789 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11790 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011791 }
11792
11793 // Mark all of the virtual members of this class as referenced, so
11794 // that we can build a vtable. Then, tell the AST consumer that a
11795 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011796 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011797 MarkVirtualMembersReferenced(Loc, Class);
11798 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11799 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11800
11801 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola531db822013-03-07 02:00:27 +000011802 if (Class->hasExternalLinkage() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011803 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011804 const FunctionDecl *KeyFunctionDef = 0;
11805 if (!KeyFunction ||
11806 (KeyFunction->hasBody(KeyFunctionDef) &&
11807 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011808 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11809 TSK_ExplicitInstantiationDefinition
11810 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11811 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011812 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011813 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011814 VTableUses.clear();
11815
Douglas Gregor78844032011-04-22 22:25:37 +000011816 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011817}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011818
Richard Smithb9d0b762012-07-27 04:22:15 +000011819void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11820 const CXXRecordDecl *RD) {
11821 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11822 E = RD->method_end(); I != E; ++I)
11823 if ((*I)->isVirtual() && !(*I)->isPure())
11824 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11825}
11826
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011827void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11828 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011829 // Mark all functions which will appear in RD's vtable as used.
11830 CXXFinalOverriderMap FinalOverriders;
11831 RD->getFinalOverriders(FinalOverriders);
11832 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11833 E = FinalOverriders.end();
11834 I != E; ++I) {
11835 for (OverridingMethods::const_iterator OI = I->second.begin(),
11836 OE = I->second.end();
11837 OI != OE; ++OI) {
11838 assert(OI->second.size() > 0 && "no final overrider");
11839 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011840
Richard Smithff817f72012-07-07 06:59:51 +000011841 // C++ [basic.def.odr]p2:
11842 // [...] A virtual member function is used if it is not pure. [...]
11843 if (!Overrider->isPure())
11844 MarkFunctionReferenced(Loc, Overrider);
11845 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011846 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011847
11848 // Only classes that have virtual bases need a VTT.
11849 if (RD->getNumVBases() == 0)
11850 return;
11851
11852 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11853 e = RD->bases_end(); i != e; ++i) {
11854 const CXXRecordDecl *Base =
11855 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011856 if (Base->getNumVBases() == 0)
11857 continue;
11858 MarkVirtualMembersReferenced(Loc, Base);
11859 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011860}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011861
11862/// SetIvarInitializers - This routine builds initialization ASTs for the
11863/// Objective-C implementation whose ivars need be initialized.
11864void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011865 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011866 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011867 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011868 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011869 CollectIvarsToConstructOrDestruct(OID, ivars);
11870 if (ivars.empty())
11871 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011872 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011873 for (unsigned i = 0; i < ivars.size(); i++) {
11874 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011875 if (Field->isInvalidDecl())
11876 continue;
11877
Sean Huntcbb67482011-01-08 20:30:50 +000011878 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011879 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11880 InitializationKind InitKind =
11881 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11882
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000011883 InitializationSequence InitSeq(*this, InitEntity, InitKind, MultiExprArg());
John McCall60d7b3a2010-08-24 06:29:42 +000011884 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011885 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011886 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011887 // Note, MemberInit could actually come back empty if no initialization
11888 // is required (e.g., because it would call a trivial default constructor)
11889 if (!MemberInit.get() || MemberInit.isInvalid())
11890 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011891
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011892 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011893 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11894 SourceLocation(),
11895 MemberInit.takeAs<Expr>(),
11896 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011897 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011898
11899 // Be sure that the destructor is accessible and is marked as referenced.
11900 if (const RecordType *RecordTy
11901 = Context.getBaseElementType(Field->getType())
11902 ->getAs<RecordType>()) {
11903 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011904 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011905 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011906 CheckDestructorAccess(Field->getLocation(), Destructor,
11907 PDiag(diag::err_access_dtor_ivar)
11908 << Context.getBaseElementType(Field->getType()));
11909 }
11910 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011911 }
11912 ObjCImplementation->setIvarInitializers(Context,
11913 AllToInit.data(), AllToInit.size());
11914 }
11915}
Sean Huntfe57eef2011-05-04 05:57:24 +000011916
Sean Huntebcbe1d2011-05-04 23:29:54 +000011917static
11918void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11919 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11920 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11921 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11922 Sema &S) {
11923 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11924 CE = Current.end();
11925 if (Ctor->isInvalidDecl())
11926 return;
11927
Richard Smitha8eaf002012-08-23 06:16:52 +000011928 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11929
11930 // Target may not be determinable yet, for instance if this is a dependent
11931 // call in an uninstantiated template.
11932 if (Target) {
11933 const FunctionDecl *FNTarget = 0;
11934 (void)Target->hasBody(FNTarget);
11935 Target = const_cast<CXXConstructorDecl*>(
11936 cast_or_null<CXXConstructorDecl>(FNTarget));
11937 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011938
11939 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11940 // Avoid dereferencing a null pointer here.
11941 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11942
11943 if (!Current.insert(Canonical))
11944 return;
11945
11946 // We know that beyond here, we aren't chaining into a cycle.
11947 if (!Target || !Target->isDelegatingConstructor() ||
11948 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11949 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11950 Valid.insert(*CI);
11951 Current.clear();
11952 // We've hit a cycle.
11953 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11954 Current.count(TCanonical)) {
11955 // If we haven't diagnosed this cycle yet, do so now.
11956 if (!Invalid.count(TCanonical)) {
11957 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011958 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011959 << Ctor;
11960
Richard Smitha8eaf002012-08-23 06:16:52 +000011961 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011962 if (TCanonical != Canonical)
11963 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11964
11965 CXXConstructorDecl *C = Target;
11966 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011967 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011968 (void)C->getTargetConstructor()->hasBody(FNTarget);
11969 assert(FNTarget && "Ctor cycle through bodiless function");
11970
Richard Smitha8eaf002012-08-23 06:16:52 +000011971 C = const_cast<CXXConstructorDecl*>(
11972 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011973 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11974 }
11975 }
11976
11977 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11978 Invalid.insert(*CI);
11979 Current.clear();
11980 } else {
11981 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11982 }
11983}
11984
11985
Sean Huntfe57eef2011-05-04 05:57:24 +000011986void Sema::CheckDelegatingCtorCycles() {
11987 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11988
Sean Huntebcbe1d2011-05-04 23:29:54 +000011989 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11990 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011991
Douglas Gregor0129b562011-07-27 21:57:17 +000011992 for (DelegatingCtorDeclsType::iterator
11993 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011994 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011995 I != E; ++I)
11996 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011997
11998 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11999 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012000}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012001
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012002namespace {
12003 /// \brief AST visitor that finds references to the 'this' expression.
12004 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12005 Sema &S;
12006
12007 public:
12008 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12009
12010 bool VisitCXXThisExpr(CXXThisExpr *E) {
12011 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12012 << E->isImplicit();
12013 return false;
12014 }
12015 };
12016}
12017
12018bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12019 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12020 if (!TSInfo)
12021 return false;
12022
12023 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012024 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012025 if (!ProtoTL)
12026 return false;
12027
12028 // C++11 [expr.prim.general]p3:
12029 // [The expression this] shall not appear before the optional
12030 // cv-qualifier-seq and it shall not appear within the declaration of a
12031 // static member function (although its type and value category are defined
12032 // within a static member function as they are within a non-static member
12033 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012034 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012035 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012036 FindCXXThisExpr Finder(*this);
12037
12038 // If the return type came after the cv-qualifier-seq, check it now.
12039 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012040 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012041 return true;
12042
12043 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012044 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12045 return true;
12046
12047 return checkThisInStaticMemberFunctionAttributes(Method);
12048}
12049
12050bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12051 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12052 if (!TSInfo)
12053 return false;
12054
12055 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012056 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012057 if (!ProtoTL)
12058 return false;
12059
David Blaikie39e6ab42013-02-18 22:06:02 +000012060 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012061 FindCXXThisExpr Finder(*this);
12062
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012063 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012064 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012065 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012066 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012067 case EST_DynamicNone:
12068 case EST_MSAny:
12069 case EST_None:
12070 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012071
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012072 case EST_ComputedNoexcept:
12073 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12074 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012075
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012076 case EST_Dynamic:
12077 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012078 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012079 E != EEnd; ++E) {
12080 if (!Finder.TraverseType(*E))
12081 return true;
12082 }
12083 break;
12084 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012085
12086 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012087}
12088
12089bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12090 FindCXXThisExpr Finder(*this);
12091
12092 // Check attributes.
12093 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12094 A != AEnd; ++A) {
12095 // FIXME: This should be emitted by tblgen.
12096 Expr *Arg = 0;
12097 ArrayRef<Expr *> Args;
12098 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12099 Arg = G->getArg();
12100 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12101 Arg = G->getArg();
12102 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12103 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12104 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12105 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12106 else if (ExclusiveLockFunctionAttr *ELF
12107 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12108 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12109 else if (SharedLockFunctionAttr *SLF
12110 = dyn_cast<SharedLockFunctionAttr>(*A))
12111 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12112 else if (ExclusiveTrylockFunctionAttr *ETLF
12113 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12114 Arg = ETLF->getSuccessValue();
12115 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12116 } else if (SharedTrylockFunctionAttr *STLF
12117 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12118 Arg = STLF->getSuccessValue();
12119 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12120 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12121 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12122 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12123 Arg = LR->getArg();
12124 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12125 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12126 else if (ExclusiveLocksRequiredAttr *ELR
12127 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12128 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12129 else if (SharedLocksRequiredAttr *SLR
12130 = dyn_cast<SharedLocksRequiredAttr>(*A))
12131 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12132
12133 if (Arg && !Finder.TraverseStmt(Arg))
12134 return true;
12135
12136 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12137 if (!Finder.TraverseStmt(Args[I]))
12138 return true;
12139 }
12140 }
12141
12142 return false;
12143}
12144
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012145void
12146Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12147 ArrayRef<ParsedType> DynamicExceptions,
12148 ArrayRef<SourceRange> DynamicExceptionRanges,
12149 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012150 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012151 FunctionProtoType::ExtProtoInfo &EPI) {
12152 Exceptions.clear();
12153 EPI.ExceptionSpecType = EST;
12154 if (EST == EST_Dynamic) {
12155 Exceptions.reserve(DynamicExceptions.size());
12156 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12157 // FIXME: Preserve type source info.
12158 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12159
12160 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12161 collectUnexpandedParameterPacks(ET, Unexpanded);
12162 if (!Unexpanded.empty()) {
12163 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12164 UPPC_ExceptionType,
12165 Unexpanded);
12166 continue;
12167 }
12168
12169 // Check that the type is valid for an exception spec, and
12170 // drop it if not.
12171 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12172 Exceptions.push_back(ET);
12173 }
12174 EPI.NumExceptions = Exceptions.size();
12175 EPI.Exceptions = Exceptions.data();
12176 return;
12177 }
12178
12179 if (EST == EST_ComputedNoexcept) {
12180 // If an error occurred, there's no expression here.
12181 if (NoexceptExpr) {
12182 assert((NoexceptExpr->isTypeDependent() ||
12183 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12184 Context.BoolTy) &&
12185 "Parser should have made sure that the expression is boolean");
12186 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12187 EPI.ExceptionSpecType = EST_BasicNoexcept;
12188 return;
12189 }
12190
12191 if (!NoexceptExpr->isValueDependent())
12192 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012193 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012194 /*AllowFold*/ false).take();
12195 EPI.NoexceptExpr = NoexceptExpr;
12196 }
12197 return;
12198 }
12199}
12200
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012201/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12202Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12203 // Implicitly declared functions (e.g. copy constructors) are
12204 // __host__ __device__
12205 if (D->isImplicit())
12206 return CFT_HostDevice;
12207
12208 if (D->hasAttr<CUDAGlobalAttr>())
12209 return CFT_Global;
12210
12211 if (D->hasAttr<CUDADeviceAttr>()) {
12212 if (D->hasAttr<CUDAHostAttr>())
12213 return CFT_HostDevice;
12214 else
12215 return CFT_Device;
12216 }
12217
12218 return CFT_Host;
12219}
12220
12221bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12222 CUDAFunctionTarget CalleeTarget) {
12223 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12224 // Callable from the device only."
12225 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12226 return true;
12227
12228 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12229 // Callable from the host only."
12230 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12231 // Callable from the host only."
12232 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12233 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12234 return true;
12235
12236 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12237 return true;
12238
12239 return false;
12240}
John McCall76da55d2013-04-16 07:28:30 +000012241
12242/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12243///
12244MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12245 SourceLocation DeclStart,
12246 Declarator &D, Expr *BitWidth,
12247 InClassInitStyle InitStyle,
12248 AccessSpecifier AS,
12249 AttributeList *MSPropertyAttr) {
12250 IdentifierInfo *II = D.getIdentifier();
12251 if (!II) {
12252 Diag(DeclStart, diag::err_anonymous_property);
12253 return NULL;
12254 }
12255 SourceLocation Loc = D.getIdentifierLoc();
12256
12257 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12258 QualType T = TInfo->getType();
12259 if (getLangOpts().CPlusPlus) {
12260 CheckExtraCXXDefaultArguments(D);
12261
12262 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12263 UPPC_DataMemberType)) {
12264 D.setInvalidType();
12265 T = Context.IntTy;
12266 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12267 }
12268 }
12269
12270 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12271
12272 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12273 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12274 diag::err_invalid_thread)
12275 << DeclSpec::getSpecifierName(TSCS);
12276
12277 // Check to see if this name was declared as a member previously
12278 NamedDecl *PrevDecl = 0;
12279 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12280 LookupName(Previous, S);
12281 switch (Previous.getResultKind()) {
12282 case LookupResult::Found:
12283 case LookupResult::FoundUnresolvedValue:
12284 PrevDecl = Previous.getAsSingle<NamedDecl>();
12285 break;
12286
12287 case LookupResult::FoundOverloaded:
12288 PrevDecl = Previous.getRepresentativeDecl();
12289 break;
12290
12291 case LookupResult::NotFound:
12292 case LookupResult::NotFoundInCurrentInstantiation:
12293 case LookupResult::Ambiguous:
12294 break;
12295 }
12296
12297 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12298 // Maybe we will complain about the shadowed template parameter.
12299 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12300 // Just pretend that we didn't see the previous declaration.
12301 PrevDecl = 0;
12302 }
12303
12304 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12305 PrevDecl = 0;
12306
12307 SourceLocation TSSL = D.getLocStart();
12308 MSPropertyDecl *NewPD;
12309 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12310 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12311 II, T, TInfo, TSSL,
12312 Data.GetterId, Data.SetterId);
12313 ProcessDeclAttributes(TUScope, NewPD, D);
12314 NewPD->setAccess(AS);
12315
12316 if (NewPD->isInvalidDecl())
12317 Record->setInvalidDecl();
12318
12319 if (D.getDeclSpec().isModulePrivateSpecified())
12320 NewPD->setModulePrivate();
12321
12322 if (NewPD->isInvalidDecl() && PrevDecl) {
12323 // Don't introduce NewFD into scope; there's already something
12324 // with the same name in the same scope.
12325 } else if (II) {
12326 PushOnScopeChains(NewPD, S);
12327 } else
12328 Record->addDecl(NewPD);
12329
12330 return NewPD;
12331}