blob: d2051b52e83efc5ce1715a0131c8cac49fe8c07d [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);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
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
Douglas Gregorc6889e72012-02-14 22:28:59 +0000636 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
637 isa<CXXMethodDecl>(FD) &&
638 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
Richard Smith7974c602013-04-17 16:25:20 +0000639
Chris Lattner3d1cee32008-04-08 05:04:30 +0000640 // Find first parameter with a default argument
641 for (p = 0; p < NumParams; ++p) {
642 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000643 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000644 break;
645 }
646
647 // C++ [dcl.fct.default]p4:
648 // In a given function declaration, all parameters
649 // subsequent to a parameter with a default argument shall
650 // have default arguments supplied in this or previous
651 // declarations. A default argument shall not be redefined
652 // by a later declaration (not even to the same value).
653 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000654 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000655 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000656 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000657 if (Param->isInvalidDecl())
658 /* We already complained about this parameter. */;
659 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000660 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000661 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000662 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000663 else
Mike Stump1eb44332009-09-09 15:08:12 +0000664 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000665 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000666
Chris Lattner3d1cee32008-04-08 05:04:30 +0000667 LastMissingDefaultArg = p;
668 }
669 }
670
671 if (LastMissingDefaultArg > 0) {
672 // Some default arguments were missing. Clear out all of the
673 // default arguments up to (and including) the last missing
674 // default argument, so that we leave the function parameters
675 // in a semantically valid state.
676 for (p = 0; p <= LastMissingDefaultArg; ++p) {
677 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000678 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000679 Param->setDefaultArg(0);
680 }
681 }
682 }
683}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000684
Richard Smith9f569cc2011-10-01 02:31:28 +0000685// CheckConstexprParameterTypes - Check whether a function's parameter types
686// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000687// diagnostic and return false.
688static bool CheckConstexprParameterTypes(Sema &SemaRef,
689 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000690 unsigned ArgIndex = 0;
691 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
692 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
693 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
694 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
695 SourceLocation ParamLoc = PD->getLocation();
696 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000697 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000698 diag::err_constexpr_non_literal_param,
699 ArgIndex+1, PD->getSourceRange(),
700 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000701 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000702 }
Joao Matos17d35c32012-08-31 22:18:20 +0000703 return true;
704}
705
706/// \brief Get diagnostic %select index for tag kind for
707/// record diagnostic message.
708/// WARNING: Indexes apply to particular diagnostics only!
709///
710/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000711static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000712 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000713 case TTK_Struct: return 0;
714 case TTK_Interface: return 1;
715 case TTK_Class: return 2;
716 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000717 }
Joao Matos17d35c32012-08-31 22:18:20 +0000718}
719
720// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
721// the requirements of a constexpr function definition or a constexpr
722// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000723// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000724//
Richard Smith86c3ae42012-02-13 03:54:03 +0000725// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
726bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000727 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
728 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000729 // C++11 [dcl.constexpr]p4:
730 // The definition of a constexpr constructor shall satisfy the following
731 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000732 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000733 const CXXRecordDecl *RD = MD->getParent();
734 if (RD->getNumVBases()) {
735 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
736 << isa<CXXConstructorDecl>(NewFD)
737 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
738 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
739 E = RD->vbases_end(); I != E; ++I)
740 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000741 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000742 return false;
743 }
Richard Smith35340502012-01-13 04:54:00 +0000744 }
745
746 if (!isa<CXXConstructorDecl>(NewFD)) {
747 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000748 // The definition of a constexpr function shall satisfy the following
749 // constraints:
750 // - it shall not be virtual;
751 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
752 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000753 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000754
Richard Smith86c3ae42012-02-13 03:54:03 +0000755 // If it's not obvious why this function is virtual, find an overridden
756 // function which uses the 'virtual' keyword.
757 const CXXMethodDecl *WrittenVirtual = Method;
758 while (!WrittenVirtual->isVirtualAsWritten())
759 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
760 if (WrittenVirtual != Method)
761 Diag(WrittenVirtual->getLocation(),
762 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000763 return false;
764 }
765
766 // - its return type shall be a literal type;
767 QualType RT = NewFD->getResultType();
768 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000769 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000770 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000771 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000772 }
773
Richard Smith35340502012-01-13 04:54:00 +0000774 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000775 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000776 return false;
777
Richard Smith9f569cc2011-10-01 02:31:28 +0000778 return true;
779}
780
781/// Check the given declaration statement is legal within a constexpr function
782/// body. C++0x [dcl.constexpr]p3,p4.
783///
784/// \return true if the body is OK, false if we have diagnosed a problem.
785static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
786 DeclStmt *DS) {
787 // C++0x [dcl.constexpr]p3 and p4:
788 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
789 // contain only
790 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
791 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
792 switch ((*DclIt)->getKind()) {
793 case Decl::StaticAssert:
794 case Decl::Using:
795 case Decl::UsingShadow:
796 case Decl::UsingDirective:
797 case Decl::UnresolvedUsingTypename:
798 // - static_assert-declarations
799 // - using-declarations,
800 // - using-directives,
801 continue;
802
803 case Decl::Typedef:
804 case Decl::TypeAlias: {
805 // - typedef declarations and alias-declarations that do not define
806 // classes or enumerations,
807 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
808 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
809 // Don't allow variably-modified types in constexpr functions.
810 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
811 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
812 << TL.getSourceRange() << TL.getType()
813 << isa<CXXConstructorDecl>(Dcl);
814 return false;
815 }
816 continue;
817 }
818
819 case Decl::Enum:
820 case Decl::CXXRecord:
821 // As an extension, we allow the declaration (but not the definition) of
822 // classes and enumerations in all declarations, not just in typedef and
823 // alias declarations.
824 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
825 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
826 << isa<CXXConstructorDecl>(Dcl);
827 return false;
828 }
829 continue;
830
831 case Decl::Var:
832 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
833 << isa<CXXConstructorDecl>(Dcl);
834 return false;
835
836 default:
837 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
838 << isa<CXXConstructorDecl>(Dcl);
839 return false;
840 }
841 }
842
843 return true;
844}
845
846/// Check that the given field is initialized within a constexpr constructor.
847///
848/// \param Dcl The constexpr constructor being checked.
849/// \param Field The field being checked. This may be a member of an anonymous
850/// struct or union nested within the class being checked.
851/// \param Inits All declarations, including anonymous struct/union members and
852/// indirect members, for which any initialization was provided.
853/// \param Diagnosed Set to true if an error is produced.
854static void CheckConstexprCtorInitializer(Sema &SemaRef,
855 const FunctionDecl *Dcl,
856 FieldDecl *Field,
857 llvm::SmallSet<Decl*, 16> &Inits,
858 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000859 if (Field->isUnnamedBitfield())
860 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000861
862 if (Field->isAnonymousStructOrUnion() &&
863 Field->getType()->getAsCXXRecordDecl()->isEmpty())
864 return;
865
Richard Smith9f569cc2011-10-01 02:31:28 +0000866 if (!Inits.count(Field)) {
867 if (!Diagnosed) {
868 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
869 Diagnosed = true;
870 }
871 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
872 } else if (Field->isAnonymousStructOrUnion()) {
873 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
874 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
875 I != E; ++I)
876 // If an anonymous union contains an anonymous struct of which any member
877 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000878 if (!RD->isUnion() || Inits.count(*I))
879 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000880 }
881}
882
883/// Check the body for the given constexpr function declaration only contains
884/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
885///
886/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000887bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000888 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000889 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000890 // The definition of a constexpr function shall satisfy the following
891 // constraints: [...]
892 // - its function-body shall be = delete, = default, or a
893 // compound-statement
894 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000895 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000896 // In the definition of a constexpr constructor, [...]
897 // - its function-body shall not be a function-try-block;
898 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
899 << isa<CXXConstructorDecl>(Dcl);
900 return false;
901 }
902
903 // - its function-body shall be [...] a compound-statement that contains only
904 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
905
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000906 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smith9f569cc2011-10-01 02:31:28 +0000907 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
908 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
909 switch ((*BodyIt)->getStmtClass()) {
910 case Stmt::NullStmtClass:
911 // - null statements,
912 continue;
913
914 case Stmt::DeclStmtClass:
915 // - static_assert-declarations
916 // - using-declarations,
917 // - using-directives,
918 // - typedef declarations and alias-declarations that do not define
919 // classes or enumerations,
920 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
921 return false;
922 continue;
923
924 case Stmt::ReturnStmtClass:
925 // - and exactly one return statement;
926 if (isa<CXXConstructorDecl>(Dcl))
927 break;
928
929 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000930 continue;
931
932 default:
933 break;
934 }
935
936 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
937 << isa<CXXConstructorDecl>(Dcl);
938 return false;
939 }
940
941 if (const CXXConstructorDecl *Constructor
942 = dyn_cast<CXXConstructorDecl>(Dcl)) {
943 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000944 // DR1359:
945 // - every non-variant non-static data member and base class sub-object
946 // shall be initialized;
947 // - if the class is a non-empty union, or for each non-empty anonymous
948 // union member of a non-union class, exactly one non-static data member
949 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000950 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000951 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000952 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
953 return false;
954 }
Richard Smith6e433752011-10-10 16:38:04 +0000955 } else if (!Constructor->isDependentContext() &&
956 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000957 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
958
959 // Skip detailed checking if we have enough initializers, and we would
960 // allow at most one initializer per member.
961 bool AnyAnonStructUnionMembers = false;
962 unsigned Fields = 0;
963 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
964 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000965 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000966 AnyAnonStructUnionMembers = true;
967 break;
968 }
969 }
970 if (AnyAnonStructUnionMembers ||
971 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
972 // Check initialization of non-static data members. Base classes are
973 // always initialized so do not need to be checked. Dependent bases
974 // might not have initializers in the member initializer list.
975 llvm::SmallSet<Decl*, 16> Inits;
976 for (CXXConstructorDecl::init_const_iterator
977 I = Constructor->init_begin(), E = Constructor->init_end();
978 I != E; ++I) {
979 if (FieldDecl *FD = (*I)->getMember())
980 Inits.insert(FD);
981 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
982 Inits.insert(ID->chain_begin(), ID->chain_end());
983 }
984
985 bool Diagnosed = false;
986 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
987 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000988 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000989 if (Diagnosed)
990 return false;
991 }
992 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000993 } else {
994 if (ReturnStmts.empty()) {
995 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
996 return false;
997 }
998 if (ReturnStmts.size() > 1) {
999 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
1000 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1001 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1002 return false;
1003 }
1004 }
1005
Richard Smith5ba73e12012-02-04 00:33:54 +00001006 // C++11 [dcl.constexpr]p5:
1007 // if no function argument values exist such that the function invocation
1008 // substitution would produce a constant expression, the program is
1009 // ill-formed; no diagnostic required.
1010 // C++11 [dcl.constexpr]p3:
1011 // - every constructor call and implicit conversion used in initializing the
1012 // return value shall be one of those allowed in a constant expression.
1013 // C++11 [dcl.constexpr]p4:
1014 // - every constructor involved in initializing non-static data members and
1015 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001016 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001017 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001018 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001019 << isa<CXXConstructorDecl>(Dcl);
1020 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1021 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001022 // Don't return false here: we allow this for compatibility in
1023 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001024 }
1025
Richard Smith9f569cc2011-10-01 02:31:28 +00001026 return true;
1027}
1028
Douglas Gregorb48fe382008-10-31 09:07:45 +00001029/// isCurrentClassName - Determine whether the identifier II is the
1030/// name of the class type currently being defined. In the case of
1031/// nested classes, this will only return true if II is the name of
1032/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001033bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1034 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001035 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001036
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001037 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001038 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001039 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001040 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1041 } else
1042 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1043
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001044 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001045 return &II == CurDecl->getIdentifier();
1046 else
1047 return false;
1048}
1049
Douglas Gregor229d47a2012-11-10 07:24:09 +00001050/// \brief Determine whether the given class is a base class of the given
1051/// class, including looking at dependent bases.
1052static bool findCircularInheritance(const CXXRecordDecl *Class,
1053 const CXXRecordDecl *Current) {
1054 SmallVector<const CXXRecordDecl*, 8> Queue;
1055
1056 Class = Class->getCanonicalDecl();
1057 while (true) {
1058 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1059 E = Current->bases_end();
1060 I != E; ++I) {
1061 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1062 if (!Base)
1063 continue;
1064
1065 Base = Base->getDefinition();
1066 if (!Base)
1067 continue;
1068
1069 if (Base->getCanonicalDecl() == Class)
1070 return true;
1071
1072 Queue.push_back(Base);
1073 }
1074
1075 if (Queue.empty())
1076 return false;
1077
1078 Current = Queue.back();
1079 Queue.pop_back();
1080 }
1081
1082 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001083}
1084
Mike Stump1eb44332009-09-09 15:08:12 +00001085/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001086///
1087/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1088/// and returns NULL otherwise.
1089CXXBaseSpecifier *
1090Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1091 SourceRange SpecifierRange,
1092 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001093 TypeSourceInfo *TInfo,
1094 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001095 QualType BaseType = TInfo->getType();
1096
Douglas Gregor2943aed2009-03-03 04:44:36 +00001097 // C++ [class.union]p1:
1098 // A union shall not have base classes.
1099 if (Class->isUnion()) {
1100 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1101 << SpecifierRange;
1102 return 0;
1103 }
1104
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001105 if (EllipsisLoc.isValid() &&
1106 !TInfo->getType()->containsUnexpandedParameterPack()) {
1107 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1108 << TInfo->getTypeLoc().getSourceRange();
1109 EllipsisLoc = SourceLocation();
1110 }
Douglas Gregord777e282012-11-10 01:18:17 +00001111
1112 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1113
1114 if (BaseType->isDependentType()) {
1115 // Make sure that we don't have circular inheritance among our dependent
1116 // bases. For non-dependent bases, the check for completeness below handles
1117 // this.
1118 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1119 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1120 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001121 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001122 Diag(BaseLoc, diag::err_circular_inheritance)
1123 << BaseType << Context.getTypeDeclType(Class);
1124
1125 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1126 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1127 << BaseType;
1128
1129 return 0;
1130 }
1131 }
1132
Mike Stump1eb44332009-09-09 15:08:12 +00001133 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001134 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001135 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001136 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001137
1138 // Base specifiers must be record types.
1139 if (!BaseType->isRecordType()) {
1140 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1141 return 0;
1142 }
1143
1144 // C++ [class.union]p1:
1145 // A union shall not be used as a base class.
1146 if (BaseType->isUnionType()) {
1147 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1148 return 0;
1149 }
1150
1151 // C++ [class.derived]p2:
1152 // The class-name in a base-specifier shall not be an incompletely
1153 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001154 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001155 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001156 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001157 return 0;
John McCall572fc622010-08-17 07:23:57 +00001158 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001159
Eli Friedman1d954f62009-08-15 21:55:26 +00001160 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001161 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001162 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001163 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001164 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001165 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1166 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001167
Anders Carlsson1d209272011-03-25 14:55:14 +00001168 // C++ [class]p3:
1169 // If a class is marked final and it appears as a base-type-specifier in
1170 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001171 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001172 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1173 << CXXBaseDecl->getDeclName();
1174 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1175 << CXXBaseDecl->getDeclName();
1176 return 0;
1177 }
1178
John McCall572fc622010-08-17 07:23:57 +00001179 if (BaseDecl->isInvalidDecl())
1180 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001181
1182 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001183 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001184 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001185 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001186}
1187
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001188/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1189/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001190/// example:
1191/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001192/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001193BaseResult
John McCalld226f652010-08-21 09:40:31 +00001194Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001195 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001196 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001197 ParsedType basetype, SourceLocation BaseLoc,
1198 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001199 if (!classdecl)
1200 return true;
1201
Douglas Gregor40808ce2009-03-09 23:48:35 +00001202 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001203 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001204 if (!Class)
1205 return true;
1206
Richard Smith05321402013-02-19 23:47:15 +00001207 // We do not support any C++11 attributes on base-specifiers yet.
1208 // Diagnose any attributes we see.
1209 if (!Attributes.empty()) {
1210 for (AttributeList *Attr = Attributes.getList(); Attr;
1211 Attr = Attr->getNext()) {
1212 if (Attr->isInvalid() ||
1213 Attr->getKind() == AttributeList::IgnoredAttribute)
1214 continue;
1215 Diag(Attr->getLoc(),
1216 Attr->getKind() == AttributeList::UnknownAttribute
1217 ? diag::warn_unknown_attribute_ignored
1218 : diag::err_base_specifier_attribute)
1219 << Attr->getName();
1220 }
1221 }
1222
Nick Lewycky56062202010-07-26 16:56:01 +00001223 TypeSourceInfo *TInfo = 0;
1224 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001225
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001226 if (EllipsisLoc.isInvalid() &&
1227 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001228 UPPC_BaseType))
1229 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001230
Douglas Gregor2943aed2009-03-03 04:44:36 +00001231 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001232 Virtual, Access, TInfo,
1233 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001234 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001235 else
1236 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001237
Douglas Gregor2943aed2009-03-03 04:44:36 +00001238 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001239}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001240
Douglas Gregor2943aed2009-03-03 04:44:36 +00001241/// \brief Performs the actual work of attaching the given base class
1242/// specifiers to a C++ class.
1243bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1244 unsigned NumBases) {
1245 if (NumBases == 0)
1246 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001247
1248 // Used to keep track of which base types we have already seen, so
1249 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001250 // that the key is always the unqualified canonical type of the base
1251 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001252 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1253
1254 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001255 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001256 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001257 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001258 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001259 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001260 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001261
1262 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1263 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001264 // C++ [class.mi]p3:
1265 // A class shall not be specified as a direct base class of a
1266 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001267 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001268 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001269 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001270 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001271
1272 // Delete the duplicate base class specifier; we're going to
1273 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001274 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001275
1276 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001277 } else {
1278 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001279 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001280 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001281 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1282 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1283 if (Class->isInterface() &&
1284 (!RD->isInterface() ||
1285 KnownBase->getAccessSpecifier() != AS_public)) {
1286 // The Microsoft extension __interface does not permit bases that
1287 // are not themselves public interfaces.
1288 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1289 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1290 << RD->getSourceRange();
1291 Invalid = true;
1292 }
1293 if (RD->hasAttr<WeakAttr>())
1294 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1295 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001296 }
1297 }
1298
1299 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001300 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001301
1302 // Delete the remaining (good) base class specifiers, since their
1303 // data has been copied into the CXXRecordDecl.
1304 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001305 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001306
1307 return Invalid;
1308}
1309
1310/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1311/// class, after checking whether there are any duplicate base
1312/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001313void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001314 unsigned NumBases) {
1315 if (!ClassDecl || !Bases || !NumBases)
1316 return;
1317
1318 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001319 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001320 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001321}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001322
Douglas Gregora8f32e02009-10-06 17:59:45 +00001323/// \brief Determine whether the type \p Derived is a C++ class that is
1324/// derived from the type \p Base.
1325bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001326 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001327 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001328
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001329 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001330 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001331 return false;
1332
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001333 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001334 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001335 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001336
1337 // If either the base or the derived type is invalid, don't try to
1338 // check whether one is derived from the other.
1339 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1340 return false;
1341
John McCall86ff3082010-02-04 22:26:26 +00001342 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1343 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001344}
1345
1346/// \brief Determine whether the type \p Derived is a C++ class that is
1347/// derived from the type \p Base.
1348bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001349 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001350 return false;
1351
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001352 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001353 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001354 return false;
1355
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001356 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001357 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001358 return false;
1359
Douglas Gregora8f32e02009-10-06 17:59:45 +00001360 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1361}
1362
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001363void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001364 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001365 assert(BasePathArray.empty() && "Base path array must be empty!");
1366 assert(Paths.isRecordingPaths() && "Must record paths!");
1367
1368 const CXXBasePath &Path = Paths.front();
1369
1370 // We first go backward and check if we have a virtual base.
1371 // FIXME: It would be better if CXXBasePath had the base specifier for
1372 // the nearest virtual base.
1373 unsigned Start = 0;
1374 for (unsigned I = Path.size(); I != 0; --I) {
1375 if (Path[I - 1].Base->isVirtual()) {
1376 Start = I - 1;
1377 break;
1378 }
1379 }
1380
1381 // Now add all bases.
1382 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001383 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001384}
1385
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001386/// \brief Determine whether the given base path includes a virtual
1387/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001388bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1389 for (CXXCastPath::const_iterator B = BasePath.begin(),
1390 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001391 B != BEnd; ++B)
1392 if ((*B)->isVirtual())
1393 return true;
1394
1395 return false;
1396}
1397
Douglas Gregora8f32e02009-10-06 17:59:45 +00001398/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1399/// conversion (where Derived and Base are class types) is
1400/// well-formed, meaning that the conversion is unambiguous (and
1401/// that all of the base classes are accessible). Returns true
1402/// and emits a diagnostic if the code is ill-formed, returns false
1403/// otherwise. Loc is the location where this routine should point to
1404/// if there is an error, and Range is the source range to highlight
1405/// if there is an error.
1406bool
1407Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001408 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001409 unsigned AmbigiousBaseConvID,
1410 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001411 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001412 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001413 // First, determine whether the path from Derived to Base is
1414 // ambiguous. This is slightly more expensive than checking whether
1415 // the Derived to Base conversion exists, because here we need to
1416 // explore multiple paths to determine if there is an ambiguity.
1417 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1418 /*DetectVirtual=*/false);
1419 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1420 assert(DerivationOkay &&
1421 "Can only be used with a derived-to-base conversion");
1422 (void)DerivationOkay;
1423
1424 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001425 if (InaccessibleBaseID) {
1426 // Check that the base class can be accessed.
1427 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1428 InaccessibleBaseID)) {
1429 case AR_inaccessible:
1430 return true;
1431 case AR_accessible:
1432 case AR_dependent:
1433 case AR_delayed:
1434 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001435 }
John McCall6b2accb2010-02-10 09:31:12 +00001436 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001437
1438 // Build a base path if necessary.
1439 if (BasePath)
1440 BuildBasePathArray(Paths, *BasePath);
1441 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001442 }
1443
1444 // We know that the derived-to-base conversion is ambiguous, and
1445 // we're going to produce a diagnostic. Perform the derived-to-base
1446 // search just one more time to compute all of the possible paths so
1447 // that we can print them out. This is more expensive than any of
1448 // the previous derived-to-base checks we've done, but at this point
1449 // performance isn't as much of an issue.
1450 Paths.clear();
1451 Paths.setRecordingPaths(true);
1452 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1453 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1454 (void)StillOkay;
1455
1456 // Build up a textual representation of the ambiguous paths, e.g.,
1457 // D -> B -> A, that will be used to illustrate the ambiguous
1458 // conversions in the diagnostic. We only print one of the paths
1459 // to each base class subobject.
1460 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1461
1462 Diag(Loc, AmbigiousBaseConvID)
1463 << Derived << Base << PathDisplayStr << Range << Name;
1464 return true;
1465}
1466
1467bool
1468Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001469 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001470 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001471 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001472 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001473 IgnoreAccess ? 0
1474 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001475 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001476 Loc, Range, DeclarationName(),
1477 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001478}
1479
1480
1481/// @brief Builds a string representing ambiguous paths from a
1482/// specific derived class to different subobjects of the same base
1483/// class.
1484///
1485/// This function builds a string that can be used in error messages
1486/// to show the different paths that one can take through the
1487/// inheritance hierarchy to go from the derived class to different
1488/// subobjects of a base class. The result looks something like this:
1489/// @code
1490/// struct D -> struct B -> struct A
1491/// struct D -> struct C -> struct A
1492/// @endcode
1493std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1494 std::string PathDisplayStr;
1495 std::set<unsigned> DisplayedPaths;
1496 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1497 Path != Paths.end(); ++Path) {
1498 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1499 // We haven't displayed a path to this particular base
1500 // class subobject yet.
1501 PathDisplayStr += "\n ";
1502 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1503 for (CXXBasePath::const_iterator Element = Path->begin();
1504 Element != Path->end(); ++Element)
1505 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1506 }
1507 }
1508
1509 return PathDisplayStr;
1510}
1511
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001512//===----------------------------------------------------------------------===//
1513// C++ class member Handling
1514//===----------------------------------------------------------------------===//
1515
Abramo Bagnara6206d532010-06-05 05:09:32 +00001516/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001517bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1518 SourceLocation ASLoc,
1519 SourceLocation ColonLoc,
1520 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001521 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001522 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001523 ASLoc, ColonLoc);
1524 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001525 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001526}
1527
Richard Smitha4b39652012-08-06 03:25:17 +00001528/// CheckOverrideControl - Check C++11 override control semantics.
1529void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001530 if (D->isInvalidDecl())
1531 return;
1532
Chris Lattner5f9e2722011-07-23 10:55:15 +00001533 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001534
Richard Smitha4b39652012-08-06 03:25:17 +00001535 // Do we know which functions this declaration might be overriding?
1536 bool OverridesAreKnown = !MD ||
1537 (!MD->getParent()->hasAnyDependentBases() &&
1538 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001539
Richard Smitha4b39652012-08-06 03:25:17 +00001540 if (!MD || !MD->isVirtual()) {
1541 if (OverridesAreKnown) {
1542 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1543 Diag(OA->getLocation(),
1544 diag::override_keyword_only_allowed_on_virtual_member_functions)
1545 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1546 D->dropAttr<OverrideAttr>();
1547 }
1548 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1549 Diag(FA->getLocation(),
1550 diag::override_keyword_only_allowed_on_virtual_member_functions)
1551 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1552 D->dropAttr<FinalAttr>();
1553 }
1554 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001555 return;
1556 }
Richard Smitha4b39652012-08-06 03:25:17 +00001557
1558 if (!OverridesAreKnown)
1559 return;
1560
1561 // C++11 [class.virtual]p5:
1562 // If a virtual function is marked with the virt-specifier override and
1563 // does not override a member function of a base class, the program is
1564 // ill-formed.
1565 bool HasOverriddenMethods =
1566 MD->begin_overridden_methods() != MD->end_overridden_methods();
1567 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1568 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1569 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001570}
1571
Richard Smitha4b39652012-08-06 03:25:17 +00001572/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001573/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001574/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001575bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1576 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001577 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001578 return false;
1579
1580 Diag(New->getLocation(), diag::err_final_function_overridden)
1581 << New->getDeclName();
1582 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1583 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001584}
1585
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001586static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001587 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1588 // FIXME: Destruction of ObjC lifetime types has side-effects.
1589 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1590 return !RD->isCompleteDefinition() ||
1591 !RD->hasTrivialDefaultConstructor() ||
1592 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001593 return false;
1594}
1595
John McCall76da55d2013-04-16 07:28:30 +00001596static AttributeList *getMSPropertyAttr(AttributeList *list) {
1597 for (AttributeList* it = list; it != 0; it = it->getNext())
1598 if (it->isDeclspecPropertyAttribute())
1599 return it;
1600 return 0;
1601}
1602
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001603/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1604/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001605/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001606/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1607/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001608NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001609Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001610 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001611 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001612 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001613 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001614 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1615 DeclarationName Name = NameInfo.getName();
1616 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001617
1618 // For anonymous bitfields, the location should point to the type.
1619 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001620 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001621
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001622 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001623
John McCall4bde1e12010-06-04 08:34:12 +00001624 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001625 assert(!DS.isFriendSpecified());
1626
Richard Smith1ab0d902011-06-25 02:28:38 +00001627 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001628
John McCalle402e722012-09-25 07:32:39 +00001629 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1630 // The Microsoft extension __interface only permits public member functions
1631 // and prohibits constructors, destructors, operators, non-public member
1632 // functions, static methods and data members.
1633 unsigned InvalidDecl;
1634 bool ShowDeclName = true;
1635 if (!isFunc)
1636 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1637 else if (AS != AS_public)
1638 InvalidDecl = 2;
1639 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1640 InvalidDecl = 3;
1641 else switch (Name.getNameKind()) {
1642 case DeclarationName::CXXConstructorName:
1643 InvalidDecl = 4;
1644 ShowDeclName = false;
1645 break;
1646
1647 case DeclarationName::CXXDestructorName:
1648 InvalidDecl = 5;
1649 ShowDeclName = false;
1650 break;
1651
1652 case DeclarationName::CXXOperatorName:
1653 case DeclarationName::CXXConversionFunctionName:
1654 InvalidDecl = 6;
1655 break;
1656
1657 default:
1658 InvalidDecl = 0;
1659 break;
1660 }
1661
1662 if (InvalidDecl) {
1663 if (ShowDeclName)
1664 Diag(Loc, diag::err_invalid_member_in_interface)
1665 << (InvalidDecl-1) << Name;
1666 else
1667 Diag(Loc, diag::err_invalid_member_in_interface)
1668 << (InvalidDecl-1) << "";
1669 return 0;
1670 }
1671 }
1672
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001673 // C++ 9.2p6: A member shall not be declared to have automatic storage
1674 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001675 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1676 // data members and cannot be applied to names declared const or static,
1677 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001678 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001679 case DeclSpec::SCS_unspecified:
1680 case DeclSpec::SCS_typedef:
1681 case DeclSpec::SCS_static:
1682 break;
1683 case DeclSpec::SCS_mutable:
1684 if (isFunc) {
1685 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Richard Smithec642442013-04-12 22:46:28 +00001687 // FIXME: It would be nicer if the keyword was ignored only for this
1688 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001689 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001690 }
1691 break;
1692 default:
1693 Diag(DS.getStorageClassSpecLoc(),
1694 diag::err_storageclass_invalid_for_member);
1695 D.getMutableDeclSpec().ClearStorageClassSpecs();
1696 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001697 }
1698
Sebastian Redl669d5d72008-11-14 23:42:31 +00001699 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1700 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001701 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001702
David Blaikie1d87fba2013-01-30 01:22:18 +00001703 if (DS.isConstexprSpecified() && isInstField) {
1704 SemaDiagnosticBuilder B =
1705 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1706 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1707 if (InitStyle == ICIS_NoInit) {
1708 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1709 D.getMutableDeclSpec().ClearConstexprSpec();
1710 const char *PrevSpec;
1711 unsigned DiagID;
1712 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1713 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001714 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001715 assert(!Failed && "Making a constexpr member const shouldn't fail");
1716 } else {
1717 B << 1;
1718 const char *PrevSpec;
1719 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001720 if (D.getMutableDeclSpec().SetStorageClassSpec(
1721 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001722 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001723 "This is the only DeclSpec that should fail to be applied");
1724 B << 1;
1725 } else {
1726 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1727 isInstField = false;
1728 }
1729 }
1730 }
1731
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001732 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001733 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001734 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001735
1736 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001737 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001738 Diag(Loc, diag::err_bad_variable_name)
1739 << Name;
1740 return 0;
1741 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001742
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001743 IdentifierInfo *II = Name.getAsIdentifierInfo();
1744
Douglas Gregorf2503652011-09-21 14:40:46 +00001745 // Member field could not be with "template" keyword.
1746 // So TemplateParameterLists should be empty in this case.
1747 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001748 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001749 if (TemplateParams->size()) {
1750 // There is no such thing as a member field template.
1751 Diag(D.getIdentifierLoc(), diag::err_template_member)
1752 << II
1753 << SourceRange(TemplateParams->getTemplateLoc(),
1754 TemplateParams->getRAngleLoc());
1755 } else {
1756 // There is an extraneous 'template<>' for this member.
1757 Diag(TemplateParams->getTemplateLoc(),
1758 diag::err_template_member_noparams)
1759 << II
1760 << SourceRange(TemplateParams->getTemplateLoc(),
1761 TemplateParams->getRAngleLoc());
1762 }
1763 return 0;
1764 }
1765
Douglas Gregor922fff22010-10-13 22:19:53 +00001766 if (SS.isSet() && !SS.isInvalid()) {
1767 // The user provided a superfluous scope specifier inside a class
1768 // definition:
1769 //
1770 // class X {
1771 // int X::member;
1772 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001773 if (DeclContext *DC = computeDeclContext(SS, false))
1774 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001775 else
1776 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1777 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001778
Douglas Gregor922fff22010-10-13 22:19:53 +00001779 SS.clear();
1780 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001781
John McCall76da55d2013-04-16 07:28:30 +00001782 AttributeList *MSPropertyAttr =
1783 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1784 if (MSPropertyAttr) {
1785 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1786 BitWidth, InitStyle, AS, MSPropertyAttr);
1787 isInstField = false;
1788 } else {
1789 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1790 BitWidth, InitStyle, AS);
1791 }
Chris Lattner6f8ce142009-03-05 23:03:49 +00001792 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001793 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001794 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001795
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001796 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001797 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001798 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001799 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001800
1801 // Non-instance-fields can't have a bitfield.
1802 if (BitWidth) {
1803 if (Member->isInvalidDecl()) {
1804 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001805 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001806 // C++ 9.6p3: A bit-field shall not be a static member.
1807 // "static member 'A' cannot be a bit-field"
1808 Diag(Loc, diag::err_static_not_bitfield)
1809 << Name << BitWidth->getSourceRange();
1810 } else if (isa<TypedefDecl>(Member)) {
1811 // "typedef member 'x' cannot be a bit-field"
1812 Diag(Loc, diag::err_typedef_not_bitfield)
1813 << Name << BitWidth->getSourceRange();
1814 } else {
1815 // A function typedef ("typedef int f(); f a;").
1816 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1817 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001818 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001819 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001820 }
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Chris Lattner8b963ef2009-03-05 23:01:03 +00001822 BitWidth = 0;
1823 Member->setInvalidDecl();
1824 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001825
1826 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Douglas Gregor37b372b2009-08-20 22:52:58 +00001828 // If we have declared a member function template, set the access of the
1829 // templated declaration as well.
1830 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1831 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001832 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001833
Richard Smitha4b39652012-08-06 03:25:17 +00001834 if (VS.isOverrideSpecified())
1835 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1836 if (VS.isFinalSpecified())
1837 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001838
Douglas Gregorf5251602011-03-08 17:10:18 +00001839 if (VS.getLastLocation().isValid()) {
1840 // Update the end location of a method that has a virt-specifiers.
1841 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1842 MD->setRangeEnd(VS.getLastLocation());
1843 }
Richard Smitha4b39652012-08-06 03:25:17 +00001844
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001845 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001846
Douglas Gregor10bd3682008-11-17 22:58:34 +00001847 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001848
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001849 if (isInstField) {
1850 FieldDecl *FD = cast<FieldDecl>(Member);
1851 FieldCollector->Add(FD);
1852
1853 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1854 FD->getLocation())
1855 != DiagnosticsEngine::Ignored) {
1856 // Remember all explicit private FieldDecls that have a name, no side
1857 // effects and are not part of a dependent type declaration.
1858 if (!FD->isImplicit() && FD->getDeclName() &&
1859 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001860 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001861 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001862 !InitializationHasSideEffects(*FD))
1863 UnusedPrivateFields.insert(FD);
1864 }
1865 }
1866
John McCalld226f652010-08-21 09:40:31 +00001867 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001868}
1869
Hans Wennborg471f9852012-09-18 15:58:06 +00001870namespace {
1871 class UninitializedFieldVisitor
1872 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1873 Sema &S;
1874 ValueDecl *VD;
1875 public:
1876 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1877 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001878 S(S) {
1879 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1880 this->VD = IFD->getAnonField();
1881 else
1882 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001883 }
1884
1885 void HandleExpr(Expr *E) {
1886 if (!E) return;
1887
1888 // Expressions like x(x) sometimes lack the surrounding expressions
1889 // but need to be checked anyways.
1890 HandleValue(E);
1891 Visit(E);
1892 }
1893
1894 void HandleValue(Expr *E) {
1895 E = E->IgnoreParens();
1896
1897 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1898 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001899 return;
1900
1901 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1902 // or union.
1903 MemberExpr *FieldME = ME;
1904
Hans Wennborg471f9852012-09-18 15:58:06 +00001905 Expr *Base = E;
1906 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001907 ME = cast<MemberExpr>(Base);
1908
1909 if (isa<VarDecl>(ME->getMemberDecl()))
1910 return;
1911
1912 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1913 if (!FD->isAnonymousStructOrUnion())
1914 FieldME = ME;
1915
Hans Wennborg471f9852012-09-18 15:58:06 +00001916 Base = ME->getBase();
1917 }
1918
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001919 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00001920 unsigned diag = VD->getType()->isReferenceType()
1921 ? diag::warn_reference_field_is_uninit
1922 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001923 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001924 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001925 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00001926 }
1927
1928 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1929 HandleValue(CO->getTrueExpr());
1930 HandleValue(CO->getFalseExpr());
1931 return;
1932 }
1933
1934 if (BinaryConditionalOperator *BCO =
1935 dyn_cast<BinaryConditionalOperator>(E)) {
1936 HandleValue(BCO->getCommon());
1937 HandleValue(BCO->getFalseExpr());
1938 return;
1939 }
1940
1941 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1942 switch (BO->getOpcode()) {
1943 default:
1944 return;
1945 case(BO_PtrMemD):
1946 case(BO_PtrMemI):
1947 HandleValue(BO->getLHS());
1948 return;
1949 case(BO_Comma):
1950 HandleValue(BO->getRHS());
1951 return;
1952 }
1953 }
1954 }
1955
1956 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1957 if (E->getCastKind() == CK_LValueToRValue)
1958 HandleValue(E->getSubExpr());
1959
1960 Inherited::VisitImplicitCastExpr(E);
1961 }
1962
1963 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1964 Expr *Callee = E->getCallee();
1965 if (isa<MemberExpr>(Callee))
1966 HandleValue(Callee);
1967
1968 Inherited::VisitCXXMemberCallExpr(E);
1969 }
1970 };
1971 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1972 ValueDecl *VD) {
1973 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1974 }
1975} // namespace
1976
Richard Smith7a614d82011-06-11 17:19:42 +00001977/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001978/// in-class initializer for a non-static C++ class member, and after
1979/// instantiating an in-class initializer in a class template. Such actions
1980/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001981void
Richard Smithca523302012-06-10 03:12:00 +00001982Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001983 Expr *InitExpr) {
1984 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001985 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1986 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001987
1988 if (!InitExpr) {
1989 FD->setInvalidDecl();
1990 FD->removeInClassInitializer();
1991 return;
1992 }
1993
Peter Collingbournefef21892011-10-23 18:59:44 +00001994 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1995 FD->setInvalidDecl();
1996 FD->removeInClassInitializer();
1997 return;
1998 }
1999
Hans Wennborg471f9852012-09-18 15:58:06 +00002000 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2001 != DiagnosticsEngine::Ignored) {
2002 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2003 }
2004
Richard Smith7a614d82011-06-11 17:19:42 +00002005 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002006 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00002007 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002008 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00002009 << /*at end of ctor*/1 << InitExpr->getSourceRange();
2010 }
Sebastian Redl33deb352012-02-22 10:50:08 +00002011 Expr **Inits = &InitExpr;
2012 unsigned NumInits = 1;
2013 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002014 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002015 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002016 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00002017 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
2018 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00002019 if (Init.isInvalid()) {
2020 FD->setInvalidDecl();
2021 return;
2022 }
Richard Smith7a614d82011-06-11 17:19:42 +00002023 }
2024
Richard Smith41956372013-01-14 22:39:08 +00002025 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002026 // The initialization of each base and member constitutes a
2027 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002028 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002029 if (Init.isInvalid()) {
2030 FD->setInvalidDecl();
2031 return;
2032 }
2033
2034 InitExpr = Init.release();
2035
2036 FD->setInClassInitializer(InitExpr);
2037}
2038
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002039/// \brief Find the direct and/or virtual base specifiers that
2040/// correspond to the given base type, for use in base initialization
2041/// within a constructor.
2042static bool FindBaseInitializer(Sema &SemaRef,
2043 CXXRecordDecl *ClassDecl,
2044 QualType BaseType,
2045 const CXXBaseSpecifier *&DirectBaseSpec,
2046 const CXXBaseSpecifier *&VirtualBaseSpec) {
2047 // First, check for a direct base class.
2048 DirectBaseSpec = 0;
2049 for (CXXRecordDecl::base_class_const_iterator Base
2050 = ClassDecl->bases_begin();
2051 Base != ClassDecl->bases_end(); ++Base) {
2052 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2053 // We found a direct base of this type. That's what we're
2054 // initializing.
2055 DirectBaseSpec = &*Base;
2056 break;
2057 }
2058 }
2059
2060 // Check for a virtual base class.
2061 // FIXME: We might be able to short-circuit this if we know in advance that
2062 // there are no virtual bases.
2063 VirtualBaseSpec = 0;
2064 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2065 // We haven't found a base yet; search the class hierarchy for a
2066 // virtual base class.
2067 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2068 /*DetectVirtual=*/false);
2069 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2070 BaseType, Paths)) {
2071 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2072 Path != Paths.end(); ++Path) {
2073 if (Path->back().Base->isVirtual()) {
2074 VirtualBaseSpec = Path->back().Base;
2075 break;
2076 }
2077 }
2078 }
2079 }
2080
2081 return DirectBaseSpec || VirtualBaseSpec;
2082}
2083
Sebastian Redl6df65482011-09-24 17:48:25 +00002084/// \brief Handle a C++ member initializer using braced-init-list syntax.
2085MemInitResult
2086Sema::ActOnMemInitializer(Decl *ConstructorD,
2087 Scope *S,
2088 CXXScopeSpec &SS,
2089 IdentifierInfo *MemberOrBase,
2090 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002091 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002092 SourceLocation IdLoc,
2093 Expr *InitList,
2094 SourceLocation EllipsisLoc) {
2095 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002096 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002097 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002098}
2099
2100/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002101MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002102Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002103 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002104 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002105 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002106 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002107 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002108 SourceLocation IdLoc,
2109 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002110 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002111 SourceLocation RParenLoc,
2112 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002113 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2114 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002115 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002116 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002117 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002118}
2119
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002120namespace {
2121
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002122// Callback to only accept typo corrections that can be a valid C++ member
2123// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002124class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2125 public:
2126 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2127 : ClassDecl(ClassDecl) {}
2128
2129 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2130 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2131 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2132 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2133 else
2134 return isa<TypeDecl>(ND);
2135 }
2136 return false;
2137 }
2138
2139 private:
2140 CXXRecordDecl *ClassDecl;
2141};
2142
2143}
2144
Sebastian Redl6df65482011-09-24 17:48:25 +00002145/// \brief Handle a C++ member initializer.
2146MemInitResult
2147Sema::BuildMemInitializer(Decl *ConstructorD,
2148 Scope *S,
2149 CXXScopeSpec &SS,
2150 IdentifierInfo *MemberOrBase,
2151 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002152 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002153 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002154 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002155 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002156 if (!ConstructorD)
2157 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002159 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002160
2161 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002162 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002163 if (!Constructor) {
2164 // The user wrote a constructor initializer on a function that is
2165 // not a C++ constructor. Ignore the error for now, because we may
2166 // have more member initializers coming; we'll diagnose it just
2167 // once in ActOnMemInitializers.
2168 return true;
2169 }
2170
2171 CXXRecordDecl *ClassDecl = Constructor->getParent();
2172
2173 // C++ [class.base.init]p2:
2174 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002175 // constructor's class and, if not found in that scope, are looked
2176 // up in the scope containing the constructor's definition.
2177 // [Note: if the constructor's class contains a member with the
2178 // same name as a direct or virtual base class of the class, a
2179 // mem-initializer-id naming the member or base class and composed
2180 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002181 // mem-initializer-id for the hidden base class may be specified
2182 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002183 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002184 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002185 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002186 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002187 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002188 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002189 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2190 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002191 if (EllipsisLoc.isValid())
2192 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002193 << MemberOrBase
2194 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002195
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002196 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002197 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002198 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002199 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002200 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002201 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002202 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002203
2204 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002205 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002206 } else if (DS.getTypeSpecType() == TST_decltype) {
2207 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002208 } else {
2209 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2210 LookupParsedName(R, S, &SS);
2211
2212 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2213 if (!TyD) {
2214 if (R.isAmbiguous()) return true;
2215
John McCallfd225442010-04-09 19:01:14 +00002216 // We don't want access-control diagnostics here.
2217 R.suppressDiagnostics();
2218
Douglas Gregor7a886e12010-01-19 06:46:48 +00002219 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2220 bool NotUnknownSpecialization = false;
2221 DeclContext *DC = computeDeclContext(SS, false);
2222 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2223 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2224
2225 if (!NotUnknownSpecialization) {
2226 // When the scope specifier can refer to a member of an unknown
2227 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002228 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2229 SS.getWithLocInContext(Context),
2230 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002231 if (BaseType.isNull())
2232 return true;
2233
Douglas Gregor7a886e12010-01-19 06:46:48 +00002234 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002235 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002236 }
2237 }
2238
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002239 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002240 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002241 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002242 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002243 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002244 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002245 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2246 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002247 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002248 // We have found a non-static data member with a similar
2249 // name to what was typed; complain and initialize that
2250 // member.
2251 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2252 << MemberOrBase << true << CorrectedQuotedStr
2253 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2254 Diag(Member->getLocation(), diag::note_previous_decl)
2255 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002256
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002257 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002258 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002259 const CXXBaseSpecifier *DirectBaseSpec;
2260 const CXXBaseSpecifier *VirtualBaseSpec;
2261 if (FindBaseInitializer(*this, ClassDecl,
2262 Context.getTypeDeclType(Type),
2263 DirectBaseSpec, VirtualBaseSpec)) {
2264 // We have found a direct or virtual base class with a
2265 // similar name to what was typed; complain and initialize
2266 // that base class.
2267 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002268 << MemberOrBase << false << CorrectedQuotedStr
2269 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002270
2271 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2272 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002273 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002274 diag::note_base_class_specified_here)
2275 << BaseSpec->getType()
2276 << BaseSpec->getSourceRange();
2277
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002278 TyD = Type;
2279 }
2280 }
2281 }
2282
Douglas Gregor7a886e12010-01-19 06:46:48 +00002283 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002284 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002285 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002286 return true;
2287 }
John McCall2b194412009-12-21 10:41:20 +00002288 }
2289
Douglas Gregor7a886e12010-01-19 06:46:48 +00002290 if (BaseType.isNull()) {
2291 BaseType = Context.getTypeDeclType(TyD);
2292 if (SS.isSet()) {
2293 NestedNameSpecifier *Qualifier =
2294 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002295
Douglas Gregor7a886e12010-01-19 06:46:48 +00002296 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002297 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002298 }
John McCall2b194412009-12-21 10:41:20 +00002299 }
2300 }
Mike Stump1eb44332009-09-09 15:08:12 +00002301
John McCalla93c9342009-12-07 02:54:59 +00002302 if (!TInfo)
2303 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002304
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002305 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002306}
2307
Chandler Carruth81c64772011-09-03 01:14:15 +00002308/// Checks a member initializer expression for cases where reference (or
2309/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002310static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2311 Expr *Init,
2312 SourceLocation IdLoc) {
2313 QualType MemberTy = Member->getType();
2314
2315 // We only handle pointers and references currently.
2316 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2317 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2318 return;
2319
2320 const bool IsPointer = MemberTy->isPointerType();
2321 if (IsPointer) {
2322 if (const UnaryOperator *Op
2323 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2324 // The only case we're worried about with pointers requires taking the
2325 // address.
2326 if (Op->getOpcode() != UO_AddrOf)
2327 return;
2328
2329 Init = Op->getSubExpr();
2330 } else {
2331 // We only handle address-of expression initializers for pointers.
2332 return;
2333 }
2334 }
2335
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002336 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2337 // Taking the address of a temporary will be diagnosed as a hard error.
2338 if (IsPointer)
2339 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002340
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002341 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2342 << Member << Init->getSourceRange();
2343 } else if (const DeclRefExpr *DRE
2344 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2345 // We only warn when referring to a non-reference parameter declaration.
2346 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2347 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002348 return;
2349
2350 S.Diag(Init->getExprLoc(),
2351 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2352 : diag::warn_bind_ref_member_to_parameter)
2353 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002354 } else {
2355 // Other initializers are fine.
2356 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002357 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002358
2359 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2360 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002361}
2362
John McCallf312b1e2010-08-26 23:41:50 +00002363MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002364Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002365 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002366 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2367 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2368 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002369 "Member must be a FieldDecl or IndirectFieldDecl");
2370
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002371 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002372 return true;
2373
Douglas Gregor464b2f02010-11-05 22:21:31 +00002374 if (Member->isInvalidDecl())
2375 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002376
John McCallb4190042009-11-04 23:02:40 +00002377 // Diagnose value-uses of fields to initialize themselves, e.g.
2378 // foo(foo)
2379 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002380 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002381 Expr **Args;
2382 unsigned NumArgs;
2383 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2384 Args = ParenList->getExprs();
2385 NumArgs = ParenList->getNumExprs();
Richard Smithc83c2302012-12-19 01:39:02 +00002386 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002387 Args = InitList->getInits();
2388 NumArgs = InitList->getNumInits();
Richard Smithc83c2302012-12-19 01:39:02 +00002389 } else {
2390 // Template instantiation doesn't reconstruct ParenListExprs for us.
2391 Args = &Init;
2392 NumArgs = 1;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002393 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002394
Richard Trieude5e75c2012-06-14 23:11:34 +00002395 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2396 != DiagnosticsEngine::Ignored)
2397 for (unsigned i = 0; i < NumArgs; ++i)
2398 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002399 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002400 // initializing the i'th field, throw a warning if any of the >= i'th
2401 // fields are used, as they are not yet initialized.
2402 // Right now we are only handling the case where the i'th field uses
2403 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002404 // Also need to take into account that some fields may be initialized by
2405 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002406 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002407
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002408 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002409
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002410 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002411 // Can't check initialization for a member of dependent type or when
2412 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002413 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002414 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002415 bool InitList = false;
2416 if (isa<InitListExpr>(Init)) {
2417 InitList = true;
2418 Args = &Init;
2419 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002420
2421 if (isStdInitializerList(Member->getType(), 0)) {
2422 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2423 << /*at end of ctor*/1 << InitRange;
2424 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002425 }
2426
Chandler Carruth894aed92010-12-06 09:23:57 +00002427 // Initialize the member.
2428 InitializedEntity MemberEntity =
2429 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2430 : InitializedEntity::InitializeMember(IndirectMember, 0);
2431 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002432 InitList ? InitializationKind::CreateDirectList(IdLoc)
2433 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2434 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002435
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002436 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2437 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002438 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002439 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002440 if (MemberInit.isInvalid())
2441 return true;
2442
Richard Smith41956372013-01-14 22:39:08 +00002443 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002444 // The initialization of each base and member constitutes a
2445 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002446 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002447 if (MemberInit.isInvalid())
2448 return true;
2449
Richard Smithc83c2302012-12-19 01:39:02 +00002450 Init = MemberInit.get();
2451 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002452 }
2453
Chandler Carruth894aed92010-12-06 09:23:57 +00002454 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002455 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2456 InitRange.getBegin(), Init,
2457 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002458 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002459 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2460 InitRange.getBegin(), Init,
2461 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002462 }
Eli Friedman59c04372009-07-29 19:44:27 +00002463}
2464
John McCallf312b1e2010-08-26 23:41:50 +00002465MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002466Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002467 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002468 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002469 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002470 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002471 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002472 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002473
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002474 bool InitList = true;
2475 Expr **Args = &Init;
2476 unsigned NumArgs = 1;
2477 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2478 InitList = false;
2479 Args = ParenList->getExprs();
2480 NumArgs = ParenList->getNumExprs();
2481 }
2482
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002483 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002484 // Initialize the object.
2485 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2486 QualType(ClassDecl->getTypeForDecl(), 0));
2487 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002488 InitList ? InitializationKind::CreateDirectList(NameLoc)
2489 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2490 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002491 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2492 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002493 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002494 0);
Sean Hunt41717662011-02-26 19:13:13 +00002495 if (DelegationInit.isInvalid())
2496 return true;
2497
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002498 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2499 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002500
Richard Smith41956372013-01-14 22:39:08 +00002501 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002502 // The initialization of each base and member constitutes a
2503 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002504 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2505 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002506 if (DelegationInit.isInvalid())
2507 return true;
2508
Eli Friedmand21016f2012-05-19 23:35:23 +00002509 // If we are in a dependent context, template instantiation will
2510 // perform this type-checking again. Just save the arguments that we
2511 // received in a ParenListExpr.
2512 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2513 // of the information that we have about the base
2514 // initializer. However, deconstructing the ASTs is a dicey process,
2515 // and this approach is far more likely to get the corner cases right.
2516 if (CurContext->isDependentContext())
2517 DelegationInit = Owned(Init);
2518
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002519 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002520 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002521 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002522}
2523
2524MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002525Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002526 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002527 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002528 SourceLocation BaseLoc
2529 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002530
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002531 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2532 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2533 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2534
2535 // C++ [class.base.init]p2:
2536 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002537 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002538 // of that class, the mem-initializer is ill-formed. A
2539 // mem-initializer-list can initialize a base class using any
2540 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002541 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002542
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002543 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002544 if (EllipsisLoc.isValid()) {
2545 // This is a pack expansion.
2546 if (!BaseType->containsUnexpandedParameterPack()) {
2547 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002548 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002549
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002550 EllipsisLoc = SourceLocation();
2551 }
2552 } else {
2553 // Check for any unexpanded parameter packs.
2554 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2555 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002556
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002557 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002558 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002559 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002560
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002561 // Check for direct and virtual base classes.
2562 const CXXBaseSpecifier *DirectBaseSpec = 0;
2563 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2564 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002565 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2566 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002567 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002568
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002569 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2570 VirtualBaseSpec);
2571
2572 // C++ [base.class.init]p2:
2573 // Unless the mem-initializer-id names a nonstatic data member of the
2574 // constructor's class or a direct or virtual base of that class, the
2575 // mem-initializer is ill-formed.
2576 if (!DirectBaseSpec && !VirtualBaseSpec) {
2577 // If the class has any dependent bases, then it's possible that
2578 // one of those types will resolve to the same type as
2579 // BaseType. Therefore, just treat this as a dependent base
2580 // class initialization. FIXME: Should we try to check the
2581 // initialization anyway? It seems odd.
2582 if (ClassDecl->hasAnyDependentBases())
2583 Dependent = true;
2584 else
2585 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2586 << BaseType << Context.getTypeDeclType(ClassDecl)
2587 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2588 }
2589 }
2590
2591 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002592 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002593
Sebastian Redl6df65482011-09-24 17:48:25 +00002594 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2595 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002596 InitRange.getBegin(), Init,
2597 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002598 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002599
2600 // C++ [base.class.init]p2:
2601 // If a mem-initializer-id is ambiguous because it designates both
2602 // a direct non-virtual base class and an inherited virtual base
2603 // class, the mem-initializer is ill-formed.
2604 if (DirectBaseSpec && VirtualBaseSpec)
2605 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002606 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002607
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002608 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002609 if (!BaseSpec)
2610 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2611
2612 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002613 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002614 Expr **Args = &Init;
2615 unsigned NumArgs = 1;
2616 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002617 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002618 Args = ParenList->getExprs();
2619 NumArgs = ParenList->getNumExprs();
2620 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002621
2622 InitializedEntity BaseEntity =
2623 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2624 InitializationKind Kind =
2625 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2626 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2627 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002628 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2629 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002630 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002631 if (BaseInit.isInvalid())
2632 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002633
Richard Smith41956372013-01-14 22:39:08 +00002634 // C++11 [class.base.init]p7:
2635 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002636 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002637 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002638 if (BaseInit.isInvalid())
2639 return true;
2640
2641 // If we are in a dependent context, template instantiation will
2642 // perform this type-checking again. Just save the arguments that we
2643 // received in a ParenListExpr.
2644 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2645 // of the information that we have about the base
2646 // initializer. However, deconstructing the ASTs is a dicey process,
2647 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002648 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002649 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002650
Sean Huntcbb67482011-01-08 20:30:50 +00002651 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002652 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002653 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002654 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002655 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002656}
2657
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002658// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002659static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2660 if (T.isNull()) T = E->getType();
2661 QualType TargetType = SemaRef.BuildReferenceType(
2662 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002663 SourceLocation ExprLoc = E->getLocStart();
2664 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2665 TargetType, ExprLoc);
2666
2667 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2668 SourceRange(ExprLoc, ExprLoc),
2669 E->getSourceRange()).take();
2670}
2671
Anders Carlssone5ef7402010-04-23 03:10:23 +00002672/// ImplicitInitializerKind - How an implicit base or member initializer should
2673/// initialize its base or member.
2674enum ImplicitInitializerKind {
2675 IIK_Default,
2676 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002677 IIK_Move,
2678 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002679};
2680
Anders Carlssondefefd22010-04-23 02:00:02 +00002681static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002682BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002683 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002684 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002685 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002686 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002687 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002688 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2689 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002690
John McCall60d7b3a2010-08-24 06:29:42 +00002691 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002692
2693 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002694 case IIK_Inherit: {
2695 const CXXRecordDecl *Inherited =
2696 Constructor->getInheritedConstructor()->getParent();
2697 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2698 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2699 // C++11 [class.inhctor]p8:
2700 // Each expression in the expression-list is of the form
2701 // static_cast<T&&>(p), where p is the name of the corresponding
2702 // constructor parameter and T is the declared type of p.
2703 SmallVector<Expr*, 16> Args;
2704 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2705 ParmVarDecl *PD = Constructor->getParamDecl(I);
2706 ExprResult ArgExpr =
2707 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2708 VK_LValue, SourceLocation());
2709 if (ArgExpr.isInvalid())
2710 return true;
2711 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2712 }
2713
2714 InitializationKind InitKind = InitializationKind::CreateDirect(
2715 Constructor->getLocation(), SourceLocation(), SourceLocation());
2716 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2717 Args.data(), Args.size());
2718 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2719 break;
2720 }
2721 }
2722 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002723 case IIK_Default: {
2724 InitializationKind InitKind
2725 = InitializationKind::CreateDefault(Constructor->getLocation());
2726 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002727 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002728 break;
2729 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002730
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002731 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002732 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002733 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002734 ParmVarDecl *Param = Constructor->getParamDecl(0);
2735 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002736
Anders Carlssone5ef7402010-04-23 03:10:23 +00002737 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002738 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002739 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002740 Constructor->getLocation(), ParamType,
2741 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002742
Eli Friedman5f2987c2012-02-02 03:46:19 +00002743 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2744
Anders Carlssonc7957502010-04-24 22:02:54 +00002745 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002746 QualType ArgTy =
2747 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2748 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002749
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002750 if (Moving) {
2751 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2752 }
2753
John McCallf871d0c2010-08-07 06:22:56 +00002754 CXXCastPath BasePath;
2755 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002756 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2757 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002758 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002759 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002760
Anders Carlssone5ef7402010-04-23 03:10:23 +00002761 InitializationKind InitKind
2762 = InitializationKind::CreateDirect(Constructor->getLocation(),
2763 SourceLocation(), SourceLocation());
2764 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2765 &CopyCtorArg, 1);
2766 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002767 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002768 break;
2769 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002770 }
John McCall9ae2f072010-08-23 23:25:46 +00002771
Douglas Gregor53c374f2010-12-07 00:41:46 +00002772 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002773 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002774 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002775
Anders Carlssondefefd22010-04-23 02:00:02 +00002776 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002777 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002778 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2779 SourceLocation()),
2780 BaseSpec->isVirtual(),
2781 SourceLocation(),
2782 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002783 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002784 SourceLocation());
2785
Anders Carlssondefefd22010-04-23 02:00:02 +00002786 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002787}
2788
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002789static bool RefersToRValueRef(Expr *MemRef) {
2790 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2791 return Referenced->getType()->isRValueReferenceType();
2792}
2793
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002794static bool
2795BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002796 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002797 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002798 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002799 if (Field->isInvalidDecl())
2800 return true;
2801
Chandler Carruthf186b542010-06-29 23:50:44 +00002802 SourceLocation Loc = Constructor->getLocation();
2803
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002804 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2805 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002806 ParmVarDecl *Param = Constructor->getParamDecl(0);
2807 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002808
2809 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002810 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2811 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002812
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002813 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002814 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002815 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002816 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002817
Eli Friedman5f2987c2012-02-02 03:46:19 +00002818 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2819
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002820 if (Moving) {
2821 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2822 }
2823
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002824 // Build a reference to this field within the parameter.
2825 CXXScopeSpec SS;
2826 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2827 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002828 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2829 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002830 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002831 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002832 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002833 ParamType, Loc,
2834 /*IsArrow=*/false,
2835 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002836 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002837 /*FirstQualifierInScope=*/0,
2838 MemberLookup,
2839 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002840 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002841 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002842
2843 // C++11 [class.copy]p15:
2844 // - if a member m has rvalue reference type T&&, it is direct-initialized
2845 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002846 if (RefersToRValueRef(CtorArg.get())) {
2847 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002848 }
2849
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002850 // When the field we are copying is an array, create index variables for
2851 // each dimension of the array. We use these index variables to subscript
2852 // the source array, and other clients (e.g., CodeGen) will perform the
2853 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002854 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002855 QualType BaseType = Field->getType();
2856 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002857 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002858 while (const ConstantArrayType *Array
2859 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002860 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002861 // Create the iteration variable for this array index.
2862 IdentifierInfo *IterationVarName = 0;
2863 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002864 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002865 llvm::raw_svector_ostream OS(Str);
2866 OS << "__i" << IndexVariables.size();
2867 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2868 }
2869 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002870 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002871 IterationVarName, SizeType,
2872 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002873 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002874 IndexVariables.push_back(IterationVar);
2875
2876 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002877 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002878 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002879 assert(!IterationVarRef.isInvalid() &&
2880 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002881 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2882 assert(!IterationVarRef.isInvalid() &&
2883 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002884
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002885 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002886 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002887 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002888 Loc);
2889 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002890 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002891
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002892 BaseType = Array->getElementType();
2893 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002894
2895 // The array subscript expression is an lvalue, which is wrong for moving.
2896 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002897 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002898
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002899 // Construct the entity that we will be initializing. For an array, this
2900 // will be first element in the array, which may require several levels
2901 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002902 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002903 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002904 if (Indirect)
2905 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2906 else
2907 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002908 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2909 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2910 0,
2911 Entities.back()));
2912
2913 // Direct-initialize to use the copy constructor.
2914 InitializationKind InitKind =
2915 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2916
Sebastian Redl74e611a2011-09-04 18:14:28 +00002917 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002918 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002919 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002920
John McCall60d7b3a2010-08-24 06:29:42 +00002921 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002922 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002923 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002924 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002925 if (MemberInit.isInvalid())
2926 return true;
2927
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002928 if (Indirect) {
2929 assert(IndexVariables.size() == 0 &&
2930 "Indirect field improperly initialized");
2931 CXXMemberInit
2932 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2933 Loc, Loc,
2934 MemberInit.takeAs<Expr>(),
2935 Loc);
2936 } else
2937 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2938 Loc, MemberInit.takeAs<Expr>(),
2939 Loc,
2940 IndexVariables.data(),
2941 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002942 return false;
2943 }
2944
Richard Smith07b0fdc2013-03-18 21:12:30 +00002945 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
2946 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002947
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002948 QualType FieldBaseElementType =
2949 SemaRef.Context.getBaseElementType(Field->getType());
2950
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002951 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002952 InitializedEntity InitEntity
2953 = Indirect? InitializedEntity::InitializeMember(Indirect)
2954 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002955 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002956 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002957
2958 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002959 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002960 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002961
Douglas Gregor53c374f2010-12-07 00:41:46 +00002962 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002963 if (MemberInit.isInvalid())
2964 return true;
2965
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002966 if (Indirect)
2967 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2968 Indirect, Loc,
2969 Loc,
2970 MemberInit.get(),
2971 Loc);
2972 else
2973 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2974 Field, Loc, Loc,
2975 MemberInit.get(),
2976 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002977 return false;
2978 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002979
Sean Hunt1f2f3842011-05-17 00:19:05 +00002980 if (!Field->getParent()->isUnion()) {
2981 if (FieldBaseElementType->isReferenceType()) {
2982 SemaRef.Diag(Constructor->getLocation(),
2983 diag::err_uninitialized_member_in_ctor)
2984 << (int)Constructor->isImplicit()
2985 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2986 << 0 << Field->getDeclName();
2987 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2988 return true;
2989 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002990
Sean Hunt1f2f3842011-05-17 00:19:05 +00002991 if (FieldBaseElementType.isConstQualified()) {
2992 SemaRef.Diag(Constructor->getLocation(),
2993 diag::err_uninitialized_member_in_ctor)
2994 << (int)Constructor->isImplicit()
2995 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2996 << 1 << Field->getDeclName();
2997 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2998 return true;
2999 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003000 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003001
David Blaikie4e4d0842012-03-11 07:00:24 +00003002 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003003 FieldBaseElementType->isObjCRetainableType() &&
3004 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3005 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003006 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003007 // Default-initialize Objective-C pointers to NULL.
3008 CXXMemberInit
3009 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3010 Loc, Loc,
3011 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3012 Loc);
3013 return false;
3014 }
3015
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003016 // Nothing to initialize.
3017 CXXMemberInit = 0;
3018 return false;
3019}
John McCallf1860e52010-05-20 23:23:51 +00003020
3021namespace {
3022struct BaseAndFieldInfo {
3023 Sema &S;
3024 CXXConstructorDecl *Ctor;
3025 bool AnyErrorsInInits;
3026 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003027 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003028 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003029
3030 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3031 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003032 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3033 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003034 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003035 else if (Generated && Ctor->isMoveConstructor())
3036 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003037 else if (Ctor->getInheritedConstructor())
3038 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003039 else
3040 IIK = IIK_Default;
3041 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003042
3043 bool isImplicitCopyOrMove() const {
3044 switch (IIK) {
3045 case IIK_Copy:
3046 case IIK_Move:
3047 return true;
3048
3049 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003050 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003051 return false;
3052 }
David Blaikie30263482012-01-20 21:50:17 +00003053
3054 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003055 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003056
3057 bool addFieldInitializer(CXXCtorInitializer *Init) {
3058 AllToInit.push_back(Init);
3059
3060 // Check whether this initializer makes the field "used".
3061 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
3062 S.UnusedPrivateFields.remove(Init->getAnyMember());
3063
3064 return false;
3065 }
John McCallf1860e52010-05-20 23:23:51 +00003066};
3067}
3068
Richard Smitha4950662011-09-19 13:34:43 +00003069/// \brief Determine whether the given indirect field declaration is somewhere
3070/// within an anonymous union.
3071static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3072 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3073 CEnd = F->chain_end();
3074 C != CEnd; ++C)
3075 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3076 if (Record->isUnion())
3077 return true;
3078
3079 return false;
3080}
3081
Douglas Gregorddb21472011-11-02 23:04:16 +00003082/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3083/// array type.
3084static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3085 if (T->isIncompleteArrayType())
3086 return true;
3087
3088 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3089 if (!ArrayT->getSize())
3090 return true;
3091
3092 T = ArrayT->getElementType();
3093 }
3094
3095 return false;
3096}
3097
Richard Smith7a614d82011-06-11 17:19:42 +00003098static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003099 FieldDecl *Field,
3100 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003101
Chandler Carruthe861c602010-06-30 02:59:29 +00003102 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003103 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3104 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003105
Richard Smith0b8220a2012-08-07 21:30:42 +00003106 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003107 // has a brace-or-equal-initializer, the entity is initialized as specified
3108 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003109 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003110 CXXCtorInitializer *Init;
3111 if (Indirect)
3112 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3113 SourceLocation(),
3114 SourceLocation(), 0,
3115 SourceLocation());
3116 else
3117 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3118 SourceLocation(),
3119 SourceLocation(), 0,
3120 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003121 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003122 }
3123
Richard Smithc115f632011-09-18 11:14:50 +00003124 // Don't build an implicit initializer for union members if none was
3125 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003126 if (Field->getParent()->isUnion() ||
3127 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003128 return false;
3129
Douglas Gregorddb21472011-11-02 23:04:16 +00003130 // Don't initialize incomplete or zero-length arrays.
3131 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3132 return false;
3133
John McCallf1860e52010-05-20 23:23:51 +00003134 // Don't try to build an implicit initializer if there were semantic
3135 // errors in any of the initializers (and therefore we might be
3136 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003137 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003138 return false;
3139
Sean Huntcbb67482011-01-08 20:30:50 +00003140 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003141 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3142 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003143 return true;
John McCallf1860e52010-05-20 23:23:51 +00003144
Richard Smith0b8220a2012-08-07 21:30:42 +00003145 if (!Init)
3146 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003147
Richard Smith0b8220a2012-08-07 21:30:42 +00003148 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003149}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003150
3151bool
3152Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3153 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003154 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003155 Constructor->setNumCtorInitializers(1);
3156 CXXCtorInitializer **initializer =
3157 new (Context) CXXCtorInitializer*[1];
3158 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3159 Constructor->setCtorInitializers(initializer);
3160
Sean Huntb76af9c2011-05-03 23:05:34 +00003161 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003162 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003163 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3164 }
3165
Sean Huntc1598702011-05-05 00:05:47 +00003166 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003167
Sean Hunt059ce0d2011-05-01 07:04:31 +00003168 return false;
3169}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003170
David Blaikie93c86172013-01-17 05:26:25 +00003171bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3172 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003173 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003174 // Just store the initializers as written, they will be checked during
3175 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003176 if (!Initializers.empty()) {
3177 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003178 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003179 new (Context) CXXCtorInitializer*[Initializers.size()];
3180 memcpy(baseOrMemberInitializers, Initializers.data(),
3181 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003182 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003183 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003184
3185 // Let template instantiation know whether we had errors.
3186 if (AnyErrors)
3187 Constructor->setInvalidDecl();
3188
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003189 return false;
3190 }
3191
John McCallf1860e52010-05-20 23:23:51 +00003192 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003193
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003194 // We need to build the initializer AST according to order of construction
3195 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003196 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003197 if (!ClassDecl)
3198 return true;
3199
Eli Friedman80c30da2009-11-09 19:20:36 +00003200 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003201
David Blaikie93c86172013-01-17 05:26:25 +00003202 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003203 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003204
3205 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003206 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003207 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003208 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003209 }
3210
Anders Carlsson711f34a2010-04-21 19:52:01 +00003211 // Keep track of the direct virtual bases.
3212 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3213 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3214 E = ClassDecl->bases_end(); I != E; ++I) {
3215 if (I->isVirtual())
3216 DirectVBases.insert(I);
3217 }
3218
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003219 // Push virtual bases before others.
3220 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3221 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3222
Sean Huntcbb67482011-01-08 20:30:50 +00003223 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003224 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3225 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003226 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003227 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003228 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003229 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003230 VBase, IsInheritedVirtualBase,
3231 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003232 HadError = true;
3233 continue;
3234 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003235
John McCallf1860e52010-05-20 23:23:51 +00003236 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003237 }
3238 }
Mike Stump1eb44332009-09-09 15:08:12 +00003239
John McCallf1860e52010-05-20 23:23:51 +00003240 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003241 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3242 E = ClassDecl->bases_end(); Base != E; ++Base) {
3243 // Virtuals are in the virtual base list and already constructed.
3244 if (Base->isVirtual())
3245 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003246
Sean Huntcbb67482011-01-08 20:30:50 +00003247 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003248 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3249 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003250 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003251 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003252 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003253 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003254 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003255 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003256 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003257 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003258
John McCallf1860e52010-05-20 23:23:51 +00003259 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003260 }
3261 }
Mike Stump1eb44332009-09-09 15:08:12 +00003262
John McCallf1860e52010-05-20 23:23:51 +00003263 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003264 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3265 MemEnd = ClassDecl->decls_end();
3266 Mem != MemEnd; ++Mem) {
3267 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003268 // C++ [class.bit]p2:
3269 // A declaration for a bit-field that omits the identifier declares an
3270 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3271 // initialized.
3272 if (F->isUnnamedBitfield())
3273 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003274
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003275 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003276 // handle anonymous struct/union fields based on their individual
3277 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003278 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003279 continue;
3280
3281 if (CollectFieldInitializer(*this, Info, F))
3282 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003283 continue;
3284 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003285
3286 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003287 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003288 continue;
3289
3290 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3291 if (F->getType()->isIncompleteArrayType()) {
3292 assert(ClassDecl->hasFlexibleArrayMember() &&
3293 "Incomplete array type is not valid");
3294 continue;
3295 }
3296
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003297 // Initialize each field of an anonymous struct individually.
3298 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3299 HadError = true;
3300
3301 continue;
3302 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003303 }
Mike Stump1eb44332009-09-09 15:08:12 +00003304
David Blaikie93c86172013-01-17 05:26:25 +00003305 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003306 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003307 Constructor->setNumCtorInitializers(NumInitializers);
3308 CXXCtorInitializer **baseOrMemberInitializers =
3309 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003310 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003311 NumInitializers * sizeof(CXXCtorInitializer*));
3312 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003313
John McCallef027fe2010-03-16 21:39:52 +00003314 // Constructors implicitly reference the base and member
3315 // destructors.
3316 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3317 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003318 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003319
3320 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003321}
3322
David Blaikieee000bb2013-01-17 08:49:22 +00003323static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003324 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003325 const RecordDecl *RD = RT->getDecl();
3326 if (RD->isAnonymousStructOrUnion()) {
3327 for (RecordDecl::field_iterator Field = RD->field_begin(),
3328 E = RD->field_end(); Field != E; ++Field)
3329 PopulateKeysForFields(*Field, IdealInits);
3330 return;
3331 }
Eli Friedman6347f422009-07-21 19:28:10 +00003332 }
David Blaikieee000bb2013-01-17 08:49:22 +00003333 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003334}
3335
Anders Carlssonea356fb2010-04-02 05:42:15 +00003336static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003337 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003338}
3339
Anders Carlssonea356fb2010-04-02 05:42:15 +00003340static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003341 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003342 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003343 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003344
David Blaikieee000bb2013-01-17 08:49:22 +00003345 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003346}
3347
David Blaikie93c86172013-01-17 05:26:25 +00003348static void DiagnoseBaseOrMemInitializerOrder(
3349 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3350 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003351 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003352 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003353
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003354 // Don't check initializers order unless the warning is enabled at the
3355 // location of at least one initializer.
3356 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003357 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003358 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003359 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3360 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003361 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003362 ShouldCheckOrder = true;
3363 break;
3364 }
3365 }
3366 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003367 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003368
John McCalld6ca8da2010-04-10 07:37:23 +00003369 // Build the list of bases and members in the order that they'll
3370 // actually be initialized. The explicit initializers should be in
3371 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003372 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003373
Anders Carlsson071d6102010-04-02 03:38:04 +00003374 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3375
John McCalld6ca8da2010-04-10 07:37:23 +00003376 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003377 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003378 ClassDecl->vbases_begin(),
3379 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003380 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003381
John McCalld6ca8da2010-04-10 07:37:23 +00003382 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003383 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003384 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003385 if (Base->isVirtual())
3386 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003387 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003388 }
Mike Stump1eb44332009-09-09 15:08:12 +00003389
John McCalld6ca8da2010-04-10 07:37:23 +00003390 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003391 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003392 E = ClassDecl->field_end(); Field != E; ++Field) {
3393 if (Field->isUnnamedBitfield())
3394 continue;
3395
David Blaikieee000bb2013-01-17 08:49:22 +00003396 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003397 }
3398
John McCalld6ca8da2010-04-10 07:37:23 +00003399 unsigned NumIdealInits = IdealInitKeys.size();
3400 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003401
Sean Huntcbb67482011-01-08 20:30:50 +00003402 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003403 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003404 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003405 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003406
3407 // Scan forward to try to find this initializer in the idealized
3408 // initializers list.
3409 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3410 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003411 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003412
3413 // If we didn't find this initializer, it must be because we
3414 // scanned past it on a previous iteration. That can only
3415 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003416 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003417 Sema::SemaDiagnosticBuilder D =
3418 SemaRef.Diag(PrevInit->getSourceLocation(),
3419 diag::warn_initializer_out_of_order);
3420
Francois Pichet00eb3f92010-12-04 09:14:42 +00003421 if (PrevInit->isAnyMemberInitializer())
3422 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003423 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003424 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003425
Francois Pichet00eb3f92010-12-04 09:14:42 +00003426 if (Init->isAnyMemberInitializer())
3427 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003428 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003429 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003430
3431 // Move back to the initializer's location in the ideal list.
3432 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3433 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003434 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003435
3436 assert(IdealIndex != NumIdealInits &&
3437 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003438 }
John McCalld6ca8da2010-04-10 07:37:23 +00003439
3440 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003441 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003442}
3443
John McCall3c3ccdb2010-04-10 09:28:51 +00003444namespace {
3445bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003446 CXXCtorInitializer *Init,
3447 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003448 if (!PrevInit) {
3449 PrevInit = Init;
3450 return false;
3451 }
3452
Douglas Gregordc392c12013-03-25 23:28:23 +00003453 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003454 S.Diag(Init->getSourceLocation(),
3455 diag::err_multiple_mem_initialization)
3456 << Field->getDeclName()
3457 << Init->getSourceRange();
3458 else {
John McCallf4c73712011-01-19 06:33:43 +00003459 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003460 assert(BaseClass && "neither field nor base");
3461 S.Diag(Init->getSourceLocation(),
3462 diag::err_multiple_base_initialization)
3463 << QualType(BaseClass, 0)
3464 << Init->getSourceRange();
3465 }
3466 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3467 << 0 << PrevInit->getSourceRange();
3468
3469 return true;
3470}
3471
Sean Huntcbb67482011-01-08 20:30:50 +00003472typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003473typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3474
3475bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003476 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003477 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003478 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003479 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003480 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003481
3482 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003483 if (Parent->isUnion()) {
3484 UnionEntry &En = Unions[Parent];
3485 if (En.first && En.first != Child) {
3486 S.Diag(Init->getSourceLocation(),
3487 diag::err_multiple_mem_union_initialization)
3488 << Field->getDeclName()
3489 << Init->getSourceRange();
3490 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3491 << 0 << En.second->getSourceRange();
3492 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003493 }
3494 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003495 En.first = Child;
3496 En.second = Init;
3497 }
David Blaikie6fe29652011-11-17 06:01:57 +00003498 if (!Parent->isAnonymousStructOrUnion())
3499 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003500 }
3501
3502 Child = Parent;
3503 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003504 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003505
3506 return false;
3507}
3508}
3509
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003510/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003511void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003512 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003513 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003514 bool AnyErrors) {
3515 if (!ConstructorDecl)
3516 return;
3517
3518 AdjustDeclIfTemplate(ConstructorDecl);
3519
3520 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003521 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003522
3523 if (!Constructor) {
3524 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3525 return;
3526 }
3527
John McCall3c3ccdb2010-04-10 09:28:51 +00003528 // Mapping for the duplicate initializers check.
3529 // For member initializers, this is keyed with a FieldDecl*.
3530 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003531 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003532
3533 // Mapping for the inconsistent anonymous-union initializers check.
3534 RedundantUnionMap MemberUnions;
3535
Anders Carlssonea356fb2010-04-02 05:42:15 +00003536 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003537 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003538 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003539
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003540 // Set the source order index.
3541 Init->setSourceOrder(i);
3542
Francois Pichet00eb3f92010-12-04 09:14:42 +00003543 if (Init->isAnyMemberInitializer()) {
3544 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003545 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3546 CheckRedundantUnionInit(*this, Init, MemberUnions))
3547 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003548 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003549 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3550 if (CheckRedundantInit(*this, Init, Members[Key]))
3551 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003552 } else {
3553 assert(Init->isDelegatingInitializer());
3554 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003555 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003556 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003557 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003558 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003559 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003560 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003561 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003562 // Return immediately as the initializer is set.
3563 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003564 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003565 }
3566
Anders Carlssonea356fb2010-04-02 05:42:15 +00003567 if (HadError)
3568 return;
3569
David Blaikie93c86172013-01-17 05:26:25 +00003570 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003571
David Blaikie93c86172013-01-17 05:26:25 +00003572 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003573}
3574
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003575void
John McCallef027fe2010-03-16 21:39:52 +00003576Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3577 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003578 // Ignore dependent contexts. Also ignore unions, since their members never
3579 // have destructors implicitly called.
3580 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003581 return;
John McCall58e6f342010-03-16 05:22:47 +00003582
3583 // FIXME: all the access-control diagnostics are positioned on the
3584 // field/base declaration. That's probably good; that said, the
3585 // user might reasonably want to know why the destructor is being
3586 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003587
Anders Carlsson9f853df2009-11-17 04:44:12 +00003588 // Non-static data members.
3589 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3590 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003591 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003592 if (Field->isInvalidDecl())
3593 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003594
3595 // Don't destroy incomplete or zero-length arrays.
3596 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3597 continue;
3598
Anders Carlsson9f853df2009-11-17 04:44:12 +00003599 QualType FieldType = Context.getBaseElementType(Field->getType());
3600
3601 const RecordType* RT = FieldType->getAs<RecordType>();
3602 if (!RT)
3603 continue;
3604
3605 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003606 if (FieldClassDecl->isInvalidDecl())
3607 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003608 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003609 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003610 // The destructor for an implicit anonymous union member is never invoked.
3611 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3612 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003613
Douglas Gregordb89f282010-07-01 22:47:18 +00003614 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003615 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003616 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003617 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003618 << Field->getDeclName()
3619 << FieldType);
3620
Eli Friedman5f2987c2012-02-02 03:46:19 +00003621 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003622 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003623 }
3624
John McCall58e6f342010-03-16 05:22:47 +00003625 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3626
Anders Carlsson9f853df2009-11-17 04:44:12 +00003627 // Bases.
3628 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3629 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003630 // Bases are always records in a well-formed non-dependent class.
3631 const RecordType *RT = Base->getType()->getAs<RecordType>();
3632
3633 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003634 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003635 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003636
John McCall58e6f342010-03-16 05:22:47 +00003637 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003638 // If our base class is invalid, we probably can't get its dtor anyway.
3639 if (BaseClassDecl->isInvalidDecl())
3640 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003641 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003642 continue;
John McCall58e6f342010-03-16 05:22:47 +00003643
Douglas Gregordb89f282010-07-01 22:47:18 +00003644 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003645 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003646
3647 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003648 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003649 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003650 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003651 << Base->getSourceRange(),
3652 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003653
Eli Friedman5f2987c2012-02-02 03:46:19 +00003654 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003655 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003656 }
3657
3658 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003659 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3660 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003661
3662 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003663 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003664
3665 // Ignore direct virtual bases.
3666 if (DirectVirtualBases.count(RT))
3667 continue;
3668
John McCall58e6f342010-03-16 05:22:47 +00003669 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003670 // If our base class is invalid, we probably can't get its dtor anyway.
3671 if (BaseClassDecl->isInvalidDecl())
3672 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003673 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003674 continue;
John McCall58e6f342010-03-16 05:22:47 +00003675
Douglas Gregordb89f282010-07-01 22:47:18 +00003676 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003677 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003678 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003679 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003680 << VBase->getType(),
3681 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003682
Eli Friedman5f2987c2012-02-02 03:46:19 +00003683 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003684 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003685 }
3686}
3687
John McCalld226f652010-08-21 09:40:31 +00003688void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003689 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003690 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003691
Mike Stump1eb44332009-09-09 15:08:12 +00003692 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003693 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003694 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003695}
3696
Mike Stump1eb44332009-09-09 15:08:12 +00003697bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003698 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003699 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3700 unsigned DiagID;
3701 AbstractDiagSelID SelID;
3702
3703 public:
3704 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3705 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3706
3707 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003708 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003709 if (SelID == -1)
3710 S.Diag(Loc, DiagID) << T;
3711 else
3712 S.Diag(Loc, DiagID) << SelID << T;
3713 }
3714 } Diagnoser(DiagID, SelID);
3715
3716 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003717}
3718
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003719bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003720 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003721 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003722 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003723
Anders Carlsson11f21a02009-03-23 19:10:31 +00003724 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003725 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003726
Ted Kremenek6217b802009-07-29 21:53:49 +00003727 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003728 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003729 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003730 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003731
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003732 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003733 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003734 }
Mike Stump1eb44332009-09-09 15:08:12 +00003735
Ted Kremenek6217b802009-07-29 21:53:49 +00003736 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003737 if (!RT)
3738 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003739
John McCall86ff3082010-02-04 22:26:26 +00003740 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003741
John McCall94c3b562010-08-18 09:41:07 +00003742 // We can't answer whether something is abstract until it has a
3743 // definition. If it's currently being defined, we'll walk back
3744 // over all the declarations when we have a full definition.
3745 const CXXRecordDecl *Def = RD->getDefinition();
3746 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003747 return false;
3748
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003749 if (!RD->isAbstract())
3750 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003751
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003752 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003753 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003754
John McCall94c3b562010-08-18 09:41:07 +00003755 return true;
3756}
3757
3758void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3759 // Check if we've already emitted the list of pure virtual functions
3760 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003761 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003762 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003763
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003764 CXXFinalOverriderMap FinalOverriders;
3765 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003766
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003767 // Keep a set of seen pure methods so we won't diagnose the same method
3768 // more than once.
3769 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3770
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003771 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3772 MEnd = FinalOverriders.end();
3773 M != MEnd;
3774 ++M) {
3775 for (OverridingMethods::iterator SO = M->second.begin(),
3776 SOEnd = M->second.end();
3777 SO != SOEnd; ++SO) {
3778 // C++ [class.abstract]p4:
3779 // A class is abstract if it contains or inherits at least one
3780 // pure virtual function for which the final overrider is pure
3781 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003782
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003783 //
3784 if (SO->second.size() != 1)
3785 continue;
3786
3787 if (!SO->second.front().Method->isPure())
3788 continue;
3789
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003790 if (!SeenPureMethods.insert(SO->second.front().Method))
3791 continue;
3792
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003793 Diag(SO->second.front().Method->getLocation(),
3794 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003795 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003796 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003797 }
3798
3799 if (!PureVirtualClassDiagSet)
3800 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3801 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003802}
3803
Anders Carlsson8211eff2009-03-24 01:19:16 +00003804namespace {
John McCall94c3b562010-08-18 09:41:07 +00003805struct AbstractUsageInfo {
3806 Sema &S;
3807 CXXRecordDecl *Record;
3808 CanQualType AbstractType;
3809 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003810
John McCall94c3b562010-08-18 09:41:07 +00003811 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3812 : S(S), Record(Record),
3813 AbstractType(S.Context.getCanonicalType(
3814 S.Context.getTypeDeclType(Record))),
3815 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003816
John McCall94c3b562010-08-18 09:41:07 +00003817 void DiagnoseAbstractType() {
3818 if (Invalid) return;
3819 S.DiagnoseAbstractType(Record);
3820 Invalid = true;
3821 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003822
John McCall94c3b562010-08-18 09:41:07 +00003823 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3824};
3825
3826struct CheckAbstractUsage {
3827 AbstractUsageInfo &Info;
3828 const NamedDecl *Ctx;
3829
3830 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3831 : Info(Info), Ctx(Ctx) {}
3832
3833 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3834 switch (TL.getTypeLocClass()) {
3835#define ABSTRACT_TYPELOC(CLASS, PARENT)
3836#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003837 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003838#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003839 }
John McCall94c3b562010-08-18 09:41:07 +00003840 }
Mike Stump1eb44332009-09-09 15:08:12 +00003841
John McCall94c3b562010-08-18 09:41:07 +00003842 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3843 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3844 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003845 if (!TL.getArg(I))
3846 continue;
3847
John McCall94c3b562010-08-18 09:41:07 +00003848 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3849 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003850 }
John McCall94c3b562010-08-18 09:41:07 +00003851 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003852
John McCall94c3b562010-08-18 09:41:07 +00003853 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3854 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3855 }
Mike Stump1eb44332009-09-09 15:08:12 +00003856
John McCall94c3b562010-08-18 09:41:07 +00003857 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3858 // Visit the type parameters from a permissive context.
3859 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3860 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3861 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3862 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3863 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3864 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003865 }
John McCall94c3b562010-08-18 09:41:07 +00003866 }
Mike Stump1eb44332009-09-09 15:08:12 +00003867
John McCall94c3b562010-08-18 09:41:07 +00003868 // Visit pointee types from a permissive context.
3869#define CheckPolymorphic(Type) \
3870 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3871 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3872 }
3873 CheckPolymorphic(PointerTypeLoc)
3874 CheckPolymorphic(ReferenceTypeLoc)
3875 CheckPolymorphic(MemberPointerTypeLoc)
3876 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003877 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003878
John McCall94c3b562010-08-18 09:41:07 +00003879 /// Handle all the types we haven't given a more specific
3880 /// implementation for above.
3881 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3882 // Every other kind of type that we haven't called out already
3883 // that has an inner type is either (1) sugar or (2) contains that
3884 // inner type in some way as a subobject.
3885 if (TypeLoc Next = TL.getNextTypeLoc())
3886 return Visit(Next, Sel);
3887
3888 // If there's no inner type and we're in a permissive context,
3889 // don't diagnose.
3890 if (Sel == Sema::AbstractNone) return;
3891
3892 // Check whether the type matches the abstract type.
3893 QualType T = TL.getType();
3894 if (T->isArrayType()) {
3895 Sel = Sema::AbstractArrayType;
3896 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003897 }
John McCall94c3b562010-08-18 09:41:07 +00003898 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3899 if (CT != Info.AbstractType) return;
3900
3901 // It matched; do some magic.
3902 if (Sel == Sema::AbstractArrayType) {
3903 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3904 << T << TL.getSourceRange();
3905 } else {
3906 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3907 << Sel << T << TL.getSourceRange();
3908 }
3909 Info.DiagnoseAbstractType();
3910 }
3911};
3912
3913void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3914 Sema::AbstractDiagSelID Sel) {
3915 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3916}
3917
3918}
3919
3920/// Check for invalid uses of an abstract type in a method declaration.
3921static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3922 CXXMethodDecl *MD) {
3923 // No need to do the check on definitions, which require that
3924 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003925 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003926 return;
3927
3928 // For safety's sake, just ignore it if we don't have type source
3929 // information. This should never happen for non-implicit methods,
3930 // but...
3931 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3932 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3933}
3934
3935/// Check for invalid uses of an abstract type within a class definition.
3936static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3937 CXXRecordDecl *RD) {
3938 for (CXXRecordDecl::decl_iterator
3939 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3940 Decl *D = *I;
3941 if (D->isImplicit()) continue;
3942
3943 // Methods and method templates.
3944 if (isa<CXXMethodDecl>(D)) {
3945 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3946 } else if (isa<FunctionTemplateDecl>(D)) {
3947 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3948 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3949
3950 // Fields and static variables.
3951 } else if (isa<FieldDecl>(D)) {
3952 FieldDecl *FD = cast<FieldDecl>(D);
3953 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3954 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3955 } else if (isa<VarDecl>(D)) {
3956 VarDecl *VD = cast<VarDecl>(D);
3957 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3958 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3959
3960 // Nested classes and class templates.
3961 } else if (isa<CXXRecordDecl>(D)) {
3962 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3963 } else if (isa<ClassTemplateDecl>(D)) {
3964 CheckAbstractClassUsage(Info,
3965 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3966 }
3967 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003968}
3969
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003970/// \brief Perform semantic checks on a class definition that has been
3971/// completing, introducing implicitly-declared members, checking for
3972/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003973void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003974 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003975 return;
3976
John McCall94c3b562010-08-18 09:41:07 +00003977 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3978 AbstractUsageInfo Info(*this, Record);
3979 CheckAbstractClassUsage(Info, Record);
3980 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003981
3982 // If this is not an aggregate type and has no user-declared constructor,
3983 // complain about any non-static data members of reference or const scalar
3984 // type, since they will never get initializers.
3985 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003986 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3987 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003988 bool Complained = false;
3989 for (RecordDecl::field_iterator F = Record->field_begin(),
3990 FEnd = Record->field_end();
3991 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003992 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003993 continue;
3994
Douglas Gregor325e5932010-04-15 00:00:53 +00003995 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003996 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003997 if (!Complained) {
3998 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3999 << Record->getTagKind() << Record;
4000 Complained = true;
4001 }
4002
4003 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4004 << F->getType()->isReferenceType()
4005 << F->getDeclName();
4006 }
4007 }
4008 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004009
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004010 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004011 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004012
4013 if (Record->getIdentifier()) {
4014 // C++ [class.mem]p13:
4015 // If T is the name of a class, then each of the following shall have a
4016 // name different from T:
4017 // - every member of every anonymous union that is a member of class T.
4018 //
4019 // C++ [class.mem]p14:
4020 // In addition, if class T has a user-declared constructor (12.1), every
4021 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004022 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4023 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4024 ++I) {
4025 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004026 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4027 isa<IndirectFieldDecl>(D)) {
4028 Diag(D->getLocation(), diag::err_member_name_of_class)
4029 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004030 break;
4031 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004032 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004033 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004034
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004035 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004036 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004037 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004038 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004039 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4040 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4041 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004042
David Blaikieb6b5b972012-09-21 03:21:07 +00004043 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4044 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4045 DiagnoseAbstractType(Record);
4046 }
4047
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004048 if (!Record->isDependentType()) {
4049 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4050 MEnd = Record->method_end();
4051 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004052 // See if a method overloads virtual methods in a base
4053 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004054 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004055 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004056
4057 // Check whether the explicitly-defaulted special members are valid.
4058 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4059 CheckExplicitlyDefaultedSpecialMember(*M);
4060
4061 // For an explicitly defaulted or deleted special member, we defer
4062 // determining triviality until the class is complete. That time is now!
4063 if (!M->isImplicit() && !M->isUserProvided()) {
4064 CXXSpecialMember CSM = getSpecialMember(*M);
4065 if (CSM != CXXInvalid) {
4066 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4067
4068 // Inform the class that we've finished declaring this member.
4069 Record->finishedDefaultedOrDeletedMember(*M);
4070 }
4071 }
4072 }
4073 }
4074
4075 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4076 // function that is not a constructor declares that member function to be
4077 // const. [...] The class of which that function is a member shall be
4078 // a literal type.
4079 //
4080 // If the class has virtual bases, any constexpr members will already have
4081 // been diagnosed by the checks performed on the member declaration, so
4082 // suppress this (less useful) diagnostic.
4083 //
4084 // We delay this until we know whether an explicitly-defaulted (or deleted)
4085 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004086 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004087 !Record->isLiteral() && !Record->getNumVBases()) {
4088 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4089 MEnd = Record->method_end();
4090 M != MEnd; ++M) {
4091 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4092 switch (Record->getTemplateSpecializationKind()) {
4093 case TSK_ImplicitInstantiation:
4094 case TSK_ExplicitInstantiationDeclaration:
4095 case TSK_ExplicitInstantiationDefinition:
4096 // If a template instantiates to a non-literal type, but its members
4097 // instantiate to constexpr functions, the template is technically
4098 // ill-formed, but we allow it for sanity.
4099 continue;
4100
4101 case TSK_Undeclared:
4102 case TSK_ExplicitSpecialization:
4103 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4104 diag::err_constexpr_method_non_literal);
4105 break;
4106 }
4107
4108 // Only produce one error per class.
4109 break;
4110 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004111 }
4112 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004113
Richard Smith07b0fdc2013-03-18 21:12:30 +00004114 // Declare inheriting constructors. We do this eagerly here because:
4115 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004116 // constructors from different classes.
4117 // - The lazy declaration of the other implicit constructors is so as to not
4118 // waste space and performance on classes that are not meant to be
4119 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004120 // have inheriting constructors.
4121 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004122}
4123
Richard Smith7756afa2012-06-10 05:43:50 +00004124/// Is the special member function which would be selected to perform the
4125/// specified operation on the specified class type a constexpr constructor?
4126static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4127 Sema::CXXSpecialMember CSM,
4128 bool ConstArg) {
4129 Sema::SpecialMemberOverloadResult *SMOR =
4130 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4131 false, false, false, false);
4132 if (!SMOR || !SMOR->getMethod())
4133 // A constructor we wouldn't select can't be "involved in initializing"
4134 // anything.
4135 return true;
4136 return SMOR->getMethod()->isConstexpr();
4137}
4138
4139/// Determine whether the specified special member function would be constexpr
4140/// if it were implicitly defined.
4141static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4142 Sema::CXXSpecialMember CSM,
4143 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004144 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004145 return false;
4146
4147 // C++11 [dcl.constexpr]p4:
4148 // In the definition of a constexpr constructor [...]
4149 switch (CSM) {
4150 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004151 // Since default constructor lookup is essentially trivial (and cannot
4152 // involve, for instance, template instantiation), we compute whether a
4153 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4154 //
4155 // This is important for performance; we need to know whether the default
4156 // constructor is constexpr to determine whether the type is a literal type.
4157 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4158
Richard Smith7756afa2012-06-10 05:43:50 +00004159 case Sema::CXXCopyConstructor:
4160 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004161 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004162 break;
4163
4164 case Sema::CXXCopyAssignment:
4165 case Sema::CXXMoveAssignment:
4166 case Sema::CXXDestructor:
4167 case Sema::CXXInvalid:
4168 return false;
4169 }
4170
4171 // -- if the class is a non-empty union, or for each non-empty anonymous
4172 // union member of a non-union class, exactly one non-static data member
4173 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004174 //
4175 // If we squint, this is guaranteed, since exactly one non-static data member
4176 // will be initialized (if the constructor isn't deleted), we just don't know
4177 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004178 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004179 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004180
4181 // -- the class shall not have any virtual base classes;
4182 if (ClassDecl->getNumVBases())
4183 return false;
4184
4185 // -- every constructor involved in initializing [...] base class
4186 // sub-objects shall be a constexpr constructor;
4187 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4188 BEnd = ClassDecl->bases_end();
4189 B != BEnd; ++B) {
4190 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4191 if (!BaseType) continue;
4192
4193 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4194 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4195 return false;
4196 }
4197
4198 // -- every constructor involved in initializing non-static data members
4199 // [...] shall be a constexpr constructor;
4200 // -- every non-static data member and base class sub-object shall be
4201 // initialized
4202 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4203 FEnd = ClassDecl->field_end();
4204 F != FEnd; ++F) {
4205 if (F->isInvalidDecl())
4206 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004207 if (const RecordType *RecordTy =
4208 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004209 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4210 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4211 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004212 }
4213 }
4214
4215 // All OK, it's constexpr!
4216 return true;
4217}
4218
Richard Smithb9d0b762012-07-27 04:22:15 +00004219static Sema::ImplicitExceptionSpecification
4220computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4221 switch (S.getSpecialMember(MD)) {
4222 case Sema::CXXDefaultConstructor:
4223 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4224 case Sema::CXXCopyConstructor:
4225 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4226 case Sema::CXXCopyAssignment:
4227 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4228 case Sema::CXXMoveConstructor:
4229 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4230 case Sema::CXXMoveAssignment:
4231 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4232 case Sema::CXXDestructor:
4233 return S.ComputeDefaultedDtorExceptionSpec(MD);
4234 case Sema::CXXInvalid:
4235 break;
4236 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004237 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4238 "only special members have implicit exception specs");
4239 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004240}
4241
Richard Smithdd25e802012-07-30 23:48:14 +00004242static void
4243updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4244 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4245 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4246 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004247 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4248 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004249}
4250
Richard Smithb9d0b762012-07-27 04:22:15 +00004251void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4252 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4253 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4254 return;
4255
Richard Smithdd25e802012-07-30 23:48:14 +00004256 // Evaluate the exception specification.
4257 ImplicitExceptionSpecification ExceptSpec =
4258 computeImplicitExceptionSpec(*this, Loc, MD);
4259
4260 // Update the type of the special member to use it.
4261 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4262
4263 // A user-provided destructor can be defined outside the class. When that
4264 // happens, be sure to update the exception specification on both
4265 // declarations.
4266 const FunctionProtoType *CanonicalFPT =
4267 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4268 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4269 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4270 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004271}
4272
Richard Smith3003e1d2012-05-15 04:39:51 +00004273void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4274 CXXRecordDecl *RD = MD->getParent();
4275 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004276
Richard Smith3003e1d2012-05-15 04:39:51 +00004277 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4278 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004279
4280 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004281 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004282 bool First = MD == MD->getCanonicalDecl();
4283
4284 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004285
4286 // C++11 [dcl.fct.def.default]p1:
4287 // A function that is explicitly defaulted shall
4288 // -- be a special member function (checked elsewhere),
4289 // -- have the same type (except for ref-qualifiers, and except that a
4290 // copy operation can take a non-const reference) as an implicit
4291 // declaration, and
4292 // -- not have default arguments.
4293 unsigned ExpectedParams = 1;
4294 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4295 ExpectedParams = 0;
4296 if (MD->getNumParams() != ExpectedParams) {
4297 // This also checks for default arguments: a copy or move constructor with a
4298 // default argument is classified as a default constructor, and assignment
4299 // operations and destructors can't have default arguments.
4300 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4301 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004302 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004303 } else if (MD->isVariadic()) {
4304 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4305 << CSM << MD->getSourceRange();
4306 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004307 }
4308
Richard Smith3003e1d2012-05-15 04:39:51 +00004309 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004310
Richard Smith7756afa2012-06-10 05:43:50 +00004311 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004312 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004313 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004314 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004315 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004316
Richard Smith3003e1d2012-05-15 04:39:51 +00004317 QualType ReturnType = Context.VoidTy;
4318 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4319 // Check for return type matching.
4320 ReturnType = Type->getResultType();
4321 QualType ExpectedReturnType =
4322 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4323 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4324 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4325 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4326 HadError = true;
4327 }
4328
4329 // A defaulted special member cannot have cv-qualifiers.
4330 if (Type->getTypeQuals()) {
4331 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4332 << (CSM == CXXMoveAssignment);
4333 HadError = true;
4334 }
4335 }
4336
4337 // Check for parameter type matching.
4338 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004339 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004340 if (ExpectedParams && ArgType->isReferenceType()) {
4341 // Argument must be reference to possibly-const T.
4342 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004343 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004344
4345 if (ReferentType.isVolatileQualified()) {
4346 Diag(MD->getLocation(),
4347 diag::err_defaulted_special_member_volatile_param) << CSM;
4348 HadError = true;
4349 }
4350
Richard Smith7756afa2012-06-10 05:43:50 +00004351 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004352 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4353 Diag(MD->getLocation(),
4354 diag::err_defaulted_special_member_copy_const_param)
4355 << (CSM == CXXCopyAssignment);
4356 // FIXME: Explain why this special member can't be const.
4357 } else {
4358 Diag(MD->getLocation(),
4359 diag::err_defaulted_special_member_move_const_param)
4360 << (CSM == CXXMoveAssignment);
4361 }
4362 HadError = true;
4363 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004364 } else if (ExpectedParams) {
4365 // A copy assignment operator can take its argument by value, but a
4366 // defaulted one cannot.
4367 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004368 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004369 HadError = true;
4370 }
Sean Huntbe631222011-05-17 20:44:43 +00004371
Richard Smith61802452011-12-22 02:22:31 +00004372 // C++11 [dcl.fct.def.default]p2:
4373 // An explicitly-defaulted function may be declared constexpr only if it
4374 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004375 // Do not apply this rule to members of class templates, since core issue 1358
4376 // makes such functions always instantiate to constexpr functions. For
4377 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004378 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4379 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004380 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4381 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4382 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004383 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004384 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004385 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004386
Richard Smith61802452011-12-22 02:22:31 +00004387 // and may have an explicit exception-specification only if it is compatible
4388 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004389 if (Type->hasExceptionSpec()) {
4390 // Delay the check if this is the first declaration of the special member,
4391 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004392 if (First) {
4393 // If the exception specification needs to be instantiated, do so now,
4394 // before we clobber it with an EST_Unevaluated specification below.
4395 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4396 InstantiateExceptionSpec(MD->getLocStart(), MD);
4397 Type = MD->getType()->getAs<FunctionProtoType>();
4398 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004399 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004400 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004401 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4402 }
Richard Smith61802452011-12-22 02:22:31 +00004403
4404 // If a function is explicitly defaulted on its first declaration,
4405 if (First) {
4406 // -- it is implicitly considered to be constexpr if the implicit
4407 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004408 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004409
Richard Smith3003e1d2012-05-15 04:39:51 +00004410 // -- it is implicitly considered to have the same exception-specification
4411 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004412 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4413 EPI.ExceptionSpecType = EST_Unevaluated;
4414 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004415 MD->setType(Context.getFunctionType(ReturnType,
4416 ArrayRef<QualType>(&ArgType,
4417 ExpectedParams),
4418 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004419 }
4420
Richard Smith3003e1d2012-05-15 04:39:51 +00004421 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004422 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004423 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004424 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004425 // C++11 [dcl.fct.def.default]p4:
4426 // [For a] user-provided explicitly-defaulted function [...] if such a
4427 // function is implicitly defined as deleted, the program is ill-formed.
4428 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4429 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004430 }
4431 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004432
Richard Smith3003e1d2012-05-15 04:39:51 +00004433 if (HadError)
4434 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004435}
4436
Richard Smith1d28caf2012-12-11 01:14:52 +00004437/// Check whether the exception specification provided for an
4438/// explicitly-defaulted special member matches the exception specification
4439/// that would have been generated for an implicit special member, per
4440/// C++11 [dcl.fct.def.default]p2.
4441void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4442 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4443 // Compute the implicit exception specification.
4444 FunctionProtoType::ExtProtoInfo EPI;
4445 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4446 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Jordan Rosebea522f2013-03-08 21:51:21 +00004447 Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004448
4449 // Ensure that it matches.
4450 CheckEquivalentExceptionSpec(
4451 PDiag(diag::err_incorrect_defaulted_exception_spec)
4452 << getSpecialMember(MD), PDiag(),
4453 ImplicitType, SourceLocation(),
4454 SpecifiedType, MD->getLocation());
4455}
4456
4457void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4458 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4459 I != N; ++I)
4460 CheckExplicitlyDefaultedMemberExceptionSpec(
4461 DelayedDefaultedMemberExceptionSpecs[I].first,
4462 DelayedDefaultedMemberExceptionSpecs[I].second);
4463
4464 DelayedDefaultedMemberExceptionSpecs.clear();
4465}
4466
Richard Smith7d5088a2012-02-18 02:02:13 +00004467namespace {
4468struct SpecialMemberDeletionInfo {
4469 Sema &S;
4470 CXXMethodDecl *MD;
4471 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004472 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004473
4474 // Properties of the special member, computed for convenience.
4475 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4476 SourceLocation Loc;
4477
4478 bool AllFieldsAreConst;
4479
4480 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004481 Sema::CXXSpecialMember CSM, bool Diagnose)
4482 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004483 IsConstructor(false), IsAssignment(false), IsMove(false),
4484 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4485 AllFieldsAreConst(true) {
4486 switch (CSM) {
4487 case Sema::CXXDefaultConstructor:
4488 case Sema::CXXCopyConstructor:
4489 IsConstructor = true;
4490 break;
4491 case Sema::CXXMoveConstructor:
4492 IsConstructor = true;
4493 IsMove = true;
4494 break;
4495 case Sema::CXXCopyAssignment:
4496 IsAssignment = true;
4497 break;
4498 case Sema::CXXMoveAssignment:
4499 IsAssignment = true;
4500 IsMove = true;
4501 break;
4502 case Sema::CXXDestructor:
4503 break;
4504 case Sema::CXXInvalid:
4505 llvm_unreachable("invalid special member kind");
4506 }
4507
4508 if (MD->getNumParams()) {
4509 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4510 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4511 }
4512 }
4513
4514 bool inUnion() const { return MD->getParent()->isUnion(); }
4515
4516 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004517 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4518 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004519 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004520 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4521 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4522 Quals = 0;
4523 return S.LookupSpecialMember(Class, CSM,
4524 ConstArg || (Quals & Qualifiers::Const),
4525 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004526 MD->getRefQualifier() == RQ_RValue,
4527 TQ & Qualifiers::Const,
4528 TQ & Qualifiers::Volatile);
4529 }
4530
Richard Smith6c4c36c2012-03-30 20:53:28 +00004531 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004532
Richard Smith6c4c36c2012-03-30 20:53:28 +00004533 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004534 bool shouldDeleteForField(FieldDecl *FD);
4535 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004536
Richard Smith517bb842012-07-18 03:51:16 +00004537 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4538 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004539 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4540 Sema::SpecialMemberOverloadResult *SMOR,
4541 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004542
4543 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004544};
4545}
4546
John McCall12d8d802012-04-09 20:53:23 +00004547/// Is the given special member inaccessible when used on the given
4548/// sub-object.
4549bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4550 CXXMethodDecl *target) {
4551 /// If we're operating on a base class, the object type is the
4552 /// type of this special member.
4553 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004554 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004555 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4556 objectTy = S.Context.getTypeDeclType(MD->getParent());
4557 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4558
4559 // If we're operating on a field, the object type is the type of the field.
4560 } else {
4561 objectTy = S.Context.getTypeDeclType(target->getParent());
4562 }
4563
4564 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4565}
4566
Richard Smith6c4c36c2012-03-30 20:53:28 +00004567/// Check whether we should delete a special member due to the implicit
4568/// definition containing a call to a special member of a subobject.
4569bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4570 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4571 bool IsDtorCallInCtor) {
4572 CXXMethodDecl *Decl = SMOR->getMethod();
4573 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4574
4575 int DiagKind = -1;
4576
4577 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4578 DiagKind = !Decl ? 0 : 1;
4579 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4580 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004581 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004582 DiagKind = 3;
4583 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4584 !Decl->isTrivial()) {
4585 // A member of a union must have a trivial corresponding special member.
4586 // As a weird special case, a destructor call from a union's constructor
4587 // must be accessible and non-deleted, but need not be trivial. Such a
4588 // destructor is never actually called, but is semantically checked as
4589 // if it were.
4590 DiagKind = 4;
4591 }
4592
4593 if (DiagKind == -1)
4594 return false;
4595
4596 if (Diagnose) {
4597 if (Field) {
4598 S.Diag(Field->getLocation(),
4599 diag::note_deleted_special_member_class_subobject)
4600 << CSM << MD->getParent() << /*IsField*/true
4601 << Field << DiagKind << IsDtorCallInCtor;
4602 } else {
4603 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4604 S.Diag(Base->getLocStart(),
4605 diag::note_deleted_special_member_class_subobject)
4606 << CSM << MD->getParent() << /*IsField*/false
4607 << Base->getType() << DiagKind << IsDtorCallInCtor;
4608 }
4609
4610 if (DiagKind == 1)
4611 S.NoteDeletedFunction(Decl);
4612 // FIXME: Explain inaccessibility if DiagKind == 3.
4613 }
4614
4615 return true;
4616}
4617
Richard Smith9a561d52012-02-26 09:11:52 +00004618/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004619/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004620bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004621 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004622 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004623
4624 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004625 // -- any direct or virtual base class, or non-static data member with no
4626 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004627 // either M has no default constructor or overload resolution as applied
4628 // to M's default constructor results in an ambiguity or in a function
4629 // that is deleted or inaccessible
4630 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4631 // -- a direct or virtual base class B that cannot be copied/moved because
4632 // overload resolution, as applied to B's corresponding special member,
4633 // results in an ambiguity or a function that is deleted or inaccessible
4634 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004635 // C++11 [class.dtor]p5:
4636 // -- any direct or virtual base class [...] has a type with a destructor
4637 // that is deleted or inaccessible
4638 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004639 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004640 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004641 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004642
Richard Smith6c4c36c2012-03-30 20:53:28 +00004643 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4644 // -- any direct or virtual base class or non-static data member has a
4645 // type with a destructor that is deleted or inaccessible
4646 if (IsConstructor) {
4647 Sema::SpecialMemberOverloadResult *SMOR =
4648 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4649 false, false, false, false, false);
4650 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4651 return true;
4652 }
4653
Richard Smith9a561d52012-02-26 09:11:52 +00004654 return false;
4655}
4656
4657/// Check whether we should delete a special member function due to the class
4658/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004659bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004660 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004661 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004662}
4663
4664/// Check whether we should delete a special member function due to the class
4665/// having a particular non-static data member.
4666bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4667 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4668 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4669
4670 if (CSM == Sema::CXXDefaultConstructor) {
4671 // For a default constructor, all references must be initialized in-class
4672 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004673 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4674 if (Diagnose)
4675 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4676 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004677 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004678 }
Richard Smith79363f52012-02-27 06:07:25 +00004679 // C++11 [class.ctor]p5: any non-variant non-static data member of
4680 // const-qualified type (or array thereof) with no
4681 // brace-or-equal-initializer does not have a user-provided default
4682 // constructor.
4683 if (!inUnion() && FieldType.isConstQualified() &&
4684 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004685 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4686 if (Diagnose)
4687 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004688 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004689 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004690 }
4691
4692 if (inUnion() && !FieldType.isConstQualified())
4693 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004694 } else if (CSM == Sema::CXXCopyConstructor) {
4695 // For a copy constructor, data members must not be of rvalue reference
4696 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004697 if (FieldType->isRValueReferenceType()) {
4698 if (Diagnose)
4699 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4700 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004701 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004702 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004703 } else if (IsAssignment) {
4704 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004705 if (FieldType->isReferenceType()) {
4706 if (Diagnose)
4707 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4708 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004709 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004710 }
4711 if (!FieldRecord && FieldType.isConstQualified()) {
4712 // C++11 [class.copy]p23:
4713 // -- a non-static data member of const non-class type (or array thereof)
4714 if (Diagnose)
4715 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004716 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004717 return true;
4718 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004719 }
4720
4721 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004722 // Some additional restrictions exist on the variant members.
4723 if (!inUnion() && FieldRecord->isUnion() &&
4724 FieldRecord->isAnonymousStructOrUnion()) {
4725 bool AllVariantFieldsAreConst = true;
4726
Richard Smithdf8dc862012-03-29 19:00:10 +00004727 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004728 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4729 UE = FieldRecord->field_end();
4730 UI != UE; ++UI) {
4731 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004732
4733 if (!UnionFieldType.isConstQualified())
4734 AllVariantFieldsAreConst = false;
4735
Richard Smith9a561d52012-02-26 09:11:52 +00004736 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4737 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004738 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4739 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004740 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004741 }
4742
4743 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004744 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004745 FieldRecord->field_begin() != FieldRecord->field_end()) {
4746 if (Diagnose)
4747 S.Diag(FieldRecord->getLocation(),
4748 diag::note_deleted_default_ctor_all_const)
4749 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004750 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004751 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004752
Richard Smithdf8dc862012-03-29 19:00:10 +00004753 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004754 // This is technically non-conformant, but sanity demands it.
4755 return false;
4756 }
4757
Richard Smith517bb842012-07-18 03:51:16 +00004758 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4759 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004760 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004761 }
4762
4763 return false;
4764}
4765
4766/// C++11 [class.ctor] p5:
4767/// A defaulted default constructor for a class X is defined as deleted if
4768/// X is a union and all of its variant members are of const-qualified type.
4769bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004770 // This is a silly definition, because it gives an empty union a deleted
4771 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004772 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4773 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4774 if (Diagnose)
4775 S.Diag(MD->getParent()->getLocation(),
4776 diag::note_deleted_default_ctor_all_const)
4777 << MD->getParent() << /*not anonymous union*/0;
4778 return true;
4779 }
4780 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004781}
4782
4783/// Determine whether a defaulted special member function should be defined as
4784/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4785/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004786bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4787 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004788 if (MD->isInvalidDecl())
4789 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004790 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004791 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004792 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004793 return false;
4794
Richard Smith7d5088a2012-02-18 02:02:13 +00004795 // C++11 [expr.lambda.prim]p19:
4796 // The closure type associated with a lambda-expression has a
4797 // deleted (8.4.3) default constructor and a deleted copy
4798 // assignment operator.
4799 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004800 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4801 if (Diagnose)
4802 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004803 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004804 }
4805
Richard Smith5bdaac52012-04-02 20:59:25 +00004806 // For an anonymous struct or union, the copy and assignment special members
4807 // will never be used, so skip the check. For an anonymous union declared at
4808 // namespace scope, the constructor and destructor are used.
4809 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4810 RD->isAnonymousStructOrUnion())
4811 return false;
4812
Richard Smith6c4c36c2012-03-30 20:53:28 +00004813 // C++11 [class.copy]p7, p18:
4814 // If the class definition declares a move constructor or move assignment
4815 // operator, an implicitly declared copy constructor or copy assignment
4816 // operator is defined as deleted.
4817 if (MD->isImplicit() &&
4818 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4819 CXXMethodDecl *UserDeclaredMove = 0;
4820
4821 // In Microsoft mode, a user-declared move only causes the deletion of the
4822 // corresponding copy operation, not both copy operations.
4823 if (RD->hasUserDeclaredMoveConstructor() &&
4824 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4825 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004826
4827 // Find any user-declared move constructor.
4828 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4829 E = RD->ctor_end(); I != E; ++I) {
4830 if (I->isMoveConstructor()) {
4831 UserDeclaredMove = *I;
4832 break;
4833 }
4834 }
Richard Smith1c931be2012-04-02 18:40:40 +00004835 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004836 } else if (RD->hasUserDeclaredMoveAssignment() &&
4837 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4838 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004839
4840 // Find any user-declared move assignment operator.
4841 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4842 E = RD->method_end(); I != E; ++I) {
4843 if (I->isMoveAssignmentOperator()) {
4844 UserDeclaredMove = *I;
4845 break;
4846 }
4847 }
Richard Smith1c931be2012-04-02 18:40:40 +00004848 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004849 }
4850
4851 if (UserDeclaredMove) {
4852 Diag(UserDeclaredMove->getLocation(),
4853 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004854 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004855 << UserDeclaredMove->isMoveAssignmentOperator();
4856 return true;
4857 }
4858 }
Sean Hunte16da072011-10-10 06:18:57 +00004859
Richard Smith5bdaac52012-04-02 20:59:25 +00004860 // Do access control from the special member function
4861 ContextRAII MethodContext(*this, MD);
4862
Richard Smith9a561d52012-02-26 09:11:52 +00004863 // C++11 [class.dtor]p5:
4864 // -- for a virtual destructor, lookup of the non-array deallocation function
4865 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004866 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004867 FunctionDecl *OperatorDelete = 0;
4868 DeclarationName Name =
4869 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4870 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004871 OperatorDelete, false)) {
4872 if (Diagnose)
4873 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004874 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004875 }
Richard Smith9a561d52012-02-26 09:11:52 +00004876 }
4877
Richard Smith6c4c36c2012-03-30 20:53:28 +00004878 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004879
Sean Huntcdee3fe2011-05-11 22:34:38 +00004880 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004881 BE = RD->bases_end(); BI != BE; ++BI)
4882 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004883 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004884 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004885
4886 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004887 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004888 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004889 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004890
4891 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004892 FE = RD->field_end(); FI != FE; ++FI)
4893 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004894 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004895 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004896
Richard Smith7d5088a2012-02-18 02:02:13 +00004897 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004898 return true;
4899
4900 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004901}
4902
Richard Smithac713512012-12-08 02:53:02 +00004903/// Perform lookup for a special member of the specified kind, and determine
4904/// whether it is trivial. If the triviality can be determined without the
4905/// lookup, skip it. This is intended for use when determining whether a
4906/// special member of a containing object is trivial, and thus does not ever
4907/// perform overload resolution for default constructors.
4908///
4909/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4910/// member that was most likely to be intended to be trivial, if any.
4911static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4912 Sema::CXXSpecialMember CSM, unsigned Quals,
4913 CXXMethodDecl **Selected) {
4914 if (Selected)
4915 *Selected = 0;
4916
4917 switch (CSM) {
4918 case Sema::CXXInvalid:
4919 llvm_unreachable("not a special member");
4920
4921 case Sema::CXXDefaultConstructor:
4922 // C++11 [class.ctor]p5:
4923 // A default constructor is trivial if:
4924 // - all the [direct subobjects] have trivial default constructors
4925 //
4926 // Note, no overload resolution is performed in this case.
4927 if (RD->hasTrivialDefaultConstructor())
4928 return true;
4929
4930 if (Selected) {
4931 // If there's a default constructor which could have been trivial, dig it
4932 // out. Otherwise, if there's any user-provided default constructor, point
4933 // to that as an example of why there's not a trivial one.
4934 CXXConstructorDecl *DefCtor = 0;
4935 if (RD->needsImplicitDefaultConstructor())
4936 S.DeclareImplicitDefaultConstructor(RD);
4937 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4938 CE = RD->ctor_end(); CI != CE; ++CI) {
4939 if (!CI->isDefaultConstructor())
4940 continue;
4941 DefCtor = *CI;
4942 if (!DefCtor->isUserProvided())
4943 break;
4944 }
4945
4946 *Selected = DefCtor;
4947 }
4948
4949 return false;
4950
4951 case Sema::CXXDestructor:
4952 // C++11 [class.dtor]p5:
4953 // A destructor is trivial if:
4954 // - all the direct [subobjects] have trivial destructors
4955 if (RD->hasTrivialDestructor())
4956 return true;
4957
4958 if (Selected) {
4959 if (RD->needsImplicitDestructor())
4960 S.DeclareImplicitDestructor(RD);
4961 *Selected = RD->getDestructor();
4962 }
4963
4964 return false;
4965
4966 case Sema::CXXCopyConstructor:
4967 // C++11 [class.copy]p12:
4968 // A copy constructor is trivial if:
4969 // - the constructor selected to copy each direct [subobject] is trivial
4970 if (RD->hasTrivialCopyConstructor()) {
4971 if (Quals == Qualifiers::Const)
4972 // We must either select the trivial copy constructor or reach an
4973 // ambiguity; no need to actually perform overload resolution.
4974 return true;
4975 } else if (!Selected) {
4976 return false;
4977 }
4978 // In C++98, we are not supposed to perform overload resolution here, but we
4979 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4980 // cases like B as having a non-trivial copy constructor:
4981 // struct A { template<typename T> A(T&); };
4982 // struct B { mutable A a; };
4983 goto NeedOverloadResolution;
4984
4985 case Sema::CXXCopyAssignment:
4986 // C++11 [class.copy]p25:
4987 // A copy assignment operator is trivial if:
4988 // - the assignment operator selected to copy each direct [subobject] is
4989 // trivial
4990 if (RD->hasTrivialCopyAssignment()) {
4991 if (Quals == Qualifiers::Const)
4992 return true;
4993 } else if (!Selected) {
4994 return false;
4995 }
4996 // In C++98, we are not supposed to perform overload resolution here, but we
4997 // treat that as a language defect.
4998 goto NeedOverloadResolution;
4999
5000 case Sema::CXXMoveConstructor:
5001 case Sema::CXXMoveAssignment:
5002 NeedOverloadResolution:
5003 Sema::SpecialMemberOverloadResult *SMOR =
5004 S.LookupSpecialMember(RD, CSM,
5005 Quals & Qualifiers::Const,
5006 Quals & Qualifiers::Volatile,
5007 /*RValueThis*/false, /*ConstThis*/false,
5008 /*VolatileThis*/false);
5009
5010 // The standard doesn't describe how to behave if the lookup is ambiguous.
5011 // We treat it as not making the member non-trivial, just like the standard
5012 // mandates for the default constructor. This should rarely matter, because
5013 // the member will also be deleted.
5014 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5015 return true;
5016
5017 if (!SMOR->getMethod()) {
5018 assert(SMOR->getKind() ==
5019 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5020 return false;
5021 }
5022
5023 // We deliberately don't check if we found a deleted special member. We're
5024 // not supposed to!
5025 if (Selected)
5026 *Selected = SMOR->getMethod();
5027 return SMOR->getMethod()->isTrivial();
5028 }
5029
5030 llvm_unreachable("unknown special method kind");
5031}
5032
Benjamin Kramera574c892013-02-15 12:30:38 +00005033static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005034 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5035 CI != CE; ++CI)
5036 if (!CI->isImplicit())
5037 return *CI;
5038
5039 // Look for constructor templates.
5040 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5041 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5042 if (CXXConstructorDecl *CD =
5043 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5044 return CD;
5045 }
5046
5047 return 0;
5048}
5049
5050/// The kind of subobject we are checking for triviality. The values of this
5051/// enumeration are used in diagnostics.
5052enum TrivialSubobjectKind {
5053 /// The subobject is a base class.
5054 TSK_BaseClass,
5055 /// The subobject is a non-static data member.
5056 TSK_Field,
5057 /// The object is actually the complete object.
5058 TSK_CompleteObject
5059};
5060
5061/// Check whether the special member selected for a given type would be trivial.
5062static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5063 QualType SubType,
5064 Sema::CXXSpecialMember CSM,
5065 TrivialSubobjectKind Kind,
5066 bool Diagnose) {
5067 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5068 if (!SubRD)
5069 return true;
5070
5071 CXXMethodDecl *Selected;
5072 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5073 Diagnose ? &Selected : 0))
5074 return true;
5075
5076 if (Diagnose) {
5077 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5078 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5079 << Kind << SubType.getUnqualifiedType();
5080 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5081 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5082 } else if (!Selected)
5083 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5084 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5085 else if (Selected->isUserProvided()) {
5086 if (Kind == TSK_CompleteObject)
5087 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5088 << Kind << SubType.getUnqualifiedType() << CSM;
5089 else {
5090 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5091 << Kind << SubType.getUnqualifiedType() << CSM;
5092 S.Diag(Selected->getLocation(), diag::note_declared_at);
5093 }
5094 } else {
5095 if (Kind != TSK_CompleteObject)
5096 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5097 << Kind << SubType.getUnqualifiedType() << CSM;
5098
5099 // Explain why the defaulted or deleted special member isn't trivial.
5100 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5101 }
5102 }
5103
5104 return false;
5105}
5106
5107/// Check whether the members of a class type allow a special member to be
5108/// trivial.
5109static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5110 Sema::CXXSpecialMember CSM,
5111 bool ConstArg, bool Diagnose) {
5112 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5113 FE = RD->field_end(); FI != FE; ++FI) {
5114 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5115 continue;
5116
5117 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5118
5119 // Pretend anonymous struct or union members are members of this class.
5120 if (FI->isAnonymousStructOrUnion()) {
5121 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5122 CSM, ConstArg, Diagnose))
5123 return false;
5124 continue;
5125 }
5126
5127 // C++11 [class.ctor]p5:
5128 // A default constructor is trivial if [...]
5129 // -- no non-static data member of its class has a
5130 // brace-or-equal-initializer
5131 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5132 if (Diagnose)
5133 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5134 return false;
5135 }
5136
5137 // Objective C ARC 4.3.5:
5138 // [...] nontrivally ownership-qualified types are [...] not trivially
5139 // default constructible, copy constructible, move constructible, copy
5140 // assignable, move assignable, or destructible [...]
5141 if (S.getLangOpts().ObjCAutoRefCount &&
5142 FieldType.hasNonTrivialObjCLifetime()) {
5143 if (Diagnose)
5144 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5145 << RD << FieldType.getObjCLifetime();
5146 return false;
5147 }
5148
5149 if (ConstArg && !FI->isMutable())
5150 FieldType.addConst();
5151 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5152 TSK_Field, Diagnose))
5153 return false;
5154 }
5155
5156 return true;
5157}
5158
5159/// Diagnose why the specified class does not have a trivial special member of
5160/// the given kind.
5161void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5162 QualType Ty = Context.getRecordType(RD);
5163 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5164 Ty.addConst();
5165
5166 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5167 TSK_CompleteObject, /*Diagnose*/true);
5168}
5169
5170/// Determine whether a defaulted or deleted special member function is trivial,
5171/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5172/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5173bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5174 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005175 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5176
5177 CXXRecordDecl *RD = MD->getParent();
5178
5179 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005180
5181 // C++11 [class.copy]p12, p25:
5182 // A [special member] is trivial if its declared parameter type is the same
5183 // as if it had been implicitly declared [...]
5184 switch (CSM) {
5185 case CXXDefaultConstructor:
5186 case CXXDestructor:
5187 // Trivial default constructors and destructors cannot have parameters.
5188 break;
5189
5190 case CXXCopyConstructor:
5191 case CXXCopyAssignment: {
5192 // Trivial copy operations always have const, non-volatile parameter types.
5193 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005194 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005195 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5196 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5197 if (Diagnose)
5198 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5199 << Param0->getSourceRange() << Param0->getType()
5200 << Context.getLValueReferenceType(
5201 Context.getRecordType(RD).withConst());
5202 return false;
5203 }
5204 break;
5205 }
5206
5207 case CXXMoveConstructor:
5208 case CXXMoveAssignment: {
5209 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005210 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005211 const RValueReferenceType *RT =
5212 Param0->getType()->getAs<RValueReferenceType>();
5213 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5214 if (Diagnose)
5215 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5216 << Param0->getSourceRange() << Param0->getType()
5217 << Context.getRValueReferenceType(Context.getRecordType(RD));
5218 return false;
5219 }
5220 break;
5221 }
5222
5223 case CXXInvalid:
5224 llvm_unreachable("not a special member");
5225 }
5226
5227 // FIXME: We require that the parameter-declaration-clause is equivalent to
5228 // that of an implicit declaration, not just that the declared parameter type
5229 // matches, in order to prevent absuridities like a function simultaneously
5230 // being a trivial copy constructor and a non-trivial default constructor.
5231 // This issue has not yet been assigned a core issue number.
5232 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5233 if (Diagnose)
5234 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5235 diag::note_nontrivial_default_arg)
5236 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5237 return false;
5238 }
5239 if (MD->isVariadic()) {
5240 if (Diagnose)
5241 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5242 return false;
5243 }
5244
5245 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5246 // A copy/move [constructor or assignment operator] is trivial if
5247 // -- the [member] selected to copy/move each direct base class subobject
5248 // is trivial
5249 //
5250 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5251 // A [default constructor or destructor] is trivial if
5252 // -- all the direct base classes have trivial [default constructors or
5253 // destructors]
5254 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5255 BE = RD->bases_end(); BI != BE; ++BI)
5256 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5257 ConstArg ? BI->getType().withConst()
5258 : BI->getType(),
5259 CSM, TSK_BaseClass, Diagnose))
5260 return false;
5261
5262 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5263 // A copy/move [constructor or assignment operator] for a class X is
5264 // trivial if
5265 // -- for each non-static data member of X that is of class type (or array
5266 // thereof), the constructor selected to copy/move that member is
5267 // trivial
5268 //
5269 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5270 // A [default constructor or destructor] is trivial if
5271 // -- for all of the non-static data members of its class that are of class
5272 // type (or array thereof), each such class has a trivial [default
5273 // constructor or destructor]
5274 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5275 return false;
5276
5277 // C++11 [class.dtor]p5:
5278 // A destructor is trivial if [...]
5279 // -- the destructor is not virtual
5280 if (CSM == CXXDestructor && MD->isVirtual()) {
5281 if (Diagnose)
5282 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5283 return false;
5284 }
5285
5286 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5287 // A [special member] for class X is trivial if [...]
5288 // -- class X has no virtual functions and no virtual base classes
5289 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5290 if (!Diagnose)
5291 return false;
5292
5293 if (RD->getNumVBases()) {
5294 // Check for virtual bases. We already know that the corresponding
5295 // member in all bases is trivial, so vbases must all be direct.
5296 CXXBaseSpecifier &BS = *RD->vbases_begin();
5297 assert(BS.isVirtual());
5298 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5299 return false;
5300 }
5301
5302 // Must have a virtual method.
5303 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5304 ME = RD->method_end(); MI != ME; ++MI) {
5305 if (MI->isVirtual()) {
5306 SourceLocation MLoc = MI->getLocStart();
5307 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5308 return false;
5309 }
5310 }
5311
5312 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5313 }
5314
5315 // Looks like it's trivial!
5316 return true;
5317}
5318
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005319/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005320namespace {
5321 struct FindHiddenVirtualMethodData {
5322 Sema *S;
5323 CXXMethodDecl *Method;
5324 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005325 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005326 };
5327}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005328
David Blaikie5f750682012-10-19 00:53:08 +00005329/// \brief Check whether any most overriden method from MD in Methods
5330static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5331 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5332 if (MD->size_overridden_methods() == 0)
5333 return Methods.count(MD->getCanonicalDecl());
5334 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5335 E = MD->end_overridden_methods();
5336 I != E; ++I)
5337 if (CheckMostOverridenMethods(*I, Methods))
5338 return true;
5339 return false;
5340}
5341
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005342/// \brief Member lookup function that determines whether a given C++
5343/// method overloads virtual methods in a base class without overriding any,
5344/// to be used with CXXRecordDecl::lookupInBases().
5345static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5346 CXXBasePath &Path,
5347 void *UserData) {
5348 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5349
5350 FindHiddenVirtualMethodData &Data
5351 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5352
5353 DeclarationName Name = Data.Method->getDeclName();
5354 assert(Name.getNameKind() == DeclarationName::Identifier);
5355
5356 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005357 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005358 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005359 !Path.Decls.empty();
5360 Path.Decls = Path.Decls.slice(1)) {
5361 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005362 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005363 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005364 foundSameNameMethod = true;
5365 // Interested only in hidden virtual methods.
5366 if (!MD->isVirtual())
5367 continue;
5368 // If the method we are checking overrides a method from its base
5369 // don't warn about the other overloaded methods.
5370 if (!Data.S->IsOverload(Data.Method, MD, false))
5371 return true;
5372 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005373 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005374 overloadedMethods.push_back(MD);
5375 }
5376 }
5377
5378 if (foundSameNameMethod)
5379 Data.OverloadedMethods.append(overloadedMethods.begin(),
5380 overloadedMethods.end());
5381 return foundSameNameMethod;
5382}
5383
David Blaikie5f750682012-10-19 00:53:08 +00005384/// \brief Add the most overriden methods from MD to Methods
5385static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5386 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5387 if (MD->size_overridden_methods() == 0)
5388 Methods.insert(MD->getCanonicalDecl());
5389 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5390 E = MD->end_overridden_methods();
5391 I != E; ++I)
5392 AddMostOverridenMethods(*I, Methods);
5393}
5394
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005395/// \brief See if a method overloads virtual methods in a base class without
5396/// overriding any.
5397void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5398 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005399 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005400 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005401 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005402 return;
5403
5404 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5405 /*bool RecordPaths=*/false,
5406 /*bool DetectVirtual=*/false);
5407 FindHiddenVirtualMethodData Data;
5408 Data.Method = MD;
5409 Data.S = this;
5410
5411 // Keep the base methods that were overriden or introduced in the subclass
5412 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005413 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5414 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5415 NamedDecl *ND = *I;
5416 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005417 ND = shad->getTargetDecl();
5418 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5419 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005420 }
5421
5422 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5423 !Data.OverloadedMethods.empty()) {
5424 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5425 << MD << (Data.OverloadedMethods.size() > 1);
5426
5427 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5428 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005429 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005430 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005431 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5432 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005433 }
5434 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005435}
5436
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005437void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005438 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005439 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005440 SourceLocation RBrac,
5441 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005442 if (!TagDecl)
5443 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005444
Douglas Gregor42af25f2009-05-11 19:58:34 +00005445 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005446
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005447 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5448 if (l->getKind() != AttributeList::AT_Visibility)
5449 continue;
5450 l->setInvalid();
5451 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5452 l->getName();
5453 }
5454
David Blaikie77b6de02011-09-22 02:58:26 +00005455 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005456 // strict aliasing violation!
5457 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005458 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005459
Douglas Gregor23c94db2010-07-02 17:43:08 +00005460 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005461 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005462}
5463
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005464/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5465/// special functions, such as the default constructor, copy
5466/// constructor, or destructor, to the given C++ class (C++
5467/// [special]p1). This routine can only be executed just before the
5468/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005469void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005470 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005471 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005472
Richard Smithbc2a35d2012-12-08 08:32:28 +00005473 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005474 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005475
Richard Smithbc2a35d2012-12-08 08:32:28 +00005476 // If the properties or semantics of the copy constructor couldn't be
5477 // determined while the class was being declared, force a declaration
5478 // of it now.
5479 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5480 DeclareImplicitCopyConstructor(ClassDecl);
5481 }
5482
Richard Smith80ad52f2013-01-02 11:42:31 +00005483 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005484 ++ASTContext::NumImplicitMoveConstructors;
5485
Richard Smithbc2a35d2012-12-08 08:32:28 +00005486 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5487 DeclareImplicitMoveConstructor(ClassDecl);
5488 }
5489
Douglas Gregora376d102010-07-02 21:50:04 +00005490 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5491 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005492
5493 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005494 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005495 // it shows up in the right place in the vtable and that we diagnose
5496 // problems with the implicit exception specification.
5497 if (ClassDecl->isDynamicClass() ||
5498 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005499 DeclareImplicitCopyAssignment(ClassDecl);
5500 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005501
Richard Smith80ad52f2013-01-02 11:42:31 +00005502 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005503 ++ASTContext::NumImplicitMoveAssignmentOperators;
5504
5505 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005506 if (ClassDecl->isDynamicClass() ||
5507 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005508 DeclareImplicitMoveAssignment(ClassDecl);
5509 }
5510
Douglas Gregor4923aa22010-07-02 20:37:36 +00005511 if (!ClassDecl->hasUserDeclaredDestructor()) {
5512 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005513
5514 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005515 // have to declare the destructor immediately. This ensures that, e.g., it
5516 // shows up in the right place in the vtable and that we diagnose problems
5517 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005518 if (ClassDecl->isDynamicClass() ||
5519 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005520 DeclareImplicitDestructor(ClassDecl);
5521 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005522}
5523
Francois Pichet8387e2a2011-04-22 22:18:13 +00005524void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5525 if (!D)
5526 return;
5527
5528 int NumParamList = D->getNumTemplateParameterLists();
5529 for (int i = 0; i < NumParamList; i++) {
5530 TemplateParameterList* Params = D->getTemplateParameterList(i);
5531 for (TemplateParameterList::iterator Param = Params->begin(),
5532 ParamEnd = Params->end();
5533 Param != ParamEnd; ++Param) {
5534 NamedDecl *Named = cast<NamedDecl>(*Param);
5535 if (Named->getDeclName()) {
5536 S->AddDecl(Named);
5537 IdResolver.AddDecl(Named);
5538 }
5539 }
5540 }
5541}
5542
John McCalld226f652010-08-21 09:40:31 +00005543void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005544 if (!D)
5545 return;
5546
5547 TemplateParameterList *Params = 0;
5548 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5549 Params = Template->getTemplateParameters();
5550 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5551 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5552 Params = PartialSpec->getTemplateParameters();
5553 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005554 return;
5555
Douglas Gregor6569d682009-05-27 23:11:45 +00005556 for (TemplateParameterList::iterator Param = Params->begin(),
5557 ParamEnd = Params->end();
5558 Param != ParamEnd; ++Param) {
5559 NamedDecl *Named = cast<NamedDecl>(*Param);
5560 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005561 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005562 IdResolver.AddDecl(Named);
5563 }
5564 }
5565}
5566
John McCalld226f652010-08-21 09:40:31 +00005567void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005568 if (!RecordD) return;
5569 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005570 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005571 PushDeclContext(S, Record);
5572}
5573
John McCalld226f652010-08-21 09:40:31 +00005574void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005575 if (!RecordD) return;
5576 PopDeclContext();
5577}
5578
Douglas Gregor72b505b2008-12-16 21:30:33 +00005579/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5580/// parsing a top-level (non-nested) C++ class, and we are now
5581/// parsing those parts of the given Method declaration that could
5582/// not be parsed earlier (C++ [class.mem]p2), such as default
5583/// arguments. This action should enter the scope of the given
5584/// Method declaration as if we had just parsed the qualified method
5585/// name. However, it should not bring the parameters into scope;
5586/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005587void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005588}
5589
5590/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5591/// C++ method declaration. We're (re-)introducing the given
5592/// function parameter into scope for use in parsing later parts of
5593/// the method declaration. For example, we could see an
5594/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005595void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005596 if (!ParamD)
5597 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005598
John McCalld226f652010-08-21 09:40:31 +00005599 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005600
5601 // If this parameter has an unparsed default argument, clear it out
5602 // to make way for the parsed default argument.
5603 if (Param->hasUnparsedDefaultArg())
5604 Param->setDefaultArg(0);
5605
John McCalld226f652010-08-21 09:40:31 +00005606 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005607 if (Param->getDeclName())
5608 IdResolver.AddDecl(Param);
5609}
5610
5611/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5612/// processing the delayed method declaration for Method. The method
5613/// declaration is now considered finished. There may be a separate
5614/// ActOnStartOfFunctionDef action later (not necessarily
5615/// immediately!) for this method, if it was also defined inside the
5616/// class body.
John McCalld226f652010-08-21 09:40:31 +00005617void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005618 if (!MethodD)
5619 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005620
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005621 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005622
John McCalld226f652010-08-21 09:40:31 +00005623 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005624
5625 // Now that we have our default arguments, check the constructor
5626 // again. It could produce additional diagnostics or affect whether
5627 // the class has implicitly-declared destructors, among other
5628 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005629 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5630 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005631
5632 // Check the default arguments, which we may have added.
5633 if (!Method->isInvalidDecl())
5634 CheckCXXDefaultArguments(Method);
5635}
5636
Douglas Gregor42a552f2008-11-05 20:51:48 +00005637/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005638/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005639/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005640/// emit diagnostics and set the invalid bit to true. In any case, the type
5641/// will be updated to reflect a well-formed type for the constructor and
5642/// returned.
5643QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005644 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005645 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005646
5647 // C++ [class.ctor]p3:
5648 // A constructor shall not be virtual (10.3) or static (9.4). A
5649 // constructor can be invoked for a const, volatile or const
5650 // volatile object. A constructor shall not be declared const,
5651 // volatile, or const volatile (9.3.2).
5652 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005653 if (!D.isInvalidType())
5654 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5655 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5656 << SourceRange(D.getIdentifierLoc());
5657 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005658 }
John McCalld931b082010-08-26 03:08:43 +00005659 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005660 if (!D.isInvalidType())
5661 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5662 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5663 << SourceRange(D.getIdentifierLoc());
5664 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005665 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005666 }
Mike Stump1eb44332009-09-09 15:08:12 +00005667
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005668 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005669 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005670 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005671 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5672 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005673 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005674 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5675 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005676 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005677 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5678 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005679 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005680 }
Mike Stump1eb44332009-09-09 15:08:12 +00005681
Douglas Gregorc938c162011-01-26 05:01:58 +00005682 // C++0x [class.ctor]p4:
5683 // A constructor shall not be declared with a ref-qualifier.
5684 if (FTI.hasRefQualifier()) {
5685 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5686 << FTI.RefQualifierIsLValueRef
5687 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5688 D.setInvalidType();
5689 }
5690
Douglas Gregor42a552f2008-11-05 20:51:48 +00005691 // Rebuild the function type "R" without any type qualifiers (in
5692 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005693 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005694 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005695 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5696 return R;
5697
5698 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5699 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005700 EPI.RefQualifier = RQ_None;
5701
Richard Smith07b0fdc2013-03-18 21:12:30 +00005702 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005703}
5704
Douglas Gregor72b505b2008-12-16 21:30:33 +00005705/// CheckConstructor - Checks a fully-formed constructor for
5706/// well-formedness, issuing any diagnostics required. Returns true if
5707/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005708void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005709 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005710 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5711 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005712 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005713
5714 // C++ [class.copy]p3:
5715 // A declaration of a constructor for a class X is ill-formed if
5716 // its first parameter is of type (optionally cv-qualified) X and
5717 // either there are no other parameters or else all other
5718 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005719 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005720 ((Constructor->getNumParams() == 1) ||
5721 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005722 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5723 Constructor->getTemplateSpecializationKind()
5724 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005725 QualType ParamType = Constructor->getParamDecl(0)->getType();
5726 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5727 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005728 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005729 const char *ConstRef
5730 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5731 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005732 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005733 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005734
5735 // FIXME: Rather that making the constructor invalid, we should endeavor
5736 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005737 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005738 }
5739 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005740}
5741
John McCall15442822010-08-04 01:04:25 +00005742/// CheckDestructor - Checks a fully-formed destructor definition for
5743/// well-formedness, issuing any diagnostics required. Returns true
5744/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005745bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005746 CXXRecordDecl *RD = Destructor->getParent();
5747
5748 if (Destructor->isVirtual()) {
5749 SourceLocation Loc;
5750
5751 if (!Destructor->isImplicit())
5752 Loc = Destructor->getLocation();
5753 else
5754 Loc = RD->getLocation();
5755
5756 // If we have a virtual destructor, look up the deallocation function
5757 FunctionDecl *OperatorDelete = 0;
5758 DeclarationName Name =
5759 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005760 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005761 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005762
Eli Friedman5f2987c2012-02-02 03:46:19 +00005763 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005764
5765 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005766 }
Anders Carlsson37909802009-11-30 21:24:50 +00005767
5768 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005769}
5770
Mike Stump1eb44332009-09-09 15:08:12 +00005771static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005772FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5773 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5774 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005775 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005776}
5777
Douglas Gregor42a552f2008-11-05 20:51:48 +00005778/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5779/// the well-formednes of the destructor declarator @p D with type @p
5780/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005781/// emit diagnostics and set the declarator to invalid. Even if this happens,
5782/// will be updated to reflect a well-formed type for the destructor and
5783/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005784QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005785 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005786 // C++ [class.dtor]p1:
5787 // [...] A typedef-name that names a class is a class-name
5788 // (7.1.3); however, a typedef-name that names a class shall not
5789 // be used as the identifier in the declarator for a destructor
5790 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005791 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005792 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005793 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005794 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005795 else if (const TemplateSpecializationType *TST =
5796 DeclaratorType->getAs<TemplateSpecializationType>())
5797 if (TST->isTypeAlias())
5798 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5799 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005800
5801 // C++ [class.dtor]p2:
5802 // A destructor is used to destroy objects of its class type. A
5803 // destructor takes no parameters, and no return type can be
5804 // specified for it (not even void). The address of a destructor
5805 // shall not be taken. A destructor shall not be static. A
5806 // destructor can be invoked for a const, volatile or const
5807 // volatile object. A destructor shall not be declared const,
5808 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005809 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005810 if (!D.isInvalidType())
5811 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5812 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005813 << SourceRange(D.getIdentifierLoc())
5814 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5815
John McCalld931b082010-08-26 03:08:43 +00005816 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005817 }
Chris Lattner65401802009-04-25 08:28:21 +00005818 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005819 // Destructors don't have return types, but the parser will
5820 // happily parse something like:
5821 //
5822 // class X {
5823 // float ~X();
5824 // };
5825 //
5826 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005827 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5828 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5829 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005830 }
Mike Stump1eb44332009-09-09 15:08:12 +00005831
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005832 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005833 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005834 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005835 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5836 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005837 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005838 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5839 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005840 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005841 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5842 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005843 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005844 }
5845
Douglas Gregorc938c162011-01-26 05:01:58 +00005846 // C++0x [class.dtor]p2:
5847 // A destructor shall not be declared with a ref-qualifier.
5848 if (FTI.hasRefQualifier()) {
5849 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5850 << FTI.RefQualifierIsLValueRef
5851 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5852 D.setInvalidType();
5853 }
5854
Douglas Gregor42a552f2008-11-05 20:51:48 +00005855 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005856 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005857 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5858
5859 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005860 FTI.freeArgs();
5861 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005862 }
5863
Mike Stump1eb44332009-09-09 15:08:12 +00005864 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005865 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005866 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005867 D.setInvalidType();
5868 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005869
5870 // Rebuild the function type "R" without any type qualifiers or
5871 // parameters (in case any of the errors above fired) and with
5872 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005873 // types.
John McCalle23cf432010-12-14 08:05:40 +00005874 if (!D.isInvalidType())
5875 return R;
5876
Douglas Gregord92ec472010-07-01 05:10:53 +00005877 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005878 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5879 EPI.Variadic = false;
5880 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005881 EPI.RefQualifier = RQ_None;
Jordan Rosebea522f2013-03-08 21:51:21 +00005882 return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005883}
5884
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005885/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5886/// well-formednes of the conversion function declarator @p D with
5887/// type @p R. If there are any errors in the declarator, this routine
5888/// will emit diagnostics and return true. Otherwise, it will return
5889/// false. Either way, the type @p R will be updated to reflect a
5890/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005891void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005892 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005893 // C++ [class.conv.fct]p1:
5894 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005895 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005896 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005897 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005898 if (!D.isInvalidType())
5899 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5900 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5901 << SourceRange(D.getIdentifierLoc());
5902 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005903 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005904 }
John McCalla3f81372010-04-13 00:04:31 +00005905
5906 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5907
Chris Lattner6e475012009-04-25 08:35:12 +00005908 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005909 // Conversion functions don't have return types, but the parser will
5910 // happily parse something like:
5911 //
5912 // class X {
5913 // float operator bool();
5914 // };
5915 //
5916 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005917 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5918 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5919 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005920 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005921 }
5922
John McCalla3f81372010-04-13 00:04:31 +00005923 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5924
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005925 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005926 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005927 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5928
5929 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005930 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005931 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005932 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005933 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005934 D.setInvalidType();
5935 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005936
John McCalla3f81372010-04-13 00:04:31 +00005937 // Diagnose "&operator bool()" and other such nonsense. This
5938 // is actually a gcc extension which we don't support.
5939 if (Proto->getResultType() != ConvType) {
5940 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5941 << Proto->getResultType();
5942 D.setInvalidType();
5943 ConvType = Proto->getResultType();
5944 }
5945
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005946 // C++ [class.conv.fct]p4:
5947 // The conversion-type-id shall not represent a function type nor
5948 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005949 if (ConvType->isArrayType()) {
5950 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5951 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005952 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005953 } else if (ConvType->isFunctionType()) {
5954 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5955 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005956 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005957 }
5958
5959 // Rebuild the function type "R" without any parameters (in case any
5960 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005961 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005962 if (D.isInvalidType())
Jordan Rosebea522f2013-03-08 21:51:21 +00005963 R = Context.getFunctionType(ConvType, ArrayRef<QualType>(),
5964 Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005965
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005966 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005967 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005968 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005969 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005970 diag::warn_cxx98_compat_explicit_conversion_functions :
5971 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005972 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005973}
5974
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005975/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5976/// the declaration of the given C++ conversion function. This routine
5977/// is responsible for recording the conversion function in the C++
5978/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005979Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005980 assert(Conversion && "Expected to receive a conversion function declaration");
5981
Douglas Gregor9d350972008-12-12 08:25:50 +00005982 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005983
5984 // Make sure we aren't redeclaring the conversion function.
5985 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005986
5987 // C++ [class.conv.fct]p1:
5988 // [...] A conversion function is never used to convert a
5989 // (possibly cv-qualified) object to the (possibly cv-qualified)
5990 // same object type (or a reference to it), to a (possibly
5991 // cv-qualified) base class of that type (or a reference to it),
5992 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005993 // FIXME: Suppress this warning if the conversion function ends up being a
5994 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005995 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005996 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005997 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005998 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005999 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6000 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006001 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006002 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006003 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6004 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006005 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006006 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006007 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006008 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006009 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006010 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006011 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006012 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006013 }
6014
Douglas Gregore80622f2010-09-29 04:25:11 +00006015 if (FunctionTemplateDecl *ConversionTemplate
6016 = Conversion->getDescribedFunctionTemplate())
6017 return ConversionTemplate;
6018
John McCalld226f652010-08-21 09:40:31 +00006019 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006020}
6021
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006022//===----------------------------------------------------------------------===//
6023// Namespace Handling
6024//===----------------------------------------------------------------------===//
6025
Richard Smithd1a55a62012-10-04 22:13:39 +00006026/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6027/// reopened.
6028static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6029 SourceLocation Loc,
6030 IdentifierInfo *II, bool *IsInline,
6031 NamespaceDecl *PrevNS) {
6032 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006033
Richard Smithc969e6a2012-10-05 01:46:25 +00006034 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6035 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6036 // inline namespaces, with the intention of bringing names into namespace std.
6037 //
6038 // We support this just well enough to get that case working; this is not
6039 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006040 if (*IsInline && II && II->getName().startswith("__atomic") &&
6041 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006042 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006043 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6044 NS = NS->getPreviousDecl())
6045 NS->setInline(*IsInline);
6046 // Patch up the lookup table for the containing namespace. This isn't really
6047 // correct, but it's good enough for this particular case.
6048 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6049 E = PrevNS->decls_end(); I != E; ++I)
6050 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6051 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6052 return;
6053 }
6054
6055 if (PrevNS->isInline())
6056 // The user probably just forgot the 'inline', so suggest that it
6057 // be added back.
6058 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6059 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6060 else
6061 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6062 << IsInline;
6063
6064 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6065 *IsInline = PrevNS->isInline();
6066}
John McCallea318642010-08-26 09:15:37 +00006067
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006068/// ActOnStartNamespaceDef - This is called at the start of a namespace
6069/// definition.
John McCalld226f652010-08-21 09:40:31 +00006070Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006071 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006072 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006073 SourceLocation IdentLoc,
6074 IdentifierInfo *II,
6075 SourceLocation LBrace,
6076 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006077 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6078 // For anonymous namespace, take the location of the left brace.
6079 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006080 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006081 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006082 bool IsStd = false;
6083 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006084 Scope *DeclRegionScope = NamespcScope->getParent();
6085
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006086 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006087 if (II) {
6088 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006089 // The identifier in an original-namespace-definition shall not
6090 // have been previously defined in the declarative region in
6091 // which the original-namespace-definition appears. The
6092 // identifier in an original-namespace-definition is the name of
6093 // the namespace. Subsequently in that declarative region, it is
6094 // treated as an original-namespace-name.
6095 //
6096 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006097 // look through using directives, just look for any ordinary names.
6098
6099 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006100 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6101 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006102 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006103 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6104 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6105 ++I) {
6106 if ((*I)->getIdentifierNamespace() & IDNS) {
6107 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006108 break;
6109 }
6110 }
6111
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006112 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6113
6114 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006115 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006116 if (IsInline != PrevNS->isInline())
6117 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6118 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006119 } else if (PrevDecl) {
6120 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006121 Diag(Loc, diag::err_redefinition_different_kind)
6122 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006123 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006124 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006125 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006126 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006127 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006128 // This is the first "real" definition of the namespace "std", so update
6129 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006130 PrevNS = getStdNamespace();
6131 IsStd = true;
6132 AddToKnown = !IsInline;
6133 } else {
6134 // We've seen this namespace for the first time.
6135 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006136 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006137 } else {
John McCall9aeed322009-10-01 00:25:31 +00006138 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006139
6140 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006141 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006142 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006143 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006144 } else {
6145 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006146 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006147 }
6148
Richard Smithd1a55a62012-10-04 22:13:39 +00006149 if (PrevNS && IsInline != PrevNS->isInline())
6150 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6151 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006152 }
6153
6154 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6155 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006156 if (IsInvalid)
6157 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006158
6159 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006160
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006161 // FIXME: Should we be merging attributes?
6162 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006163 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006164
6165 if (IsStd)
6166 StdNamespace = Namespc;
6167 if (AddToKnown)
6168 KnownNamespaces[Namespc] = false;
6169
6170 if (II) {
6171 PushOnScopeChains(Namespc, DeclRegionScope);
6172 } else {
6173 // Link the anonymous namespace into its parent.
6174 DeclContext *Parent = CurContext->getRedeclContext();
6175 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6176 TU->setAnonymousNamespace(Namespc);
6177 } else {
6178 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006179 }
John McCall9aeed322009-10-01 00:25:31 +00006180
Douglas Gregora4181472010-03-24 00:46:35 +00006181 CurContext->addDecl(Namespc);
6182
John McCall9aeed322009-10-01 00:25:31 +00006183 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6184 // behaves as if it were replaced by
6185 // namespace unique { /* empty body */ }
6186 // using namespace unique;
6187 // namespace unique { namespace-body }
6188 // where all occurrences of 'unique' in a translation unit are
6189 // replaced by the same identifier and this identifier differs
6190 // from all other identifiers in the entire program.
6191
6192 // We just create the namespace with an empty name and then add an
6193 // implicit using declaration, just like the standard suggests.
6194 //
6195 // CodeGen enforces the "universally unique" aspect by giving all
6196 // declarations semantically contained within an anonymous
6197 // namespace internal linkage.
6198
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006199 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006200 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006201 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006202 /* 'using' */ LBrace,
6203 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006204 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006205 /* identifier */ SourceLocation(),
6206 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006207 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006208 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006209 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006210 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006211 }
6212
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006213 ActOnDocumentableDecl(Namespc);
6214
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006215 // Although we could have an invalid decl (i.e. the namespace name is a
6216 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006217 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6218 // for the namespace has the declarations that showed up in that particular
6219 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006220 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006221 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006222}
6223
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006224/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6225/// is a namespace alias, returns the namespace it points to.
6226static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6227 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6228 return AD->getNamespace();
6229 return dyn_cast_or_null<NamespaceDecl>(D);
6230}
6231
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006232/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6233/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006234void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006235 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6236 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006237 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006238 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006239 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006240 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006241}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006242
John McCall384aff82010-08-25 07:42:41 +00006243CXXRecordDecl *Sema::getStdBadAlloc() const {
6244 return cast_or_null<CXXRecordDecl>(
6245 StdBadAlloc.get(Context.getExternalSource()));
6246}
6247
6248NamespaceDecl *Sema::getStdNamespace() const {
6249 return cast_or_null<NamespaceDecl>(
6250 StdNamespace.get(Context.getExternalSource()));
6251}
6252
Douglas Gregor66992202010-06-29 17:53:46 +00006253/// \brief Retrieve the special "std" namespace, which may require us to
6254/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006255NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006256 if (!StdNamespace) {
6257 // The "std" namespace has not yet been defined, so build one implicitly.
6258 StdNamespace = NamespaceDecl::Create(Context,
6259 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006260 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006261 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006262 &PP.getIdentifierTable().get("std"),
6263 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006264 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006265 }
6266
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006267 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006268}
6269
Sebastian Redl395e04d2012-01-17 22:49:33 +00006270bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006271 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006272 "Looking for std::initializer_list outside of C++.");
6273
6274 // We're looking for implicit instantiations of
6275 // template <typename E> class std::initializer_list.
6276
6277 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6278 return false;
6279
Sebastian Redl84760e32012-01-17 22:49:58 +00006280 ClassTemplateDecl *Template = 0;
6281 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006282
Sebastian Redl84760e32012-01-17 22:49:58 +00006283 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006284
Sebastian Redl84760e32012-01-17 22:49:58 +00006285 ClassTemplateSpecializationDecl *Specialization =
6286 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6287 if (!Specialization)
6288 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006289
Sebastian Redl84760e32012-01-17 22:49:58 +00006290 Template = Specialization->getSpecializedTemplate();
6291 Arguments = Specialization->getTemplateArgs().data();
6292 } else if (const TemplateSpecializationType *TST =
6293 Ty->getAs<TemplateSpecializationType>()) {
6294 Template = dyn_cast_or_null<ClassTemplateDecl>(
6295 TST->getTemplateName().getAsTemplateDecl());
6296 Arguments = TST->getArgs();
6297 }
6298 if (!Template)
6299 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006300
6301 if (!StdInitializerList) {
6302 // Haven't recognized std::initializer_list yet, maybe this is it.
6303 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6304 if (TemplateClass->getIdentifier() !=
6305 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006306 !getStdNamespace()->InEnclosingNamespaceSetOf(
6307 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006308 return false;
6309 // This is a template called std::initializer_list, but is it the right
6310 // template?
6311 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006312 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006313 return false;
6314 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6315 return false;
6316
6317 // It's the right template.
6318 StdInitializerList = Template;
6319 }
6320
6321 if (Template != StdInitializerList)
6322 return false;
6323
6324 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006325 if (Element)
6326 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006327 return true;
6328}
6329
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006330static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6331 NamespaceDecl *Std = S.getStdNamespace();
6332 if (!Std) {
6333 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6334 return 0;
6335 }
6336
6337 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6338 Loc, Sema::LookupOrdinaryName);
6339 if (!S.LookupQualifiedName(Result, Std)) {
6340 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6341 return 0;
6342 }
6343 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6344 if (!Template) {
6345 Result.suppressDiagnostics();
6346 // We found something weird. Complain about the first thing we found.
6347 NamedDecl *Found = *Result.begin();
6348 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6349 return 0;
6350 }
6351
6352 // We found some template called std::initializer_list. Now verify that it's
6353 // correct.
6354 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006355 if (Params->getMinRequiredArguments() != 1 ||
6356 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006357 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6358 return 0;
6359 }
6360
6361 return Template;
6362}
6363
6364QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6365 if (!StdInitializerList) {
6366 StdInitializerList = LookupStdInitializerList(*this, Loc);
6367 if (!StdInitializerList)
6368 return QualType();
6369 }
6370
6371 TemplateArgumentListInfo Args(Loc, Loc);
6372 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6373 Context.getTrivialTypeSourceInfo(Element,
6374 Loc)));
6375 return Context.getCanonicalType(
6376 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6377}
6378
Sebastian Redl98d36062012-01-17 22:50:14 +00006379bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6380 // C++ [dcl.init.list]p2:
6381 // A constructor is an initializer-list constructor if its first parameter
6382 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6383 // std::initializer_list<E> for some type E, and either there are no other
6384 // parameters or else all other parameters have default arguments.
6385 if (Ctor->getNumParams() < 1 ||
6386 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6387 return false;
6388
6389 QualType ArgType = Ctor->getParamDecl(0)->getType();
6390 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6391 ArgType = RT->getPointeeType().getUnqualifiedType();
6392
6393 return isStdInitializerList(ArgType, 0);
6394}
6395
Douglas Gregor9172aa62011-03-26 22:25:30 +00006396/// \brief Determine whether a using statement is in a context where it will be
6397/// apply in all contexts.
6398static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6399 switch (CurContext->getDeclKind()) {
6400 case Decl::TranslationUnit:
6401 return true;
6402 case Decl::LinkageSpec:
6403 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6404 default:
6405 return false;
6406 }
6407}
6408
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006409namespace {
6410
6411// Callback to only accept typo corrections that are namespaces.
6412class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6413 public:
6414 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6415 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6416 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6417 }
6418 return false;
6419 }
6420};
6421
6422}
6423
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006424static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6425 CXXScopeSpec &SS,
6426 SourceLocation IdentLoc,
6427 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006428 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006429 R.clear();
6430 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006431 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006432 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006433 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6434 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006435 if (DeclContext *DC = S.computeDeclContext(SS, false))
6436 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6437 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006438 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6439 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006440 else
6441 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6442 << Ident << CorrectedQuotedStr
6443 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006444
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006445 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6446 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006447
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006448 R.addDecl(Corrected.getCorrectionDecl());
6449 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006450 }
6451 return false;
6452}
6453
John McCalld226f652010-08-21 09:40:31 +00006454Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006455 SourceLocation UsingLoc,
6456 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006457 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006458 SourceLocation IdentLoc,
6459 IdentifierInfo *NamespcName,
6460 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006461 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6462 assert(NamespcName && "Invalid NamespcName.");
6463 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006464
6465 // This can only happen along a recovery path.
6466 while (S->getFlags() & Scope::TemplateParamScope)
6467 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006468 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006469
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006470 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006471 NestedNameSpecifier *Qualifier = 0;
6472 if (SS.isSet())
6473 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6474
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006475 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006476 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6477 LookupParsedName(R, S, &SS);
6478 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006479 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006480
Douglas Gregor66992202010-06-29 17:53:46 +00006481 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006482 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006483 // Allow "using namespace std;" or "using namespace ::std;" even if
6484 // "std" hasn't been defined yet, for GCC compatibility.
6485 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6486 NamespcName->isStr("std")) {
6487 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006488 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006489 R.resolveKind();
6490 }
6491 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006492 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006493 }
6494
John McCallf36e02d2009-10-09 21:13:30 +00006495 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006496 NamedDecl *Named = R.getFoundDecl();
6497 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6498 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006499 // C++ [namespace.udir]p1:
6500 // A using-directive specifies that the names in the nominated
6501 // namespace can be used in the scope in which the
6502 // using-directive appears after the using-directive. During
6503 // unqualified name lookup (3.4.1), the names appear as if they
6504 // were declared in the nearest enclosing namespace which
6505 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006506 // namespace. [Note: in this context, "contains" means "contains
6507 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006508
6509 // Find enclosing context containing both using-directive and
6510 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006511 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006512 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6513 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6514 CommonAncestor = CommonAncestor->getParent();
6515
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006516 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006517 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006518 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006519
Douglas Gregor9172aa62011-03-26 22:25:30 +00006520 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006521 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006522 Diag(IdentLoc, diag::warn_using_directive_in_header);
6523 }
6524
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006525 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006526 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006527 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006528 }
6529
Richard Smith6b3d3e52013-02-20 19:22:51 +00006530 if (UDir)
6531 ProcessDeclAttributeList(S, UDir, AttrList);
6532
John McCalld226f652010-08-21 09:40:31 +00006533 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006534}
6535
6536void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006537 // If the scope has an associated entity and the using directive is at
6538 // namespace or translation unit scope, add the UsingDirectiveDecl into
6539 // its lookup structure so qualified name lookup can find it.
6540 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6541 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006542 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006543 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006544 // Otherwise, it is at block sope. The using-directives will affect lookup
6545 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006546 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006547}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006548
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006549
John McCalld226f652010-08-21 09:40:31 +00006550Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006551 AccessSpecifier AS,
6552 bool HasUsingKeyword,
6553 SourceLocation UsingLoc,
6554 CXXScopeSpec &SS,
6555 UnqualifiedId &Name,
6556 AttributeList *AttrList,
6557 bool IsTypeName,
6558 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006559 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006560
Douglas Gregor12c118a2009-11-04 16:30:06 +00006561 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006562 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006563 case UnqualifiedId::IK_Identifier:
6564 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006565 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006566 case UnqualifiedId::IK_ConversionFunctionId:
6567 break;
6568
6569 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006570 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006571 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006572 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006573 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006574 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006575 diag::err_using_decl_constructor)
6576 << SS.getRange();
6577
Richard Smith80ad52f2013-01-02 11:42:31 +00006578 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006579
John McCalld226f652010-08-21 09:40:31 +00006580 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006581
6582 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006583 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006584 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006585 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006586
6587 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006588 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006589 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006590 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006591 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006592
6593 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6594 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006595 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006596 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006597
Richard Smith07b0fdc2013-03-18 21:12:30 +00006598 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006599 // TODO: store that the declaration was written without 'using' and
6600 // talk about access decls instead of using decls in the
6601 // diagnostics.
6602 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006603 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006604
6605 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006606 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006607 }
6608
Douglas Gregor56c04582010-12-16 00:46:58 +00006609 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6610 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6611 return 0;
6612
John McCall9488ea12009-11-17 05:59:44 +00006613 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006614 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006615 /* IsInstantiation */ false,
6616 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006617 if (UD)
6618 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006619
John McCalld226f652010-08-21 09:40:31 +00006620 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006621}
6622
Douglas Gregor09acc982010-07-07 23:08:52 +00006623/// \brief Determine whether a using declaration considers the given
6624/// declarations as "equivalent", e.g., if they are redeclarations of
6625/// the same entity or are both typedefs of the same type.
6626static bool
6627IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6628 bool &SuppressRedeclaration) {
6629 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6630 SuppressRedeclaration = false;
6631 return true;
6632 }
6633
Richard Smith162e1c12011-04-15 14:24:37 +00006634 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6635 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006636 SuppressRedeclaration = true;
6637 return Context.hasSameType(TD1->getUnderlyingType(),
6638 TD2->getUnderlyingType());
6639 }
6640
6641 return false;
6642}
6643
6644
John McCall9f54ad42009-12-10 09:41:52 +00006645/// Determines whether to create a using shadow decl for a particular
6646/// decl, given the set of decls existing prior to this using lookup.
6647bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6648 const LookupResult &Previous) {
6649 // Diagnose finding a decl which is not from a base class of the
6650 // current class. We do this now because there are cases where this
6651 // function will silently decide not to build a shadow decl, which
6652 // will pre-empt further diagnostics.
6653 //
6654 // We don't need to do this in C++0x because we do the check once on
6655 // the qualifier.
6656 //
6657 // FIXME: diagnose the following if we care enough:
6658 // struct A { int foo; };
6659 // struct B : A { using A::foo; };
6660 // template <class T> struct C : A {};
6661 // template <class T> struct D : C<T> { using B::foo; } // <---
6662 // This is invalid (during instantiation) in C++03 because B::foo
6663 // resolves to the using decl in B, which is not a base class of D<T>.
6664 // We can't diagnose it immediately because C<T> is an unknown
6665 // specialization. The UsingShadowDecl in D<T> then points directly
6666 // to A::foo, which will look well-formed when we instantiate.
6667 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006668 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006669 DeclContext *OrigDC = Orig->getDeclContext();
6670
6671 // Handle enums and anonymous structs.
6672 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6673 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6674 while (OrigRec->isAnonymousStructOrUnion())
6675 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6676
6677 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6678 if (OrigDC == CurContext) {
6679 Diag(Using->getLocation(),
6680 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006681 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006682 Diag(Orig->getLocation(), diag::note_using_decl_target);
6683 return true;
6684 }
6685
Douglas Gregordc355712011-02-25 00:36:19 +00006686 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006687 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006688 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006689 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006690 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006691 Diag(Orig->getLocation(), diag::note_using_decl_target);
6692 return true;
6693 }
6694 }
6695
6696 if (Previous.empty()) return false;
6697
6698 NamedDecl *Target = Orig;
6699 if (isa<UsingShadowDecl>(Target))
6700 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6701
John McCalld7533ec2009-12-11 02:33:26 +00006702 // If the target happens to be one of the previous declarations, we
6703 // don't have a conflict.
6704 //
6705 // FIXME: but we might be increasing its access, in which case we
6706 // should redeclare it.
6707 NamedDecl *NonTag = 0, *Tag = 0;
6708 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6709 I != E; ++I) {
6710 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006711 bool Result;
6712 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6713 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006714
6715 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6716 }
6717
John McCall9f54ad42009-12-10 09:41:52 +00006718 if (Target->isFunctionOrFunctionTemplate()) {
6719 FunctionDecl *FD;
6720 if (isa<FunctionTemplateDecl>(Target))
6721 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6722 else
6723 FD = cast<FunctionDecl>(Target);
6724
6725 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006726 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006727 case Ovl_Overload:
6728 return false;
6729
6730 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006731 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006732 break;
6733
6734 // We found a decl with the exact signature.
6735 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006736 // If we're in a record, we want to hide the target, so we
6737 // return true (without a diagnostic) to tell the caller not to
6738 // build a shadow decl.
6739 if (CurContext->isRecord())
6740 return true;
6741
6742 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006743 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006744 break;
6745 }
6746
6747 Diag(Target->getLocation(), diag::note_using_decl_target);
6748 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6749 return true;
6750 }
6751
6752 // Target is not a function.
6753
John McCall9f54ad42009-12-10 09:41:52 +00006754 if (isa<TagDecl>(Target)) {
6755 // No conflict between a tag and a non-tag.
6756 if (!Tag) return false;
6757
John McCall41ce66f2009-12-10 19:51:03 +00006758 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006759 Diag(Target->getLocation(), diag::note_using_decl_target);
6760 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6761 return true;
6762 }
6763
6764 // No conflict between a tag and a non-tag.
6765 if (!NonTag) return false;
6766
John McCall41ce66f2009-12-10 19:51:03 +00006767 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006768 Diag(Target->getLocation(), diag::note_using_decl_target);
6769 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6770 return true;
6771}
6772
John McCall9488ea12009-11-17 05:59:44 +00006773/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006774UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006775 UsingDecl *UD,
6776 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006777
6778 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006779 NamedDecl *Target = Orig;
6780 if (isa<UsingShadowDecl>(Target)) {
6781 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6782 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006783 }
6784
6785 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006786 = UsingShadowDecl::Create(Context, CurContext,
6787 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006788 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006789
6790 Shadow->setAccess(UD->getAccess());
6791 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6792 Shadow->setInvalidDecl();
6793
John McCall9488ea12009-11-17 05:59:44 +00006794 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006795 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006796 else
John McCall604e7f12009-12-08 07:46:18 +00006797 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006798
John McCall604e7f12009-12-08 07:46:18 +00006799
John McCall9f54ad42009-12-10 09:41:52 +00006800 return Shadow;
6801}
John McCall604e7f12009-12-08 07:46:18 +00006802
John McCall9f54ad42009-12-10 09:41:52 +00006803/// Hides a using shadow declaration. This is required by the current
6804/// using-decl implementation when a resolvable using declaration in a
6805/// class is followed by a declaration which would hide or override
6806/// one or more of the using decl's targets; for example:
6807///
6808/// struct Base { void foo(int); };
6809/// struct Derived : Base {
6810/// using Base::foo;
6811/// void foo(int);
6812/// };
6813///
6814/// The governing language is C++03 [namespace.udecl]p12:
6815///
6816/// When a using-declaration brings names from a base class into a
6817/// derived class scope, member functions in the derived class
6818/// override and/or hide member functions with the same name and
6819/// parameter types in a base class (rather than conflicting).
6820///
6821/// There are two ways to implement this:
6822/// (1) optimistically create shadow decls when they're not hidden
6823/// by existing declarations, or
6824/// (2) don't create any shadow decls (or at least don't make them
6825/// visible) until we've fully parsed/instantiated the class.
6826/// The problem with (1) is that we might have to retroactively remove
6827/// a shadow decl, which requires several O(n) operations because the
6828/// decl structures are (very reasonably) not designed for removal.
6829/// (2) avoids this but is very fiddly and phase-dependent.
6830void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006831 if (Shadow->getDeclName().getNameKind() ==
6832 DeclarationName::CXXConversionFunctionName)
6833 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6834
John McCall9f54ad42009-12-10 09:41:52 +00006835 // Remove it from the DeclContext...
6836 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006837
John McCall9f54ad42009-12-10 09:41:52 +00006838 // ...and the scope, if applicable...
6839 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006840 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006841 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006842 }
6843
John McCall9f54ad42009-12-10 09:41:52 +00006844 // ...and the using decl.
6845 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6846
6847 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006848 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006849}
6850
John McCall7ba107a2009-11-18 02:36:19 +00006851/// Builds a using declaration.
6852///
6853/// \param IsInstantiation - Whether this call arises from an
6854/// instantiation of an unresolved using declaration. We treat
6855/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006856NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6857 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006858 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006859 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006860 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006861 bool IsInstantiation,
6862 bool IsTypeName,
6863 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006864 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006865 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006866 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006867
Anders Carlsson550b14b2009-08-28 05:49:21 +00006868 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006869
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006870 if (SS.isEmpty()) {
6871 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006872 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006873 }
Mike Stump1eb44332009-09-09 15:08:12 +00006874
John McCall9f54ad42009-12-10 09:41:52 +00006875 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006876 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006877 ForRedeclaration);
6878 Previous.setHideTags(false);
6879 if (S) {
6880 LookupName(Previous, S);
6881
6882 // It is really dumb that we have to do this.
6883 LookupResult::Filter F = Previous.makeFilter();
6884 while (F.hasNext()) {
6885 NamedDecl *D = F.next();
6886 if (!isDeclInScope(D, CurContext, S))
6887 F.erase();
6888 }
6889 F.done();
6890 } else {
6891 assert(IsInstantiation && "no scope in non-instantiation");
6892 assert(CurContext->isRecord() && "scope not record in instantiation");
6893 LookupQualifiedName(Previous, CurContext);
6894 }
6895
John McCall9f54ad42009-12-10 09:41:52 +00006896 // Check for invalid redeclarations.
6897 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6898 return 0;
6899
6900 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006901 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6902 return 0;
6903
John McCallaf8e6ed2009-11-12 03:15:40 +00006904 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006905 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006906 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006907 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006908 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006909 // FIXME: not all declaration name kinds are legal here
6910 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6911 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006912 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006913 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006914 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006915 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6916 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006917 }
John McCalled976492009-12-04 22:46:56 +00006918 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006919 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6920 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006921 }
John McCalled976492009-12-04 22:46:56 +00006922 D->setAccess(AS);
6923 CurContext->addDecl(D);
6924
6925 if (!LookupContext) return D;
6926 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006927
John McCall77bb1aa2010-05-01 00:40:08 +00006928 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006929 UD->setInvalidDecl();
6930 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006931 }
6932
Richard Smithc5a89a12012-04-02 01:30:27 +00006933 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006934 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006935 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006936 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006937 return UD;
6938 }
6939
6940 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006941
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006942 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006943
John McCall604e7f12009-12-08 07:46:18 +00006944 // Unlike most lookups, we don't always want to hide tag
6945 // declarations: tag names are visible through the using declaration
6946 // even if hidden by ordinary names, *except* in a dependent context
6947 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006948 if (!IsInstantiation)
6949 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006950
John McCallb9abd8722012-04-07 03:04:20 +00006951 // For the purposes of this lookup, we have a base object type
6952 // equal to that of the current context.
6953 if (CurContext->isRecord()) {
6954 R.setBaseObjectType(
6955 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6956 }
6957
John McCalla24dc2e2009-11-17 02:14:36 +00006958 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006959
John McCallf36e02d2009-10-09 21:13:30 +00006960 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006961 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006962 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006963 UD->setInvalidDecl();
6964 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006965 }
6966
John McCalled976492009-12-04 22:46:56 +00006967 if (R.isAmbiguous()) {
6968 UD->setInvalidDecl();
6969 return UD;
6970 }
Mike Stump1eb44332009-09-09 15:08:12 +00006971
John McCall7ba107a2009-11-18 02:36:19 +00006972 if (IsTypeName) {
6973 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006974 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006975 Diag(IdentLoc, diag::err_using_typename_non_type);
6976 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6977 Diag((*I)->getUnderlyingDecl()->getLocation(),
6978 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006979 UD->setInvalidDecl();
6980 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006981 }
6982 } else {
6983 // If we asked for a non-typename and we got a type, error out,
6984 // but only if this is an instantiation of an unresolved using
6985 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006986 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006987 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6988 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006989 UD->setInvalidDecl();
6990 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006991 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006992 }
6993
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006994 // C++0x N2914 [namespace.udecl]p6:
6995 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006996 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006997 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6998 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006999 UD->setInvalidDecl();
7000 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007001 }
Mike Stump1eb44332009-09-09 15:08:12 +00007002
John McCall9f54ad42009-12-10 09:41:52 +00007003 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7004 if (!CheckUsingShadowDecl(UD, *I, Previous))
7005 BuildUsingShadowDecl(S, UD, *I);
7006 }
John McCall9488ea12009-11-17 05:59:44 +00007007
7008 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007009}
7010
Sebastian Redlf677ea32011-02-05 19:23:19 +00007011/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007012bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7013 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007014
Douglas Gregordc355712011-02-25 00:36:19 +00007015 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007016 assert(SourceType &&
7017 "Using decl naming constructor doesn't have type in scope spec.");
7018 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7019
7020 // Check whether the named type is a direct base class.
7021 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7022 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7023 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7024 BaseIt != BaseE; ++BaseIt) {
7025 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7026 if (CanonicalSourceType == BaseType)
7027 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007028 if (BaseIt->getType()->isDependentType())
7029 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007030 }
7031
7032 if (BaseIt == BaseE) {
7033 // Did not find SourceType in the bases.
7034 Diag(UD->getUsingLocation(),
7035 diag::err_using_decl_constructor_not_in_direct_base)
7036 << UD->getNameInfo().getSourceRange()
7037 << QualType(SourceType, 0) << TargetClass;
7038 return true;
7039 }
7040
Richard Smithc5a89a12012-04-02 01:30:27 +00007041 if (!CurContext->isDependentContext())
7042 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007043
7044 return false;
7045}
7046
John McCall9f54ad42009-12-10 09:41:52 +00007047/// Checks that the given using declaration is not an invalid
7048/// redeclaration. Note that this is checking only for the using decl
7049/// itself, not for any ill-formedness among the UsingShadowDecls.
7050bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7051 bool isTypeName,
7052 const CXXScopeSpec &SS,
7053 SourceLocation NameLoc,
7054 const LookupResult &Prev) {
7055 // C++03 [namespace.udecl]p8:
7056 // C++0x [namespace.udecl]p10:
7057 // A using-declaration is a declaration and can therefore be used
7058 // repeatedly where (and only where) multiple declarations are
7059 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007060 //
John McCall8a726212010-11-29 18:01:58 +00007061 // That's in non-member contexts.
7062 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007063 return false;
7064
7065 NestedNameSpecifier *Qual
7066 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7067
7068 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7069 NamedDecl *D = *I;
7070
7071 bool DTypename;
7072 NestedNameSpecifier *DQual;
7073 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7074 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007075 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007076 } else if (UnresolvedUsingValueDecl *UD
7077 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7078 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007079 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007080 } else if (UnresolvedUsingTypenameDecl *UD
7081 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7082 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007083 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007084 } else continue;
7085
7086 // using decls differ if one says 'typename' and the other doesn't.
7087 // FIXME: non-dependent using decls?
7088 if (isTypeName != DTypename) continue;
7089
7090 // using decls differ if they name different scopes (but note that
7091 // template instantiation can cause this check to trigger when it
7092 // didn't before instantiation).
7093 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7094 Context.getCanonicalNestedNameSpecifier(DQual))
7095 continue;
7096
7097 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007098 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007099 return true;
7100 }
7101
7102 return false;
7103}
7104
John McCall604e7f12009-12-08 07:46:18 +00007105
John McCalled976492009-12-04 22:46:56 +00007106/// Checks that the given nested-name qualifier used in a using decl
7107/// in the current context is appropriately related to the current
7108/// scope. If an error is found, diagnoses it and returns true.
7109bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7110 const CXXScopeSpec &SS,
7111 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007112 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007113
John McCall604e7f12009-12-08 07:46:18 +00007114 if (!CurContext->isRecord()) {
7115 // C++03 [namespace.udecl]p3:
7116 // C++0x [namespace.udecl]p8:
7117 // A using-declaration for a class member shall be a member-declaration.
7118
7119 // If we weren't able to compute a valid scope, it must be a
7120 // dependent class scope.
7121 if (!NamedContext || NamedContext->isRecord()) {
7122 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7123 << SS.getRange();
7124 return true;
7125 }
7126
7127 // Otherwise, everything is known to be fine.
7128 return false;
7129 }
7130
7131 // The current scope is a record.
7132
7133 // If the named context is dependent, we can't decide much.
7134 if (!NamedContext) {
7135 // FIXME: in C++0x, we can diagnose if we can prove that the
7136 // nested-name-specifier does not refer to a base class, which is
7137 // still possible in some cases.
7138
7139 // Otherwise we have to conservatively report that things might be
7140 // okay.
7141 return false;
7142 }
7143
7144 if (!NamedContext->isRecord()) {
7145 // Ideally this would point at the last name in the specifier,
7146 // but we don't have that level of source info.
7147 Diag(SS.getRange().getBegin(),
7148 diag::err_using_decl_nested_name_specifier_is_not_class)
7149 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7150 return true;
7151 }
7152
Douglas Gregor6fb07292010-12-21 07:41:49 +00007153 if (!NamedContext->isDependentContext() &&
7154 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7155 return true;
7156
Richard Smith80ad52f2013-01-02 11:42:31 +00007157 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007158 // C++0x [namespace.udecl]p3:
7159 // In a using-declaration used as a member-declaration, the
7160 // nested-name-specifier shall name a base class of the class
7161 // being defined.
7162
7163 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7164 cast<CXXRecordDecl>(NamedContext))) {
7165 if (CurContext == NamedContext) {
7166 Diag(NameLoc,
7167 diag::err_using_decl_nested_name_specifier_is_current_class)
7168 << SS.getRange();
7169 return true;
7170 }
7171
7172 Diag(SS.getRange().getBegin(),
7173 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7174 << (NestedNameSpecifier*) SS.getScopeRep()
7175 << cast<CXXRecordDecl>(CurContext)
7176 << SS.getRange();
7177 return true;
7178 }
7179
7180 return false;
7181 }
7182
7183 // C++03 [namespace.udecl]p4:
7184 // A using-declaration used as a member-declaration shall refer
7185 // to a member of a base class of the class being defined [etc.].
7186
7187 // Salient point: SS doesn't have to name a base class as long as
7188 // lookup only finds members from base classes. Therefore we can
7189 // diagnose here only if we can prove that that can't happen,
7190 // i.e. if the class hierarchies provably don't intersect.
7191
7192 // TODO: it would be nice if "definitely valid" results were cached
7193 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7194 // need to be repeated.
7195
7196 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007197 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007198
7199 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7200 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7201 Data->Bases.insert(Base);
7202 return true;
7203 }
7204
7205 bool hasDependentBases(const CXXRecordDecl *Class) {
7206 return !Class->forallBases(collect, this);
7207 }
7208
7209 /// Returns true if the base is dependent or is one of the
7210 /// accumulated base classes.
7211 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7212 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7213 return !Data->Bases.count(Base);
7214 }
7215
7216 bool mightShareBases(const CXXRecordDecl *Class) {
7217 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7218 }
7219 };
7220
7221 UserData Data;
7222
7223 // Returns false if we find a dependent base.
7224 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7225 return false;
7226
7227 // Returns false if the class has a dependent base or if it or one
7228 // of its bases is present in the base set of the current context.
7229 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7230 return false;
7231
7232 Diag(SS.getRange().getBegin(),
7233 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7234 << (NestedNameSpecifier*) SS.getScopeRep()
7235 << cast<CXXRecordDecl>(CurContext)
7236 << SS.getRange();
7237
7238 return true;
John McCalled976492009-12-04 22:46:56 +00007239}
7240
Richard Smith162e1c12011-04-15 14:24:37 +00007241Decl *Sema::ActOnAliasDeclaration(Scope *S,
7242 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007243 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007244 SourceLocation UsingLoc,
7245 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007246 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007247 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007248 // Skip up to the relevant declaration scope.
7249 while (S->getFlags() & Scope::TemplateParamScope)
7250 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007251 assert((S->getFlags() & Scope::DeclScope) &&
7252 "got alias-declaration outside of declaration scope");
7253
7254 if (Type.isInvalid())
7255 return 0;
7256
7257 bool Invalid = false;
7258 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7259 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007260 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007261
7262 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7263 return 0;
7264
7265 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007266 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007267 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007268 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7269 TInfo->getTypeLoc().getBeginLoc());
7270 }
Richard Smith162e1c12011-04-15 14:24:37 +00007271
7272 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7273 LookupName(Previous, S);
7274
7275 // Warn about shadowing the name of a template parameter.
7276 if (Previous.isSingleResult() &&
7277 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007278 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007279 Previous.clear();
7280 }
7281
7282 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7283 "name in alias declaration must be an identifier");
7284 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7285 Name.StartLocation,
7286 Name.Identifier, TInfo);
7287
7288 NewTD->setAccess(AS);
7289
7290 if (Invalid)
7291 NewTD->setInvalidDecl();
7292
Richard Smith6b3d3e52013-02-20 19:22:51 +00007293 ProcessDeclAttributeList(S, NewTD, AttrList);
7294
Richard Smith3e4c6c42011-05-05 21:57:07 +00007295 CheckTypedefForVariablyModifiedType(S, NewTD);
7296 Invalid |= NewTD->isInvalidDecl();
7297
Richard Smith162e1c12011-04-15 14:24:37 +00007298 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007299
7300 NamedDecl *NewND;
7301 if (TemplateParamLists.size()) {
7302 TypeAliasTemplateDecl *OldDecl = 0;
7303 TemplateParameterList *OldTemplateParams = 0;
7304
7305 if (TemplateParamLists.size() != 1) {
7306 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007307 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7308 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007309 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007310 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007311
7312 // Only consider previous declarations in the same scope.
7313 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7314 /*ExplicitInstantiationOrSpecialization*/false);
7315 if (!Previous.empty()) {
7316 Redeclaration = true;
7317
7318 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7319 if (!OldDecl && !Invalid) {
7320 Diag(UsingLoc, diag::err_redefinition_different_kind)
7321 << Name.Identifier;
7322
7323 NamedDecl *OldD = Previous.getRepresentativeDecl();
7324 if (OldD->getLocation().isValid())
7325 Diag(OldD->getLocation(), diag::note_previous_definition);
7326
7327 Invalid = true;
7328 }
7329
7330 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7331 if (TemplateParameterListsAreEqual(TemplateParams,
7332 OldDecl->getTemplateParameters(),
7333 /*Complain=*/true,
7334 TPL_TemplateMatch))
7335 OldTemplateParams = OldDecl->getTemplateParameters();
7336 else
7337 Invalid = true;
7338
7339 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7340 if (!Invalid &&
7341 !Context.hasSameType(OldTD->getUnderlyingType(),
7342 NewTD->getUnderlyingType())) {
7343 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7344 // but we can't reasonably accept it.
7345 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7346 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7347 if (OldTD->getLocation().isValid())
7348 Diag(OldTD->getLocation(), diag::note_previous_definition);
7349 Invalid = true;
7350 }
7351 }
7352 }
7353
7354 // Merge any previous default template arguments into our parameters,
7355 // and check the parameter list.
7356 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7357 TPC_TypeAliasTemplate))
7358 return 0;
7359
7360 TypeAliasTemplateDecl *NewDecl =
7361 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7362 Name.Identifier, TemplateParams,
7363 NewTD);
7364
7365 NewDecl->setAccess(AS);
7366
7367 if (Invalid)
7368 NewDecl->setInvalidDecl();
7369 else if (OldDecl)
7370 NewDecl->setPreviousDeclaration(OldDecl);
7371
7372 NewND = NewDecl;
7373 } else {
7374 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7375 NewND = NewTD;
7376 }
Richard Smith162e1c12011-04-15 14:24:37 +00007377
7378 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007379 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007380
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007381 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007382 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007383}
7384
John McCalld226f652010-08-21 09:40:31 +00007385Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007386 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007387 SourceLocation AliasLoc,
7388 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007389 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007390 SourceLocation IdentLoc,
7391 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007392
Anders Carlsson81c85c42009-03-28 23:53:49 +00007393 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007394 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7395 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007396
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007397 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007398 NamedDecl *PrevDecl
7399 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7400 ForRedeclaration);
7401 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7402 PrevDecl = 0;
7403
7404 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007405 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007406 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007407 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007408 // FIXME: At some point, we'll want to create the (redundant)
7409 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007410 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007411 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007412 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007413 }
Mike Stump1eb44332009-09-09 15:08:12 +00007414
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007415 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7416 diag::err_redefinition_different_kind;
7417 Diag(AliasLoc, DiagID) << Alias;
7418 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007419 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007420 }
7421
John McCalla24dc2e2009-11-17 02:14:36 +00007422 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007423 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007424
John McCallf36e02d2009-10-09 21:13:30 +00007425 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007426 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007427 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007428 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007429 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007430 }
Mike Stump1eb44332009-09-09 15:08:12 +00007431
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007432 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007433 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007434 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007435 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007436
John McCall3dbd3d52010-02-16 06:53:13 +00007437 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007438 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007439}
7440
Sean Hunt001cad92011-05-10 00:49:42 +00007441Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007442Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7443 CXXMethodDecl *MD) {
7444 CXXRecordDecl *ClassDecl = MD->getParent();
7445
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007446 // C++ [except.spec]p14:
7447 // An implicitly declared special member function (Clause 12) shall have an
7448 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007449 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007450 if (ClassDecl->isInvalidDecl())
7451 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007452
Sebastian Redl60618fa2011-03-12 11:50:43 +00007453 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007454 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7455 BEnd = ClassDecl->bases_end();
7456 B != BEnd; ++B) {
7457 if (B->isVirtual()) // Handled below.
7458 continue;
7459
Douglas Gregor18274032010-07-03 00:47:00 +00007460 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7461 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007462 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7463 // If this is a deleted function, add it anyway. This might be conformant
7464 // with the standard. This might not. I'm not sure. It might not matter.
7465 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007466 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007467 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007468 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007469
7470 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007471 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7472 BEnd = ClassDecl->vbases_end();
7473 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007474 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7475 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007476 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7477 // If this is a deleted function, add it anyway. This might be conformant
7478 // with the standard. This might not. I'm not sure. It might not matter.
7479 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007480 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007481 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007482 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007483
7484 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007485 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7486 FEnd = ClassDecl->field_end();
7487 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007488 if (F->hasInClassInitializer()) {
7489 if (Expr *E = F->getInClassInitializer())
7490 ExceptSpec.CalledExpr(E);
7491 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007492 // DR1351:
7493 // If the brace-or-equal-initializer of a non-static data member
7494 // invokes a defaulted default constructor of its class or of an
7495 // enclosing class in a potentially evaluated subexpression, the
7496 // program is ill-formed.
7497 //
7498 // This resolution is unworkable: the exception specification of the
7499 // default constructor can be needed in an unevaluated context, in
7500 // particular, in the operand of a noexcept-expression, and we can be
7501 // unable to compute an exception specification for an enclosed class.
7502 //
7503 // We do not allow an in-class initializer to require the evaluation
7504 // of the exception specification for any in-class initializer whose
7505 // definition is not lexically complete.
7506 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007507 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007508 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007509 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7510 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7511 // If this is a deleted function, add it anyway. This might be conformant
7512 // with the standard. This might not. I'm not sure. It might not matter.
7513 // In particular, the problem is that this function never gets called. It
7514 // might just be ill-formed because this function attempts to refer to
7515 // a deleted function here.
7516 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007517 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007518 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007519 }
John McCalle23cf432010-12-14 08:05:40 +00007520
Sean Hunt001cad92011-05-10 00:49:42 +00007521 return ExceptSpec;
7522}
7523
Richard Smith07b0fdc2013-03-18 21:12:30 +00007524Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007525Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7526 CXXRecordDecl *ClassDecl = CD->getParent();
7527
7528 // C++ [except.spec]p14:
7529 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007530 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007531 if (ClassDecl->isInvalidDecl())
7532 return ExceptSpec;
7533
7534 // Inherited constructor.
7535 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7536 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7537 // FIXME: Copying or moving the parameters could add extra exceptions to the
7538 // set, as could the default arguments for the inherited constructor. This
7539 // will be addressed when we implement the resolution of core issue 1351.
7540 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7541
7542 // Direct base-class constructors.
7543 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7544 BEnd = ClassDecl->bases_end();
7545 B != BEnd; ++B) {
7546 if (B->isVirtual()) // Handled below.
7547 continue;
7548
7549 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7550 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7551 if (BaseClassDecl == InheritedDecl)
7552 continue;
7553 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7554 if (Constructor)
7555 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7556 }
7557 }
7558
7559 // Virtual base-class constructors.
7560 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7561 BEnd = ClassDecl->vbases_end();
7562 B != BEnd; ++B) {
7563 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7564 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7565 if (BaseClassDecl == InheritedDecl)
7566 continue;
7567 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7568 if (Constructor)
7569 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7570 }
7571 }
7572
7573 // Field constructors.
7574 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7575 FEnd = ClassDecl->field_end();
7576 F != FEnd; ++F) {
7577 if (F->hasInClassInitializer()) {
7578 if (Expr *E = F->getInClassInitializer())
7579 ExceptSpec.CalledExpr(E);
7580 else if (!F->isInvalidDecl())
7581 Diag(CD->getLocation(),
7582 diag::err_in_class_initializer_references_def_ctor) << CD;
7583 } else if (const RecordType *RecordTy
7584 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7585 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7586 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7587 if (Constructor)
7588 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7589 }
7590 }
7591
Richard Smith07b0fdc2013-03-18 21:12:30 +00007592 return ExceptSpec;
7593}
7594
Richard Smithafb49182012-11-29 01:34:07 +00007595namespace {
7596/// RAII object to register a special member as being currently declared.
7597struct DeclaringSpecialMember {
7598 Sema &S;
7599 Sema::SpecialMemberDecl D;
7600 bool WasAlreadyBeingDeclared;
7601
7602 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7603 : S(S), D(RD, CSM) {
7604 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7605 if (WasAlreadyBeingDeclared)
7606 // This almost never happens, but if it does, ensure that our cache
7607 // doesn't contain a stale result.
7608 S.SpecialMemberCache.clear();
7609
7610 // FIXME: Register a note to be produced if we encounter an error while
7611 // declaring the special member.
7612 }
7613 ~DeclaringSpecialMember() {
7614 if (!WasAlreadyBeingDeclared)
7615 S.SpecialMembersBeingDeclared.erase(D);
7616 }
7617
7618 /// \brief Are we already trying to declare this special member?
7619 bool isAlreadyBeingDeclared() const {
7620 return WasAlreadyBeingDeclared;
7621 }
7622};
7623}
7624
Sean Hunt001cad92011-05-10 00:49:42 +00007625CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7626 CXXRecordDecl *ClassDecl) {
7627 // C++ [class.ctor]p5:
7628 // A default constructor for a class X is a constructor of class X
7629 // that can be called without an argument. If there is no
7630 // user-declared constructor for class X, a default constructor is
7631 // implicitly declared. An implicitly-declared default constructor
7632 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007633 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007634 "Should not build implicit default constructor!");
7635
Richard Smithafb49182012-11-29 01:34:07 +00007636 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7637 if (DSM.isAlreadyBeingDeclared())
7638 return 0;
7639
Richard Smith7756afa2012-06-10 05:43:50 +00007640 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7641 CXXDefaultConstructor,
7642 false);
7643
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007644 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007645 CanQualType ClassType
7646 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007647 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007648 DeclarationName Name
7649 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007650 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007651 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007652 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007653 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007654 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007655 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007656 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007657 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007658
7659 // Build an exception specification pointing back at this constructor.
7660 FunctionProtoType::ExtProtoInfo EPI;
7661 EPI.ExceptionSpecType = EST_Unevaluated;
7662 EPI.ExceptionSpecDecl = DefaultCon;
Jordan Rosebea522f2013-03-08 21:51:21 +00007663 DefaultCon->setType(Context.getFunctionType(Context.VoidTy,
7664 ArrayRef<QualType>(),
7665 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007666
Richard Smithbc2a35d2012-12-08 08:32:28 +00007667 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7668 // constructors is easy to compute.
7669 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7670
7671 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007672 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007673
Douglas Gregor18274032010-07-03 00:47:00 +00007674 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007675 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007676
Douglas Gregor23c94db2010-07-02 17:43:08 +00007677 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007678 PushOnScopeChains(DefaultCon, S, false);
7679 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007680
Douglas Gregor32df23e2010-07-01 22:02:46 +00007681 return DefaultCon;
7682}
7683
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007684void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7685 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007686 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007687 !Constructor->doesThisDeclarationHaveABody() &&
7688 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007689 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007690
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007691 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007692 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007693
Eli Friedman9a14db32012-10-18 20:14:08 +00007694 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007695 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007696 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007697 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007698 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007699 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007700 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007701 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007702 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007703
7704 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007705 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007706
7707 Constructor->setUsed();
7708 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007709
7710 if (ASTMutationListener *L = getASTMutationListener()) {
7711 L->CompletedImplicitDefinition(Constructor);
7712 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007713}
7714
Richard Smith7a614d82011-06-11 17:19:42 +00007715void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007716 // Check that any explicitly-defaulted methods have exception specifications
7717 // compatible with their implicit exception specifications.
7718 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007719}
7720
Richard Smith4841ca52013-04-10 05:48:59 +00007721namespace {
7722/// Information on inheriting constructors to declare.
7723class InheritingConstructorInfo {
7724public:
7725 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7726 : SemaRef(SemaRef), Derived(Derived) {
7727 // Mark the constructors that we already have in the derived class.
7728 //
7729 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7730 // unless there is a user-declared constructor with the same signature in
7731 // the class where the using-declaration appears.
7732 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7733 }
7734
7735 void inheritAll(CXXRecordDecl *RD) {
7736 visitAll(RD, &InheritingConstructorInfo::inherit);
7737 }
7738
7739private:
7740 /// Information about an inheriting constructor.
7741 struct InheritingConstructor {
7742 InheritingConstructor()
7743 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7744
7745 /// If \c true, a constructor with this signature is already declared
7746 /// in the derived class.
7747 bool DeclaredInDerived;
7748
7749 /// The constructor which is inherited.
7750 const CXXConstructorDecl *BaseCtor;
7751
7752 /// The derived constructor we declared.
7753 CXXConstructorDecl *DerivedCtor;
7754 };
7755
7756 /// Inheriting constructors with a given canonical type. There can be at
7757 /// most one such non-template constructor, and any number of templated
7758 /// constructors.
7759 struct InheritingConstructorsForType {
7760 InheritingConstructor NonTemplate;
7761 llvm::SmallVector<
7762 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7763
7764 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7765 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7766 TemplateParameterList *ParamList = FTD->getTemplateParameters();
7767 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7768 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7769 false, S.TPL_TemplateMatch))
7770 return Templates[I].second;
7771 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7772 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007773 }
Richard Smith4841ca52013-04-10 05:48:59 +00007774
7775 return NonTemplate;
7776 }
7777 };
7778
7779 /// Get or create the inheriting constructor record for a constructor.
7780 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7781 QualType CtorType) {
7782 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7783 .getEntry(SemaRef, Ctor);
7784 }
7785
7786 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7787
7788 /// Process all constructors for a class.
7789 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7790 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7791 CtorE = RD->ctor_end();
7792 CtorIt != CtorE; ++CtorIt)
7793 (this->*Callback)(*CtorIt);
7794 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7795 I(RD->decls_begin()), E(RD->decls_end());
7796 I != E; ++I) {
7797 const FunctionDecl *FD = (*I)->getTemplatedDecl();
7798 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7799 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007800 }
7801 }
Richard Smith4841ca52013-04-10 05:48:59 +00007802
7803 /// Note that a constructor (or constructor template) was declared in Derived.
7804 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7805 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7806 }
7807
7808 /// Inherit a single constructor.
7809 void inherit(const CXXConstructorDecl *Ctor) {
7810 const FunctionProtoType *CtorType =
7811 Ctor->getType()->castAs<FunctionProtoType>();
7812 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7813 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7814
7815 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7816
7817 // Core issue (no number yet): the ellipsis is always discarded.
7818 if (EPI.Variadic) {
7819 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7820 SemaRef.Diag(Ctor->getLocation(),
7821 diag::note_using_decl_constructor_ellipsis);
7822 EPI.Variadic = false;
7823 }
7824
7825 // Declare a constructor for each number of parameters.
7826 //
7827 // C++11 [class.inhctor]p1:
7828 // The candidate set of inherited constructors from the class X named in
7829 // the using-declaration consists of [... modulo defects ...] for each
7830 // constructor or constructor template of X, the set of constructors or
7831 // constructor templates that results from omitting any ellipsis parameter
7832 // specification and successively omitting parameters with a default
7833 // argument from the end of the parameter-type-list
7834 for (unsigned Params = std::max(minParamsToInherit(Ctor),
7835 Ctor->getMinRequiredArguments()),
7836 MaxParams = Ctor->getNumParams();
7837 Params <= MaxParams; ++Params)
7838 declareCtor(UsingLoc, Ctor,
7839 SemaRef.Context.getFunctionType(
7840 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7841 }
7842
7843 /// Find the using-declaration which specified that we should inherit the
7844 /// constructors of \p Base.
7845 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
7846 // No fancy lookup required; just look for the base constructor name
7847 // directly within the derived class.
7848 ASTContext &Context = SemaRef.Context;
7849 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
7850 Context.getCanonicalType(Context.getRecordType(Base)));
7851 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
7852 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
7853 }
7854
7855 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
7856 // C++11 [class.inhctor]p3:
7857 // [F]or each constructor template in the candidate set of inherited
7858 // constructors, a constructor template is implicitly declared
7859 if (Ctor->getDescribedFunctionTemplate())
7860 return 0;
7861
7862 // For each non-template constructor in the candidate set of inherited
7863 // constructors other than a constructor having no parameters or a
7864 // copy/move constructor having a single parameter, a constructor is
7865 // implicitly declared [...]
7866 if (Ctor->getNumParams() == 0)
7867 return 1;
7868 if (Ctor->isCopyOrMoveConstructor())
7869 return 2;
7870
7871 // Per discussion on core reflector, never inherit a constructor which
7872 // would become a default, copy, or move constructor of Derived either.
7873 const ParmVarDecl *PD = Ctor->getParamDecl(0);
7874 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
7875 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
7876 }
7877
7878 /// Declare a single inheriting constructor, inheriting the specified
7879 /// constructor, with the given type.
7880 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
7881 QualType DerivedType) {
7882 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
7883
7884 // C++11 [class.inhctor]p3:
7885 // ... a constructor is implicitly declared with the same constructor
7886 // characteristics unless there is a user-declared constructor with
7887 // the same signature in the class where the using-declaration appears
7888 if (Entry.DeclaredInDerived)
7889 return;
7890
7891 // C++11 [class.inhctor]p7:
7892 // If two using-declarations declare inheriting constructors with the
7893 // same signature, the program is ill-formed
7894 if (Entry.DerivedCtor) {
7895 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
7896 // Only diagnose this once per constructor.
7897 if (Entry.DerivedCtor->isInvalidDecl())
7898 return;
7899 Entry.DerivedCtor->setInvalidDecl();
7900
7901 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7902 SemaRef.Diag(BaseCtor->getLocation(),
7903 diag::note_using_decl_constructor_conflict_current_ctor);
7904 SemaRef.Diag(Entry.BaseCtor->getLocation(),
7905 diag::note_using_decl_constructor_conflict_previous_ctor);
7906 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
7907 diag::note_using_decl_constructor_conflict_previous_using);
7908 } else {
7909 // Core issue (no number): if the same inheriting constructor is
7910 // produced by multiple base class constructors from the same base
7911 // class, the inheriting constructor is defined as deleted.
7912 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
7913 }
7914
7915 return;
7916 }
7917
7918 ASTContext &Context = SemaRef.Context;
7919 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
7920 Context.getCanonicalType(Context.getRecordType(Derived)));
7921 DeclarationNameInfo NameInfo(Name, UsingLoc);
7922
7923 TemplateParameterList *TemplateParams = 0;
7924 if (const FunctionTemplateDecl *FTD =
7925 BaseCtor->getDescribedFunctionTemplate()) {
7926 TemplateParams = FTD->getTemplateParameters();
7927 // We're reusing template parameters from a different DeclContext. This
7928 // is questionable at best, but works out because the template depth in
7929 // both places is guaranteed to be 0.
7930 // FIXME: Rebuild the template parameters in the new context, and
7931 // transform the function type to refer to them.
7932 }
7933
7934 // Build type source info pointing at the using-declaration. This is
7935 // required by template instantiation.
7936 TypeSourceInfo *TInfo =
7937 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
7938 FunctionProtoTypeLoc ProtoLoc =
7939 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
7940
7941 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
7942 Context, Derived, UsingLoc, NameInfo, DerivedType,
7943 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
7944 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
7945
7946 // Build an unevaluated exception specification for this constructor.
7947 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
7948 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7949 EPI.ExceptionSpecType = EST_Unevaluated;
7950 EPI.ExceptionSpecDecl = DerivedCtor;
7951 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
7952 FPT->getArgTypes(), EPI));
7953
7954 // Build the parameter declarations.
7955 SmallVector<ParmVarDecl *, 16> ParamDecls;
7956 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
7957 TypeSourceInfo *TInfo =
7958 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
7959 ParmVarDecl *PD = ParmVarDecl::Create(
7960 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
7961 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
7962 PD->setScopeInfo(0, I);
7963 PD->setImplicit();
7964 ParamDecls.push_back(PD);
7965 ProtoLoc.setArg(I, PD);
7966 }
7967
7968 // Set up the new constructor.
7969 DerivedCtor->setAccess(BaseCtor->getAccess());
7970 DerivedCtor->setParams(ParamDecls);
7971 DerivedCtor->setInheritedConstructor(BaseCtor);
7972 if (BaseCtor->isDeleted())
7973 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
7974
7975 // If this is a constructor template, build the template declaration.
7976 if (TemplateParams) {
7977 FunctionTemplateDecl *DerivedTemplate =
7978 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
7979 TemplateParams, DerivedCtor);
7980 DerivedTemplate->setAccess(BaseCtor->getAccess());
7981 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
7982 Derived->addDecl(DerivedTemplate);
7983 } else {
7984 Derived->addDecl(DerivedCtor);
7985 }
7986
7987 Entry.BaseCtor = BaseCtor;
7988 Entry.DerivedCtor = DerivedCtor;
7989 }
7990
7991 Sema &SemaRef;
7992 CXXRecordDecl *Derived;
7993 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
7994 MapType Map;
7995};
7996}
7997
7998void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
7999 // Defer declaring the inheriting constructors until the class is
8000 // instantiated.
8001 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008002 return;
8003
Richard Smith4841ca52013-04-10 05:48:59 +00008004 // Find base classes from which we might inherit constructors.
8005 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8006 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8007 BaseE = ClassDecl->bases_end();
8008 BaseIt != BaseE; ++BaseIt)
8009 if (BaseIt->getInheritConstructors())
8010 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008011
Richard Smith4841ca52013-04-10 05:48:59 +00008012 // Go no further if we're not inheriting any constructors.
8013 if (InheritedBases.empty())
8014 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008015
Richard Smith4841ca52013-04-10 05:48:59 +00008016 // Declare the inherited constructors.
8017 InheritingConstructorInfo ICI(*this, ClassDecl);
8018 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8019 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008020}
8021
Richard Smith07b0fdc2013-03-18 21:12:30 +00008022void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8023 CXXConstructorDecl *Constructor) {
8024 CXXRecordDecl *ClassDecl = Constructor->getParent();
8025 assert(Constructor->getInheritedConstructor() &&
8026 !Constructor->doesThisDeclarationHaveABody() &&
8027 !Constructor->isDeleted());
8028
8029 SynthesizedFunctionScope Scope(*this, Constructor);
8030 DiagnosticErrorTrap Trap(Diags);
8031 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8032 Trap.hasErrorOccurred()) {
8033 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8034 << Context.getTagDeclType(ClassDecl);
8035 Constructor->setInvalidDecl();
8036 return;
8037 }
8038
8039 SourceLocation Loc = Constructor->getLocation();
8040 Constructor->setBody(new (Context) CompoundStmt(Loc));
8041
8042 Constructor->setUsed();
8043 MarkVTableUsed(CurrentLocation, ClassDecl);
8044
8045 if (ASTMutationListener *L = getASTMutationListener()) {
8046 L->CompletedImplicitDefinition(Constructor);
8047 }
8048}
8049
8050
Sean Huntcb45a0f2011-05-12 22:46:25 +00008051Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008052Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8053 CXXRecordDecl *ClassDecl = MD->getParent();
8054
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008055 // C++ [except.spec]p14:
8056 // An implicitly declared special member function (Clause 12) shall have
8057 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008058 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008059 if (ClassDecl->isInvalidDecl())
8060 return ExceptSpec;
8061
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008062 // Direct base-class destructors.
8063 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8064 BEnd = ClassDecl->bases_end();
8065 B != BEnd; ++B) {
8066 if (B->isVirtual()) // Handled below.
8067 continue;
8068
8069 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008070 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008071 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008072 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008073
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008074 // Virtual base-class destructors.
8075 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8076 BEnd = ClassDecl->vbases_end();
8077 B != BEnd; ++B) {
8078 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008079 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008080 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008081 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008082
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008083 // Field destructors.
8084 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8085 FEnd = ClassDecl->field_end();
8086 F != FEnd; ++F) {
8087 if (const RecordType *RecordTy
8088 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008089 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008090 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008091 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008092
Sean Huntcb45a0f2011-05-12 22:46:25 +00008093 return ExceptSpec;
8094}
8095
8096CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8097 // C++ [class.dtor]p2:
8098 // If a class has no user-declared destructor, a destructor is
8099 // declared implicitly. An implicitly-declared destructor is an
8100 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008101 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008102
Richard Smithafb49182012-11-29 01:34:07 +00008103 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8104 if (DSM.isAlreadyBeingDeclared())
8105 return 0;
8106
Douglas Gregor4923aa22010-07-02 20:37:36 +00008107 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008108 CanQualType ClassType
8109 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008110 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008111 DeclarationName Name
8112 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008113 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008114 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008115 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8116 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008117 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008118 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008119 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008120 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008121
8122 // Build an exception specification pointing back at this destructor.
8123 FunctionProtoType::ExtProtoInfo EPI;
8124 EPI.ExceptionSpecType = EST_Unevaluated;
8125 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00008126 Destructor->setType(Context.getFunctionType(Context.VoidTy,
8127 ArrayRef<QualType>(),
8128 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008129
Richard Smithbc2a35d2012-12-08 08:32:28 +00008130 AddOverriddenMethods(ClassDecl, Destructor);
8131
8132 // We don't need to use SpecialMemberIsTrivial here; triviality for
8133 // destructors is easy to compute.
8134 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8135
8136 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008137 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008138
Douglas Gregor4923aa22010-07-02 20:37:36 +00008139 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008140 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008141
Douglas Gregor4923aa22010-07-02 20:37:36 +00008142 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008143 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008144 PushOnScopeChains(Destructor, S, false);
8145 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008146
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008147 return Destructor;
8148}
8149
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008150void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008151 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008152 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008153 !Destructor->doesThisDeclarationHaveABody() &&
8154 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008155 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008156 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008157 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008158
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008159 if (Destructor->isInvalidDecl())
8160 return;
8161
Eli Friedman9a14db32012-10-18 20:14:08 +00008162 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008163
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008164 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008165 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8166 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008167
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008168 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008169 Diag(CurrentLocation, diag::note_member_synthesized_at)
8170 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8171
8172 Destructor->setInvalidDecl();
8173 return;
8174 }
8175
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008176 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008177 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008178 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008179 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008180 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008181
8182 if (ASTMutationListener *L = getASTMutationListener()) {
8183 L->CompletedImplicitDefinition(Destructor);
8184 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008185}
8186
Richard Smitha4156b82012-04-21 18:42:51 +00008187/// \brief Perform any semantic analysis which needs to be delayed until all
8188/// pending class member declarations have been parsed.
8189void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008190 // If the context is an invalid C++ class, just suppress these checks.
8191 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8192 if (Record->isInvalidDecl()) {
8193 DelayedDestructorExceptionSpecChecks.clear();
8194 return;
8195 }
8196 }
8197
Richard Smitha4156b82012-04-21 18:42:51 +00008198 // Perform any deferred checking of exception specifications for virtual
8199 // destructors.
8200 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8201 i != e; ++i) {
8202 const CXXDestructorDecl *Dtor =
8203 DelayedDestructorExceptionSpecChecks[i].first;
8204 assert(!Dtor->getParent()->isDependentType() &&
8205 "Should not ever add destructors of templates into the list.");
8206 CheckOverridingFunctionExceptionSpec(Dtor,
8207 DelayedDestructorExceptionSpecChecks[i].second);
8208 }
8209 DelayedDestructorExceptionSpecChecks.clear();
8210}
8211
Richard Smithb9d0b762012-07-27 04:22:15 +00008212void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8213 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008214 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008215 "adjusting dtor exception specs was introduced in c++11");
8216
Sebastian Redl0ee33912011-05-19 05:13:44 +00008217 // C++11 [class.dtor]p3:
8218 // A declaration of a destructor that does not have an exception-
8219 // specification is implicitly considered to have the same exception-
8220 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008221 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008222 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008223 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008224 return;
8225
Chandler Carruth3f224b22011-09-20 04:55:26 +00008226 // Replace the destructor's type, building off the existing one. Fortunately,
8227 // the only thing of interest in the destructor type is its extended info.
8228 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008229 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8230 EPI.ExceptionSpecType = EST_Unevaluated;
8231 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00008232 Destructor->setType(Context.getFunctionType(Context.VoidTy,
8233 ArrayRef<QualType>(),
8234 EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008235
Sebastian Redl0ee33912011-05-19 05:13:44 +00008236 // FIXME: If the destructor has a body that could throw, and the newly created
8237 // spec doesn't allow exceptions, we should emit a warning, because this
8238 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008239 // However, we don't have a body or an exception specification yet, so it
8240 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008241}
8242
Richard Smith8c889532012-11-14 00:50:40 +00008243/// When generating a defaulted copy or move assignment operator, if a field
8244/// should be copied with __builtin_memcpy rather than via explicit assignments,
8245/// do so. This optimization only applies for arrays of scalars, and for arrays
8246/// of class type where the selected copy/move-assignment operator is trivial.
8247static StmtResult
8248buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8249 Expr *To, Expr *From) {
8250 // Compute the size of the memory buffer to be copied.
8251 QualType SizeType = S.Context.getSizeType();
8252 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8253 S.Context.getTypeSizeInChars(T).getQuantity());
8254
8255 // Take the address of the field references for "from" and "to". We
8256 // directly construct UnaryOperators here because semantic analysis
8257 // does not permit us to take the address of an xvalue.
8258 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8259 S.Context.getPointerType(From->getType()),
8260 VK_RValue, OK_Ordinary, Loc);
8261 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8262 S.Context.getPointerType(To->getType()),
8263 VK_RValue, OK_Ordinary, Loc);
8264
8265 const Type *E = T->getBaseElementTypeUnsafe();
8266 bool NeedsCollectableMemCpy =
8267 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8268
8269 // Create a reference to the __builtin_objc_memmove_collectable function
8270 StringRef MemCpyName = NeedsCollectableMemCpy ?
8271 "__builtin_objc_memmove_collectable" :
8272 "__builtin_memcpy";
8273 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8274 Sema::LookupOrdinaryName);
8275 S.LookupName(R, S.TUScope, true);
8276
8277 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8278 if (!MemCpy)
8279 // Something went horribly wrong earlier, and we will have complained
8280 // about it.
8281 return StmtError();
8282
8283 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8284 VK_RValue, Loc, 0);
8285 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8286
8287 Expr *CallArgs[] = {
8288 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8289 };
8290 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8291 Loc, CallArgs, Loc);
8292
8293 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8294 return S.Owned(Call.takeAs<Stmt>());
8295}
8296
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008297/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008298/// \c To.
8299///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008300/// This routine is used to copy/move the members of a class with an
8301/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008302/// copied are arrays, this routine builds for loops to copy them.
8303///
8304/// \param S The Sema object used for type-checking.
8305///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008306/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008307///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008308/// \param T The type of the expressions being copied/moved. Both expressions
8309/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008310///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008311/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008312///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008313/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008314///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008315/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008316/// Otherwise, it's a non-static member subobject.
8317///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008318/// \param Copying Whether we're copying or moving.
8319///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008320/// \param Depth Internal parameter recording the depth of the recursion.
8321///
Richard Smith8c889532012-11-14 00:50:40 +00008322/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8323/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008324static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008325buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8326 Expr *To, Expr *From,
8327 bool CopyingBaseSubobject, bool Copying,
8328 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008329 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008330 // Each subobject is assigned in the manner appropriate to its type:
8331 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008332 // - if the subobject is of class type, as if by a call to operator= with
8333 // the subobject as the object expression and the corresponding
8334 // subobject of x as a single function argument (as if by explicit
8335 // qualification; that is, ignoring any possible virtual overriding
8336 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008337 //
8338 // C++03 [class.copy]p13:
8339 // - if the subobject is of class type, the copy assignment operator for
8340 // the class is used (as if by explicit qualification; that is,
8341 // ignoring any possible virtual overriding functions in more derived
8342 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008343 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8344 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008345
Douglas Gregor06a9f362010-05-01 20:49:11 +00008346 // Look for operator=.
8347 DeclarationName Name
8348 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8349 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8350 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008351
Richard Smith044c8aa2012-11-13 00:54:12 +00008352 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8353 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008354 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008355 LookupResult::Filter F = OpLookup.makeFilter();
8356 while (F.hasNext()) {
8357 NamedDecl *D = F.next();
8358 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8359 if (Method->isCopyAssignmentOperator() ||
8360 (!Copying && Method->isMoveAssignmentOperator()))
8361 continue;
8362
8363 F.erase();
8364 }
8365 F.done();
John McCallb0207482010-03-16 06:11:48 +00008366 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008367
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008368 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008369 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008370 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008371 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008372 // ambiguities), we need to cast "this" to that subobject type; to
8373 // ensure that we don't go through the virtual call mechanism, we need
8374 // to qualify the operator= name with the base class (see below). However,
8375 // this means that if the base class has a protected copy assignment
8376 // operator, the protected member access check will fail. So, we
8377 // rewrite "protected" access to "public" access in this case, since we
8378 // know by construction that we're calling from a derived class.
8379 if (CopyingBaseSubobject) {
8380 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8381 L != LEnd; ++L) {
8382 if (L.getAccess() == AS_protected)
8383 L.setAccess(AS_public);
8384 }
8385 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008386
Douglas Gregor06a9f362010-05-01 20:49:11 +00008387 // Create the nested-name-specifier that will be used to qualify the
8388 // reference to operator=; this is required to suppress the virtual
8389 // call mechanism.
8390 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008391 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008392 SS.MakeTrivial(S.Context,
8393 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008394 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008395 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008396
Douglas Gregor06a9f362010-05-01 20:49:11 +00008397 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008398 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008399 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008400 /*TemplateKWLoc=*/SourceLocation(),
8401 /*FirstQualifierInScope=*/0,
8402 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008403 /*TemplateArgs=*/0,
8404 /*SuppressQualifierCheck=*/true);
8405 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008406 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008407
Douglas Gregor06a9f362010-05-01 20:49:11 +00008408 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008409
Richard Smith044c8aa2012-11-13 00:54:12 +00008410 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008411 OpEqualRef.takeAs<Expr>(),
8412 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008413 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008414 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008415
Richard Smith8c889532012-11-14 00:50:40 +00008416 // If we built a call to a trivial 'operator=' while copying an array,
8417 // bail out. We'll replace the whole shebang with a memcpy.
8418 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8419 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8420 return StmtResult((Stmt*)0);
8421
Richard Smith044c8aa2012-11-13 00:54:12 +00008422 // Convert to an expression-statement, and clean up any produced
8423 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008424 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008425 }
John McCallb0207482010-03-16 06:11:48 +00008426
Richard Smith044c8aa2012-11-13 00:54:12 +00008427 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008428 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008429 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008430 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008431 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008432 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008433 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008434 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008435 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008436
8437 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008438 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008439
Douglas Gregor06a9f362010-05-01 20:49:11 +00008440 // Construct a loop over the array bounds, e.g.,
8441 //
8442 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8443 //
8444 // that will copy each of the array elements.
8445 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008446
Douglas Gregor06a9f362010-05-01 20:49:11 +00008447 // Create the iteration variable.
8448 IdentifierInfo *IterationVarName = 0;
8449 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008450 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008451 llvm::raw_svector_ostream OS(Str);
8452 OS << "__i" << Depth;
8453 IterationVarName = &S.Context.Idents.get(OS.str());
8454 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008455 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008456 IterationVarName, SizeType,
8457 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008458 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008459
Douglas Gregor06a9f362010-05-01 20:49:11 +00008460 // Initialize the iteration variable to zero.
8461 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008462 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008463
8464 // Create a reference to the iteration variable; we'll use this several
8465 // times throughout.
8466 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008467 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008468 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008469 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8470 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8471
Douglas Gregor06a9f362010-05-01 20:49:11 +00008472 // Create the DeclStmt that holds the iteration variable.
8473 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008474
Douglas Gregor06a9f362010-05-01 20:49:11 +00008475 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008476 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008477 IterationVarRefRVal,
8478 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008479 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008480 IterationVarRefRVal,
8481 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008482 if (!Copying) // Cast to rvalue
8483 From = CastForMoving(S, From);
8484
8485 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008486 StmtResult Copy =
8487 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8488 To, From, CopyingBaseSubobject,
8489 Copying, Depth + 1);
8490 // Bail out if copying fails or if we determined that we should use memcpy.
8491 if (Copy.isInvalid() || !Copy.get())
8492 return Copy;
8493
8494 // Create the comparison against the array bound.
8495 llvm::APInt Upper
8496 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8497 Expr *Comparison
8498 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8499 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8500 BO_NE, S.Context.BoolTy,
8501 VK_RValue, OK_Ordinary, Loc, false);
8502
8503 // Create the pre-increment of the iteration variable.
8504 Expr *Increment
8505 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8506 VK_LValue, OK_Ordinary, Loc);
8507
Douglas Gregor06a9f362010-05-01 20:49:11 +00008508 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008509 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008510 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008511 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008512 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008513}
8514
Richard Smith8c889532012-11-14 00:50:40 +00008515static StmtResult
8516buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8517 Expr *To, Expr *From,
8518 bool CopyingBaseSubobject, bool Copying) {
8519 // Maybe we should use a memcpy?
8520 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8521 T.isTriviallyCopyableType(S.Context))
8522 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8523
8524 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8525 CopyingBaseSubobject,
8526 Copying, 0));
8527
8528 // If we ended up picking a trivial assignment operator for an array of a
8529 // non-trivially-copyable class type, just emit a memcpy.
8530 if (!Result.isInvalid() && !Result.get())
8531 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8532
8533 return Result;
8534}
8535
Richard Smithb9d0b762012-07-27 04:22:15 +00008536Sema::ImplicitExceptionSpecification
8537Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8538 CXXRecordDecl *ClassDecl = MD->getParent();
8539
8540 ImplicitExceptionSpecification ExceptSpec(*this);
8541 if (ClassDecl->isInvalidDecl())
8542 return ExceptSpec;
8543
8544 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8545 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8546 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8547
Douglas Gregorb87786f2010-07-01 17:48:08 +00008548 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008549 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008550 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008551
8552 // It is unspecified whether or not an implicit copy assignment operator
8553 // attempts to deduplicate calls to assignment operators of virtual bases are
8554 // made. As such, this exception specification is effectively unspecified.
8555 // Based on a similar decision made for constness in C++0x, we're erring on
8556 // the side of assuming such calls to be made regardless of whether they
8557 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008558 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8559 BaseEnd = ClassDecl->bases_end();
8560 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008561 if (Base->isVirtual())
8562 continue;
8563
Douglas Gregora376d102010-07-02 21:50:04 +00008564 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008565 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008566 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8567 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008568 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008569 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008570
8571 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8572 BaseEnd = ClassDecl->vbases_end();
8573 Base != BaseEnd; ++Base) {
8574 CXXRecordDecl *BaseClassDecl
8575 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8576 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8577 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008578 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008579 }
8580
Douglas Gregorb87786f2010-07-01 17:48:08 +00008581 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8582 FieldEnd = ClassDecl->field_end();
8583 Field != FieldEnd;
8584 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008585 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008586 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8587 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008588 LookupCopyingAssignment(FieldClassDecl,
8589 ArgQuals | FieldType.getCVRQualifiers(),
8590 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008591 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008592 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008593 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008594
Richard Smithb9d0b762012-07-27 04:22:15 +00008595 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008596}
8597
8598CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8599 // Note: The following rules are largely analoguous to the copy
8600 // constructor rules. Note that virtual bases are not taken into account
8601 // for determining the argument type of the operator. Note also that
8602 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008603 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008604
Richard Smithafb49182012-11-29 01:34:07 +00008605 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8606 if (DSM.isAlreadyBeingDeclared())
8607 return 0;
8608
Sean Hunt30de05c2011-05-14 05:23:20 +00008609 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8610 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008611 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008612 ArgType = ArgType.withConst();
8613 ArgType = Context.getLValueReferenceType(ArgType);
8614
Douglas Gregord3c35902010-07-01 16:36:15 +00008615 // An implicitly-declared copy assignment operator is an inline public
8616 // member of its class.
8617 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008618 SourceLocation ClassLoc = ClassDecl->getLocation();
8619 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008620 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008621 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008622 /*TInfo=*/0,
8623 /*StorageClass=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008624 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008625 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008626 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008627 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008628 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008629
8630 // Build an exception specification pointing back at this member.
8631 FunctionProtoType::ExtProtoInfo EPI;
8632 EPI.ExceptionSpecType = EST_Unevaluated;
8633 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008634 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008635
Douglas Gregord3c35902010-07-01 16:36:15 +00008636 // Add the parameter to the operator.
8637 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008638 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008639 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008640 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008641 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008642
Richard Smithbc2a35d2012-12-08 08:32:28 +00008643 AddOverriddenMethods(ClassDecl, CopyAssignment);
8644
8645 CopyAssignment->setTrivial(
8646 ClassDecl->needsOverloadResolutionForCopyAssignment()
8647 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8648 : ClassDecl->hasTrivialCopyAssignment());
8649
Nico Weberafcc96a2012-01-23 03:19:29 +00008650 // C++0x [class.copy]p19:
8651 // .... If the class definition does not explicitly declare a copy
8652 // assignment operator, there is no user-declared move constructor, and
8653 // there is no user-declared move assignment operator, a copy assignment
8654 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008655 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008656 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008657
Richard Smithbc2a35d2012-12-08 08:32:28 +00008658 // Note that we have added this copy-assignment operator.
8659 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8660
8661 if (Scope *S = getScopeForContext(ClassDecl))
8662 PushOnScopeChains(CopyAssignment, S, false);
8663 ClassDecl->addDecl(CopyAssignment);
8664
Douglas Gregord3c35902010-07-01 16:36:15 +00008665 return CopyAssignment;
8666}
8667
Douglas Gregor06a9f362010-05-01 20:49:11 +00008668void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8669 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008670 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008671 CopyAssignOperator->isOverloadedOperator() &&
8672 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008673 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8674 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008675 "DefineImplicitCopyAssignment called for wrong function");
8676
8677 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8678
8679 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8680 CopyAssignOperator->setInvalidDecl();
8681 return;
8682 }
8683
8684 CopyAssignOperator->setUsed();
8685
Eli Friedman9a14db32012-10-18 20:14:08 +00008686 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008687 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008688
8689 // C++0x [class.copy]p30:
8690 // The implicitly-defined or explicitly-defaulted copy assignment operator
8691 // for a non-union class X performs memberwise copy assignment of its
8692 // subobjects. The direct base classes of X are assigned first, in the
8693 // order of their declaration in the base-specifier-list, and then the
8694 // immediate non-static data members of X are assigned, in the order in
8695 // which they were declared in the class definition.
8696
8697 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008698 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008699
8700 // The parameter for the "other" object, which we are copying from.
8701 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8702 Qualifiers OtherQuals = Other->getType().getQualifiers();
8703 QualType OtherRefType = Other->getType();
8704 if (const LValueReferenceType *OtherRef
8705 = OtherRefType->getAs<LValueReferenceType>()) {
8706 OtherRefType = OtherRef->getPointeeType();
8707 OtherQuals = OtherRefType.getQualifiers();
8708 }
8709
8710 // Our location for everything implicitly-generated.
8711 SourceLocation Loc = CopyAssignOperator->getLocation();
8712
8713 // Construct a reference to the "other" object. We'll be using this
8714 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008715 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008716 assert(OtherRef && "Reference to parameter cannot fail!");
8717
8718 // Construct the "this" pointer. We'll be using this throughout the generated
8719 // ASTs.
8720 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8721 assert(This && "Reference to this cannot fail!");
8722
8723 // Assign base classes.
8724 bool Invalid = false;
8725 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8726 E = ClassDecl->bases_end(); Base != E; ++Base) {
8727 // Form the assignment:
8728 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8729 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008730 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008731 Invalid = true;
8732 continue;
8733 }
8734
John McCallf871d0c2010-08-07 06:22:56 +00008735 CXXCastPath BasePath;
8736 BasePath.push_back(Base);
8737
Douglas Gregor06a9f362010-05-01 20:49:11 +00008738 // Construct the "from" expression, which is an implicit cast to the
8739 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008740 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008741 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8742 CK_UncheckedDerivedToBase,
8743 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008744
8745 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008746 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008747
8748 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008749 To = ImpCastExprToType(To.take(),
8750 Context.getCVRQualifiedType(BaseType,
8751 CopyAssignOperator->getTypeQualifiers()),
8752 CK_UncheckedDerivedToBase,
8753 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008754
8755 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008756 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008757 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008758 /*CopyingBaseSubobject=*/true,
8759 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008760 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008761 Diag(CurrentLocation, diag::note_member_synthesized_at)
8762 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8763 CopyAssignOperator->setInvalidDecl();
8764 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008765 }
8766
8767 // Success! Record the copy.
8768 Statements.push_back(Copy.takeAs<Expr>());
8769 }
8770
Douglas Gregor06a9f362010-05-01 20:49:11 +00008771 // Assign non-static members.
8772 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8773 FieldEnd = ClassDecl->field_end();
8774 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008775 if (Field->isUnnamedBitfield())
8776 continue;
8777
Douglas Gregor06a9f362010-05-01 20:49:11 +00008778 // Check for members of reference type; we can't copy those.
8779 if (Field->getType()->isReferenceType()) {
8780 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8781 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8782 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008783 Diag(CurrentLocation, diag::note_member_synthesized_at)
8784 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008785 Invalid = true;
8786 continue;
8787 }
8788
8789 // Check for members of const-qualified, non-class type.
8790 QualType BaseType = Context.getBaseElementType(Field->getType());
8791 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8792 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8793 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8794 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008795 Diag(CurrentLocation, diag::note_member_synthesized_at)
8796 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008797 Invalid = true;
8798 continue;
8799 }
John McCallb77115d2011-06-17 00:18:42 +00008800
8801 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008802 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8803 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008804
8805 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008806 if (FieldType->isIncompleteArrayType()) {
8807 assert(ClassDecl->hasFlexibleArrayMember() &&
8808 "Incomplete array type is not valid");
8809 continue;
8810 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008811
8812 // Build references to the field in the object we're copying from and to.
8813 CXXScopeSpec SS; // Intentionally empty
8814 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8815 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008816 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008817 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008818 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008819 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008820 SS, SourceLocation(), 0,
8821 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008822 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008823 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008824 SS, SourceLocation(), 0,
8825 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008826 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8827 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008828
Douglas Gregor06a9f362010-05-01 20:49:11 +00008829 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008830 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008831 To.get(), From.get(),
8832 /*CopyingBaseSubobject=*/false,
8833 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008834 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008835 Diag(CurrentLocation, diag::note_member_synthesized_at)
8836 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8837 CopyAssignOperator->setInvalidDecl();
8838 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008839 }
8840
8841 // Success! Record the copy.
8842 Statements.push_back(Copy.takeAs<Stmt>());
8843 }
8844
8845 if (!Invalid) {
8846 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008847 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008848
John McCall60d7b3a2010-08-24 06:29:42 +00008849 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008850 if (Return.isInvalid())
8851 Invalid = true;
8852 else {
8853 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008854
8855 if (Trap.hasErrorOccurred()) {
8856 Diag(CurrentLocation, diag::note_member_synthesized_at)
8857 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8858 Invalid = true;
8859 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008860 }
8861 }
8862
8863 if (Invalid) {
8864 CopyAssignOperator->setInvalidDecl();
8865 return;
8866 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008867
8868 StmtResult Body;
8869 {
8870 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008871 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008872 /*isStmtExpr=*/false);
8873 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8874 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008875 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008876
8877 if (ASTMutationListener *L = getASTMutationListener()) {
8878 L->CompletedImplicitDefinition(CopyAssignOperator);
8879 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008880}
8881
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008882Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008883Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8884 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008885
Richard Smithb9d0b762012-07-27 04:22:15 +00008886 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008887 if (ClassDecl->isInvalidDecl())
8888 return ExceptSpec;
8889
8890 // C++0x [except.spec]p14:
8891 // An implicitly declared special member function (Clause 12) shall have an
8892 // exception-specification. [...]
8893
8894 // It is unspecified whether or not an implicit move assignment operator
8895 // attempts to deduplicate calls to assignment operators of virtual bases are
8896 // made. As such, this exception specification is effectively unspecified.
8897 // Based on a similar decision made for constness in C++0x, we're erring on
8898 // the side of assuming such calls to be made regardless of whether they
8899 // actually happen.
8900 // Note that a move constructor is not implicitly declared when there are
8901 // virtual bases, but it can still be user-declared and explicitly defaulted.
8902 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8903 BaseEnd = ClassDecl->bases_end();
8904 Base != BaseEnd; ++Base) {
8905 if (Base->isVirtual())
8906 continue;
8907
8908 CXXRecordDecl *BaseClassDecl
8909 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8910 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008911 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008912 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008913 }
8914
8915 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8916 BaseEnd = ClassDecl->vbases_end();
8917 Base != BaseEnd; ++Base) {
8918 CXXRecordDecl *BaseClassDecl
8919 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8920 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008921 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008922 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008923 }
8924
8925 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8926 FieldEnd = ClassDecl->field_end();
8927 Field != FieldEnd;
8928 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008929 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008930 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008931 if (CXXMethodDecl *MoveAssign =
8932 LookupMovingAssignment(FieldClassDecl,
8933 FieldType.getCVRQualifiers(),
8934 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008935 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008936 }
8937 }
8938
8939 return ExceptSpec;
8940}
8941
Richard Smith1c931be2012-04-02 18:40:40 +00008942/// Determine whether the class type has any direct or indirect virtual base
8943/// classes which have a non-trivial move assignment operator.
8944static bool
8945hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8946 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8947 BaseEnd = ClassDecl->vbases_end();
8948 Base != BaseEnd; ++Base) {
8949 CXXRecordDecl *BaseClass =
8950 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8951
8952 // Try to declare the move assignment. If it would be deleted, then the
8953 // class does not have a non-trivial move assignment.
8954 if (BaseClass->needsImplicitMoveAssignment())
8955 S.DeclareImplicitMoveAssignment(BaseClass);
8956
Richard Smith426391c2012-11-16 00:53:38 +00008957 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008958 return true;
8959 }
8960
8961 return false;
8962}
8963
8964/// Determine whether the given type either has a move constructor or is
8965/// trivially copyable.
8966static bool
8967hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8968 Type = S.Context.getBaseElementType(Type);
8969
8970 // FIXME: Technically, non-trivially-copyable non-class types, such as
8971 // reference types, are supposed to return false here, but that appears
8972 // to be a standard defect.
8973 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008974 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008975 return true;
8976
8977 if (Type.isTriviallyCopyableType(S.Context))
8978 return true;
8979
8980 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008981 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8982 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008983 if (ClassDecl->needsImplicitMoveConstructor())
8984 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008985 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008986 }
8987
Richard Smithe5411b72012-12-01 02:35:44 +00008988 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8989 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008990 if (ClassDecl->needsImplicitMoveAssignment())
8991 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008992 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008993}
8994
8995/// Determine whether all non-static data members and direct or virtual bases
8996/// of class \p ClassDecl have either a move operation, or are trivially
8997/// copyable.
8998static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8999 bool IsConstructor) {
9000 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9001 BaseEnd = ClassDecl->bases_end();
9002 Base != BaseEnd; ++Base) {
9003 if (Base->isVirtual())
9004 continue;
9005
9006 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9007 return false;
9008 }
9009
9010 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9011 BaseEnd = ClassDecl->vbases_end();
9012 Base != BaseEnd; ++Base) {
9013 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9014 return false;
9015 }
9016
9017 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9018 FieldEnd = ClassDecl->field_end();
9019 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009020 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009021 return false;
9022 }
9023
9024 return true;
9025}
9026
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009027CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009028 // C++11 [class.copy]p20:
9029 // If the definition of a class X does not explicitly declare a move
9030 // assignment operator, one will be implicitly declared as defaulted
9031 // if and only if:
9032 //
9033 // - [first 4 bullets]
9034 assert(ClassDecl->needsImplicitMoveAssignment());
9035
Richard Smithafb49182012-11-29 01:34:07 +00009036 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9037 if (DSM.isAlreadyBeingDeclared())
9038 return 0;
9039
Richard Smith1c931be2012-04-02 18:40:40 +00009040 // [Checked after we build the declaration]
9041 // - the move assignment operator would not be implicitly defined as
9042 // deleted,
9043
9044 // [DR1402]:
9045 // - X has no direct or indirect virtual base class with a non-trivial
9046 // move assignment operator, and
9047 // - each of X's non-static data members and direct or virtual base classes
9048 // has a type that either has a move assignment operator or is trivially
9049 // copyable.
9050 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9051 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9052 ClassDecl->setFailedImplicitMoveAssignment();
9053 return 0;
9054 }
9055
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009056 // Note: The following rules are largely analoguous to the move
9057 // constructor rules.
9058
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009059 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9060 QualType RetType = Context.getLValueReferenceType(ArgType);
9061 ArgType = Context.getRValueReferenceType(ArgType);
9062
9063 // An implicitly-declared move assignment operator is an inline public
9064 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009065 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9066 SourceLocation ClassLoc = ClassDecl->getLocation();
9067 DeclarationNameInfo NameInfo(Name, ClassLoc);
9068 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00009069 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009070 /*TInfo=*/0,
9071 /*StorageClass=*/SC_None,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009072 /*isInline=*/true,
9073 /*isConstexpr=*/false,
9074 SourceLocation());
9075 MoveAssignment->setAccess(AS_public);
9076 MoveAssignment->setDefaulted();
9077 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009078
Richard Smithb9d0b762012-07-27 04:22:15 +00009079 // Build an exception specification pointing back at this member.
9080 FunctionProtoType::ExtProtoInfo EPI;
9081 EPI.ExceptionSpecType = EST_Unevaluated;
9082 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009083 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009084
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009085 // Add the parameter to the operator.
9086 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9087 ClassLoc, ClassLoc, /*Id=*/0,
9088 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009089 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009090 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009091
Richard Smithbc2a35d2012-12-08 08:32:28 +00009092 AddOverriddenMethods(ClassDecl, MoveAssignment);
9093
9094 MoveAssignment->setTrivial(
9095 ClassDecl->needsOverloadResolutionForMoveAssignment()
9096 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9097 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009098
9099 // C++0x [class.copy]p9:
9100 // If the definition of a class X does not explicitly declare a move
9101 // assignment operator, one will be implicitly declared as defaulted if and
9102 // only if:
9103 // [...]
9104 // - the move assignment operator would not be implicitly defined as
9105 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009106 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009107 // Cache this result so that we don't try to generate this over and over
9108 // on every lookup, leaking memory and wasting time.
9109 ClassDecl->setFailedImplicitMoveAssignment();
9110 return 0;
9111 }
9112
Richard Smithbc2a35d2012-12-08 08:32:28 +00009113 // Note that we have added this copy-assignment operator.
9114 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9115
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009116 if (Scope *S = getScopeForContext(ClassDecl))
9117 PushOnScopeChains(MoveAssignment, S, false);
9118 ClassDecl->addDecl(MoveAssignment);
9119
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009120 return MoveAssignment;
9121}
9122
9123void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9124 CXXMethodDecl *MoveAssignOperator) {
9125 assert((MoveAssignOperator->isDefaulted() &&
9126 MoveAssignOperator->isOverloadedOperator() &&
9127 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009128 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9129 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009130 "DefineImplicitMoveAssignment called for wrong function");
9131
9132 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9133
9134 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9135 MoveAssignOperator->setInvalidDecl();
9136 return;
9137 }
9138
9139 MoveAssignOperator->setUsed();
9140
Eli Friedman9a14db32012-10-18 20:14:08 +00009141 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009142 DiagnosticErrorTrap Trap(Diags);
9143
9144 // C++0x [class.copy]p28:
9145 // The implicitly-defined or move assignment operator for a non-union class
9146 // X performs memberwise move assignment of its subobjects. The direct base
9147 // classes of X are assigned first, in the order of their declaration in the
9148 // base-specifier-list, and then the immediate non-static data members of X
9149 // are assigned, in the order in which they were declared in the class
9150 // definition.
9151
9152 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009153 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009154
9155 // The parameter for the "other" object, which we are move from.
9156 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9157 QualType OtherRefType = Other->getType()->
9158 getAs<RValueReferenceType>()->getPointeeType();
9159 assert(OtherRefType.getQualifiers() == 0 &&
9160 "Bad argument type of defaulted move assignment");
9161
9162 // Our location for everything implicitly-generated.
9163 SourceLocation Loc = MoveAssignOperator->getLocation();
9164
9165 // Construct a reference to the "other" object. We'll be using this
9166 // throughout the generated ASTs.
9167 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9168 assert(OtherRef && "Reference to parameter cannot fail!");
9169 // Cast to rvalue.
9170 OtherRef = CastForMoving(*this, OtherRef);
9171
9172 // Construct the "this" pointer. We'll be using this throughout the generated
9173 // ASTs.
9174 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9175 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009176
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009177 // Assign base classes.
9178 bool Invalid = false;
9179 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9180 E = ClassDecl->bases_end(); Base != E; ++Base) {
9181 // Form the assignment:
9182 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9183 QualType BaseType = Base->getType().getUnqualifiedType();
9184 if (!BaseType->isRecordType()) {
9185 Invalid = true;
9186 continue;
9187 }
9188
9189 CXXCastPath BasePath;
9190 BasePath.push_back(Base);
9191
9192 // Construct the "from" expression, which is an implicit cast to the
9193 // appropriately-qualified base type.
9194 Expr *From = OtherRef;
9195 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009196 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009197
9198 // Dereference "this".
9199 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9200
9201 // Implicitly cast "this" to the appropriately-qualified base type.
9202 To = ImpCastExprToType(To.take(),
9203 Context.getCVRQualifiedType(BaseType,
9204 MoveAssignOperator->getTypeQualifiers()),
9205 CK_UncheckedDerivedToBase,
9206 VK_LValue, &BasePath);
9207
9208 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009209 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009210 To.get(), From,
9211 /*CopyingBaseSubobject=*/true,
9212 /*Copying=*/false);
9213 if (Move.isInvalid()) {
9214 Diag(CurrentLocation, diag::note_member_synthesized_at)
9215 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9216 MoveAssignOperator->setInvalidDecl();
9217 return;
9218 }
9219
9220 // Success! Record the move.
9221 Statements.push_back(Move.takeAs<Expr>());
9222 }
9223
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009224 // Assign non-static members.
9225 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9226 FieldEnd = ClassDecl->field_end();
9227 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009228 if (Field->isUnnamedBitfield())
9229 continue;
9230
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009231 // Check for members of reference type; we can't move those.
9232 if (Field->getType()->isReferenceType()) {
9233 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9234 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9235 Diag(Field->getLocation(), diag::note_declared_at);
9236 Diag(CurrentLocation, diag::note_member_synthesized_at)
9237 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9238 Invalid = true;
9239 continue;
9240 }
9241
9242 // Check for members of const-qualified, non-class type.
9243 QualType BaseType = Context.getBaseElementType(Field->getType());
9244 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9245 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9246 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9247 Diag(Field->getLocation(), diag::note_declared_at);
9248 Diag(CurrentLocation, diag::note_member_synthesized_at)
9249 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9250 Invalid = true;
9251 continue;
9252 }
9253
9254 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009255 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9256 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009257
9258 QualType FieldType = Field->getType().getNonReferenceType();
9259 if (FieldType->isIncompleteArrayType()) {
9260 assert(ClassDecl->hasFlexibleArrayMember() &&
9261 "Incomplete array type is not valid");
9262 continue;
9263 }
9264
9265 // Build references to the field in the object we're copying from and to.
9266 CXXScopeSpec SS; // Intentionally empty
9267 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9268 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009269 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009270 MemberLookup.resolveKind();
9271 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9272 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009273 SS, SourceLocation(), 0,
9274 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009275 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9276 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009277 SS, SourceLocation(), 0,
9278 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009279 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9280 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9281
9282 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9283 "Member reference with rvalue base must be rvalue except for reference "
9284 "members, which aren't allowed for move assignment.");
9285
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009286 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009287 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009288 To.get(), From.get(),
9289 /*CopyingBaseSubobject=*/false,
9290 /*Copying=*/false);
9291 if (Move.isInvalid()) {
9292 Diag(CurrentLocation, diag::note_member_synthesized_at)
9293 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9294 MoveAssignOperator->setInvalidDecl();
9295 return;
9296 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009297
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009298 // Success! Record the copy.
9299 Statements.push_back(Move.takeAs<Stmt>());
9300 }
9301
9302 if (!Invalid) {
9303 // Add a "return *this;"
9304 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9305
9306 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9307 if (Return.isInvalid())
9308 Invalid = true;
9309 else {
9310 Statements.push_back(Return.takeAs<Stmt>());
9311
9312 if (Trap.hasErrorOccurred()) {
9313 Diag(CurrentLocation, diag::note_member_synthesized_at)
9314 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9315 Invalid = true;
9316 }
9317 }
9318 }
9319
9320 if (Invalid) {
9321 MoveAssignOperator->setInvalidDecl();
9322 return;
9323 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009324
9325 StmtResult Body;
9326 {
9327 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009328 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009329 /*isStmtExpr=*/false);
9330 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9331 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009332 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9333
9334 if (ASTMutationListener *L = getASTMutationListener()) {
9335 L->CompletedImplicitDefinition(MoveAssignOperator);
9336 }
9337}
9338
Richard Smithb9d0b762012-07-27 04:22:15 +00009339Sema::ImplicitExceptionSpecification
9340Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9341 CXXRecordDecl *ClassDecl = MD->getParent();
9342
9343 ImplicitExceptionSpecification ExceptSpec(*this);
9344 if (ClassDecl->isInvalidDecl())
9345 return ExceptSpec;
9346
9347 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9348 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9349 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9350
Douglas Gregor0d405db2010-07-01 20:59:04 +00009351 // C++ [except.spec]p14:
9352 // An implicitly declared special member function (Clause 12) shall have an
9353 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009354 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9355 BaseEnd = ClassDecl->bases_end();
9356 Base != BaseEnd;
9357 ++Base) {
9358 // Virtual bases are handled below.
9359 if (Base->isVirtual())
9360 continue;
9361
Douglas Gregor22584312010-07-02 23:41:54 +00009362 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009363 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009364 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009365 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009366 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009367 }
9368 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9369 BaseEnd = ClassDecl->vbases_end();
9370 Base != BaseEnd;
9371 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009372 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009373 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009374 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009375 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009376 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009377 }
9378 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9379 FieldEnd = ClassDecl->field_end();
9380 Field != FieldEnd;
9381 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009382 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009383 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9384 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009385 LookupCopyingConstructor(FieldClassDecl,
9386 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009387 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009388 }
9389 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009390
Richard Smithb9d0b762012-07-27 04:22:15 +00009391 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009392}
9393
9394CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9395 CXXRecordDecl *ClassDecl) {
9396 // C++ [class.copy]p4:
9397 // If the class definition does not explicitly declare a copy
9398 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009399 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009400
Richard Smithafb49182012-11-29 01:34:07 +00009401 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9402 if (DSM.isAlreadyBeingDeclared())
9403 return 0;
9404
Sean Hunt49634cf2011-05-13 06:10:58 +00009405 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9406 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009407 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009408 if (Const)
9409 ArgType = ArgType.withConst();
9410 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009411
Richard Smith7756afa2012-06-10 05:43:50 +00009412 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9413 CXXCopyConstructor,
9414 Const);
9415
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009416 DeclarationName Name
9417 = Context.DeclarationNames.getCXXConstructorName(
9418 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009419 SourceLocation ClassLoc = ClassDecl->getLocation();
9420 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009421
9422 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009423 // member of its class.
9424 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009425 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009426 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009427 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009428 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009429 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009430
Richard Smithb9d0b762012-07-27 04:22:15 +00009431 // Build an exception specification pointing back at this member.
9432 FunctionProtoType::ExtProtoInfo EPI;
9433 EPI.ExceptionSpecType = EST_Unevaluated;
9434 EPI.ExceptionSpecDecl = CopyConstructor;
9435 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009436 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009437
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009438 // Add the parameter to the constructor.
9439 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009440 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009441 /*IdentifierInfo=*/0,
9442 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009443 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009444 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009445
Richard Smithbc2a35d2012-12-08 08:32:28 +00009446 CopyConstructor->setTrivial(
9447 ClassDecl->needsOverloadResolutionForCopyConstructor()
9448 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9449 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009450
Nico Weberafcc96a2012-01-23 03:19:29 +00009451 // C++11 [class.copy]p8:
9452 // ... If the class definition does not explicitly declare a copy
9453 // constructor, there is no user-declared move constructor, and there is no
9454 // user-declared move assignment operator, a copy constructor is implicitly
9455 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009456 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009457 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009458
Richard Smithbc2a35d2012-12-08 08:32:28 +00009459 // Note that we have declared this constructor.
9460 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9461
9462 if (Scope *S = getScopeForContext(ClassDecl))
9463 PushOnScopeChains(CopyConstructor, S, false);
9464 ClassDecl->addDecl(CopyConstructor);
9465
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009466 return CopyConstructor;
9467}
9468
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009469void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009470 CXXConstructorDecl *CopyConstructor) {
9471 assert((CopyConstructor->isDefaulted() &&
9472 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009473 !CopyConstructor->doesThisDeclarationHaveABody() &&
9474 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009475 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009476
Anders Carlsson63010a72010-04-23 16:24:12 +00009477 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009478 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009479
Eli Friedman9a14db32012-10-18 20:14:08 +00009480 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009481 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009482
David Blaikie93c86172013-01-17 05:26:25 +00009483 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009484 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009485 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009486 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009487 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009488 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009489 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009490 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9491 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009492 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009493 /*isStmtExpr=*/false)
9494 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009495 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009496 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009497
9498 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009499 if (ASTMutationListener *L = getASTMutationListener()) {
9500 L->CompletedImplicitDefinition(CopyConstructor);
9501 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009502}
9503
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009504Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009505Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9506 CXXRecordDecl *ClassDecl = MD->getParent();
9507
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009508 // C++ [except.spec]p14:
9509 // An implicitly declared special member function (Clause 12) shall have an
9510 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009511 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009512 if (ClassDecl->isInvalidDecl())
9513 return ExceptSpec;
9514
9515 // Direct base-class constructors.
9516 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9517 BEnd = ClassDecl->bases_end();
9518 B != BEnd; ++B) {
9519 if (B->isVirtual()) // Handled below.
9520 continue;
9521
9522 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9523 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009524 CXXConstructorDecl *Constructor =
9525 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009526 // If this is a deleted function, add it anyway. This might be conformant
9527 // with the standard. This might not. I'm not sure. It might not matter.
9528 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009529 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009530 }
9531 }
9532
9533 // Virtual base-class constructors.
9534 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9535 BEnd = ClassDecl->vbases_end();
9536 B != BEnd; ++B) {
9537 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9538 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009539 CXXConstructorDecl *Constructor =
9540 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009541 // If this is a deleted function, add it anyway. This might be conformant
9542 // with the standard. This might not. I'm not sure. It might not matter.
9543 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009544 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009545 }
9546 }
9547
9548 // Field constructors.
9549 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9550 FEnd = ClassDecl->field_end();
9551 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009552 QualType FieldType = Context.getBaseElementType(F->getType());
9553 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9554 CXXConstructorDecl *Constructor =
9555 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009556 // If this is a deleted function, add it anyway. This might be conformant
9557 // with the standard. This might not. I'm not sure. It might not matter.
9558 // In particular, the problem is that this function never gets called. It
9559 // might just be ill-formed because this function attempts to refer to
9560 // a deleted function here.
9561 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009562 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009563 }
9564 }
9565
9566 return ExceptSpec;
9567}
9568
9569CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9570 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009571 // C++11 [class.copy]p9:
9572 // If the definition of a class X does not explicitly declare a move
9573 // constructor, one will be implicitly declared as defaulted if and only if:
9574 //
9575 // - [first 4 bullets]
9576 assert(ClassDecl->needsImplicitMoveConstructor());
9577
Richard Smithafb49182012-11-29 01:34:07 +00009578 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9579 if (DSM.isAlreadyBeingDeclared())
9580 return 0;
9581
Richard Smith1c931be2012-04-02 18:40:40 +00009582 // [Checked after we build the declaration]
9583 // - the move assignment operator would not be implicitly defined as
9584 // deleted,
9585
9586 // [DR1402]:
9587 // - each of X's non-static data members and direct or virtual base classes
9588 // has a type that either has a move constructor or is trivially copyable.
9589 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9590 ClassDecl->setFailedImplicitMoveConstructor();
9591 return 0;
9592 }
9593
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009594 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9595 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009596
Richard Smith7756afa2012-06-10 05:43:50 +00009597 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9598 CXXMoveConstructor,
9599 false);
9600
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009601 DeclarationName Name
9602 = Context.DeclarationNames.getCXXConstructorName(
9603 Context.getCanonicalType(ClassType));
9604 SourceLocation ClassLoc = ClassDecl->getLocation();
9605 DeclarationNameInfo NameInfo(Name, ClassLoc);
9606
9607 // C++0x [class.copy]p11:
9608 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009609 // member of its class.
9610 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009611 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009612 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009613 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009614 MoveConstructor->setAccess(AS_public);
9615 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009616
Richard Smithb9d0b762012-07-27 04:22:15 +00009617 // Build an exception specification pointing back at this member.
9618 FunctionProtoType::ExtProtoInfo EPI;
9619 EPI.ExceptionSpecType = EST_Unevaluated;
9620 EPI.ExceptionSpecDecl = MoveConstructor;
9621 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009622 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009623
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009624 // Add the parameter to the constructor.
9625 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9626 ClassLoc, ClassLoc,
9627 /*IdentifierInfo=*/0,
9628 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009629 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009630 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009631
Richard Smithbc2a35d2012-12-08 08:32:28 +00009632 MoveConstructor->setTrivial(
9633 ClassDecl->needsOverloadResolutionForMoveConstructor()
9634 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9635 : ClassDecl->hasTrivialMoveConstructor());
9636
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009637 // C++0x [class.copy]p9:
9638 // If the definition of a class X does not explicitly declare a move
9639 // constructor, one will be implicitly declared as defaulted if and only if:
9640 // [...]
9641 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009642 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009643 // Cache this result so that we don't try to generate this over and over
9644 // on every lookup, leaking memory and wasting time.
9645 ClassDecl->setFailedImplicitMoveConstructor();
9646 return 0;
9647 }
9648
9649 // Note that we have declared this constructor.
9650 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9651
9652 if (Scope *S = getScopeForContext(ClassDecl))
9653 PushOnScopeChains(MoveConstructor, S, false);
9654 ClassDecl->addDecl(MoveConstructor);
9655
9656 return MoveConstructor;
9657}
9658
9659void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9660 CXXConstructorDecl *MoveConstructor) {
9661 assert((MoveConstructor->isDefaulted() &&
9662 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009663 !MoveConstructor->doesThisDeclarationHaveABody() &&
9664 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009665 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9666
9667 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9668 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9669
Eli Friedman9a14db32012-10-18 20:14:08 +00009670 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009671 DiagnosticErrorTrap Trap(Diags);
9672
David Blaikie93c86172013-01-17 05:26:25 +00009673 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009674 Trap.hasErrorOccurred()) {
9675 Diag(CurrentLocation, diag::note_member_synthesized_at)
9676 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9677 MoveConstructor->setInvalidDecl();
9678 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009679 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009680 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9681 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009682 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009683 /*isStmtExpr=*/false)
9684 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009685 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009686 }
9687
9688 MoveConstructor->setUsed();
9689
9690 if (ASTMutationListener *L = getASTMutationListener()) {
9691 L->CompletedImplicitDefinition(MoveConstructor);
9692 }
9693}
9694
Douglas Gregore4e68d42012-02-15 19:33:52 +00009695bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9696 return FD->isDeleted() &&
9697 (FD->isDefaulted() || FD->isImplicit()) &&
9698 isa<CXXMethodDecl>(FD);
9699}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009700
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009701/// \brief Mark the call operator of the given lambda closure type as "used".
9702static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9703 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009704 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009705 Lambda->lookup(
9706 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009707 CallOperator->setReferenced();
9708 CallOperator->setUsed();
9709}
9710
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009711void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9712 SourceLocation CurrentLocation,
9713 CXXConversionDecl *Conv)
9714{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009715 CXXRecordDecl *Lambda = Conv->getParent();
9716
9717 // Make sure that the lambda call operator is marked used.
9718 markLambdaCallOperatorUsed(*this, Lambda);
9719
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009720 Conv->setUsed();
9721
Eli Friedman9a14db32012-10-18 20:14:08 +00009722 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009723 DiagnosticErrorTrap Trap(Diags);
9724
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009725 // Return the address of the __invoke function.
9726 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9727 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009728 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009729 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9730 VK_LValue, Conv->getLocation()).take();
9731 assert(FunctionRef && "Can't refer to __invoke function?");
9732 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009733 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009734 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009735 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009736
9737 // Fill in the __invoke function with a dummy implementation. IR generation
9738 // will fill in the actual details.
9739 Invoke->setUsed();
9740 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009741 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009742
9743 if (ASTMutationListener *L = getASTMutationListener()) {
9744 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009745 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009746 }
9747}
9748
9749void Sema::DefineImplicitLambdaToBlockPointerConversion(
9750 SourceLocation CurrentLocation,
9751 CXXConversionDecl *Conv)
9752{
9753 Conv->setUsed();
9754
Eli Friedman9a14db32012-10-18 20:14:08 +00009755 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009756 DiagnosticErrorTrap Trap(Diags);
9757
Douglas Gregorac1303e2012-02-22 05:02:47 +00009758 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009759 Expr *This = ActOnCXXThis(CurrentLocation).take();
9760 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009761
Eli Friedman23f02672012-03-01 04:01:32 +00009762 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9763 Conv->getLocation(),
9764 Conv, DerefThis);
9765
9766 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9767 // behavior. Note that only the general conversion function does this
9768 // (since it's unusable otherwise); in the case where we inline the
9769 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009770 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009771 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9772 CK_CopyAndAutoreleaseBlockObject,
9773 BuildBlock.get(), 0, VK_RValue);
9774
9775 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009776 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009777 Conv->setInvalidDecl();
9778 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009779 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009780
Douglas Gregorac1303e2012-02-22 05:02:47 +00009781 // Create the return statement that returns the block from the conversion
9782 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009783 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009784 if (Return.isInvalid()) {
9785 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9786 Conv->setInvalidDecl();
9787 return;
9788 }
9789
9790 // Set the body of the conversion function.
9791 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009792 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009793 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009794 Conv->getLocation()));
9795
Douglas Gregorac1303e2012-02-22 05:02:47 +00009796 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009797 if (ASTMutationListener *L = getASTMutationListener()) {
9798 L->CompletedImplicitDefinition(Conv);
9799 }
9800}
9801
Douglas Gregorf52757d2012-03-10 06:53:13 +00009802/// \brief Determine whether the given list arguments contains exactly one
9803/// "real" (non-default) argument.
9804static bool hasOneRealArgument(MultiExprArg Args) {
9805 switch (Args.size()) {
9806 case 0:
9807 return false;
9808
9809 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009810 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009811 return false;
9812
9813 // fall through
9814 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009815 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009816 }
9817
9818 return false;
9819}
9820
John McCall60d7b3a2010-08-24 06:29:42 +00009821ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009822Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009823 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009824 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009825 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009826 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009827 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009828 unsigned ConstructKind,
9829 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009830 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009831
Douglas Gregor2f599792010-04-02 18:24:57 +00009832 // C++0x [class.copy]p34:
9833 // When certain criteria are met, an implementation is allowed to
9834 // omit the copy/move construction of a class object, even if the
9835 // copy/move constructor and/or destructor for the object have
9836 // side effects. [...]
9837 // - when a temporary class object that has not been bound to a
9838 // reference (12.2) would be copied/moved to a class object
9839 // with the same cv-unqualified type, the copy/move operation
9840 // can be omitted by constructing the temporary object
9841 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009842 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009843 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009844 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009845 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009846 }
Mike Stump1eb44332009-09-09 15:08:12 +00009847
9848 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009849 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009850 IsListInitialization, RequiresZeroInit,
9851 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009852}
9853
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009854/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9855/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009856ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009857Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9858 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009859 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009860 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009861 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009862 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009863 unsigned ConstructKind,
9864 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009865 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009866 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009867 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +00009868 HadMultipleCandidates,
9869 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009870 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9871 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009872}
9873
John McCall68c6c9a2010-02-02 09:10:11 +00009874void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009875 if (VD->isInvalidDecl()) return;
9876
John McCall68c6c9a2010-02-02 09:10:11 +00009877 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009878 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009879 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009880 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009881
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009882 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009883 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009884 CheckDestructorAccess(VD->getLocation(), Destructor,
9885 PDiag(diag::err_access_dtor_var)
9886 << VD->getDeclName()
9887 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009888 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009889
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009890 if (!VD->hasGlobalStorage()) return;
9891
9892 // Emit warning for non-trivial dtor in global scope (a real global,
9893 // class-static, function-static).
9894 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9895
9896 // TODO: this should be re-enabled for static locals by !CXAAtExit
9897 if (!VD->isStaticLocal())
9898 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009899}
9900
Douglas Gregor39da0b82009-09-09 23:08:42 +00009901/// \brief Given a constructor and the set of arguments provided for the
9902/// constructor, convert the arguments and add any required default arguments
9903/// to form a proper call to this constructor.
9904///
9905/// \returns true if an error occurred, false otherwise.
9906bool
9907Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9908 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009909 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009910 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009911 bool AllowExplicit,
9912 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009913 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9914 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009915 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009916
9917 const FunctionProtoType *Proto
9918 = Constructor->getType()->getAs<FunctionProtoType>();
9919 assert(Proto && "Constructor without a prototype?");
9920 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009921
9922 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009923 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009924 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009925 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009926 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009927
9928 VariadicCallType CallType =
9929 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009930 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009931 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9932 Proto, 0, Args, NumArgs, AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009933 CallType, AllowExplicit,
9934 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009935 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009936
9937 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9938
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00009939 CheckConstructorCall(Constructor,
9940 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9941 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +00009942 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009943
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009944 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009945}
9946
Anders Carlsson20d45d22009-12-12 00:32:00 +00009947static inline bool
9948CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9949 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009950 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009951 if (isa<NamespaceDecl>(DC)) {
9952 return SemaRef.Diag(FnDecl->getLocation(),
9953 diag::err_operator_new_delete_declared_in_namespace)
9954 << FnDecl->getDeclName();
9955 }
9956
9957 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009958 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009959 return SemaRef.Diag(FnDecl->getLocation(),
9960 diag::err_operator_new_delete_declared_static)
9961 << FnDecl->getDeclName();
9962 }
9963
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009964 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009965}
9966
Anders Carlsson156c78e2009-12-13 17:53:43 +00009967static inline bool
9968CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9969 CanQualType ExpectedResultType,
9970 CanQualType ExpectedFirstParamType,
9971 unsigned DependentParamTypeDiag,
9972 unsigned InvalidParamTypeDiag) {
9973 QualType ResultType =
9974 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9975
9976 // Check that the result type is not dependent.
9977 if (ResultType->isDependentType())
9978 return SemaRef.Diag(FnDecl->getLocation(),
9979 diag::err_operator_new_delete_dependent_result_type)
9980 << FnDecl->getDeclName() << ExpectedResultType;
9981
9982 // Check that the result type is what we expect.
9983 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9984 return SemaRef.Diag(FnDecl->getLocation(),
9985 diag::err_operator_new_delete_invalid_result_type)
9986 << FnDecl->getDeclName() << ExpectedResultType;
9987
9988 // A function template must have at least 2 parameters.
9989 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9990 return SemaRef.Diag(FnDecl->getLocation(),
9991 diag::err_operator_new_delete_template_too_few_parameters)
9992 << FnDecl->getDeclName();
9993
9994 // The function decl must have at least 1 parameter.
9995 if (FnDecl->getNumParams() == 0)
9996 return SemaRef.Diag(FnDecl->getLocation(),
9997 diag::err_operator_new_delete_too_few_parameters)
9998 << FnDecl->getDeclName();
9999
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010000 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010001 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10002 if (FirstParamType->isDependentType())
10003 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10004 << FnDecl->getDeclName() << ExpectedFirstParamType;
10005
10006 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010007 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010008 ExpectedFirstParamType)
10009 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10010 << FnDecl->getDeclName() << ExpectedFirstParamType;
10011
10012 return false;
10013}
10014
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010015static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010016CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010017 // C++ [basic.stc.dynamic.allocation]p1:
10018 // A program is ill-formed if an allocation function is declared in a
10019 // namespace scope other than global scope or declared static in global
10020 // scope.
10021 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10022 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010023
10024 CanQualType SizeTy =
10025 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10026
10027 // C++ [basic.stc.dynamic.allocation]p1:
10028 // The return type shall be void*. The first parameter shall have type
10029 // std::size_t.
10030 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10031 SizeTy,
10032 diag::err_operator_new_dependent_param_type,
10033 diag::err_operator_new_param_type))
10034 return true;
10035
10036 // C++ [basic.stc.dynamic.allocation]p1:
10037 // The first parameter shall not have an associated default argument.
10038 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010039 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010040 diag::err_operator_new_default_arg)
10041 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10042
10043 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010044}
10045
10046static bool
Richard Smith444d3842012-10-20 08:26:51 +000010047CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010048 // C++ [basic.stc.dynamic.deallocation]p1:
10049 // A program is ill-formed if deallocation functions are declared in a
10050 // namespace scope other than global scope or declared static in global
10051 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010052 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10053 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010054
10055 // C++ [basic.stc.dynamic.deallocation]p2:
10056 // Each deallocation function shall return void and its first parameter
10057 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010058 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10059 SemaRef.Context.VoidPtrTy,
10060 diag::err_operator_delete_dependent_param_type,
10061 diag::err_operator_delete_param_type))
10062 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010063
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010064 return false;
10065}
10066
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010067/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10068/// of this overloaded operator is well-formed. If so, returns false;
10069/// otherwise, emits appropriate diagnostics and returns true.
10070bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010071 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010072 "Expected an overloaded operator declaration");
10073
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010074 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10075
Mike Stump1eb44332009-09-09 15:08:12 +000010076 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010077 // The allocation and deallocation functions, operator new,
10078 // operator new[], operator delete and operator delete[], are
10079 // described completely in 3.7.3. The attributes and restrictions
10080 // found in the rest of this subclause do not apply to them unless
10081 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010082 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010083 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010084
Anders Carlssona3ccda52009-12-12 00:26:23 +000010085 if (Op == OO_New || Op == OO_Array_New)
10086 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010087
10088 // C++ [over.oper]p6:
10089 // An operator function shall either be a non-static member
10090 // function or be a non-member function and have at least one
10091 // parameter whose type is a class, a reference to a class, an
10092 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010093 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10094 if (MethodDecl->isStatic())
10095 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010096 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010097 } else {
10098 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010099 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10100 ParamEnd = FnDecl->param_end();
10101 Param != ParamEnd; ++Param) {
10102 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010103 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10104 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010105 ClassOrEnumParam = true;
10106 break;
10107 }
10108 }
10109
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010110 if (!ClassOrEnumParam)
10111 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010112 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010113 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010114 }
10115
10116 // C++ [over.oper]p8:
10117 // An operator function cannot have default arguments (8.3.6),
10118 // except where explicitly stated below.
10119 //
Mike Stump1eb44332009-09-09 15:08:12 +000010120 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010121 // (C++ [over.call]p1).
10122 if (Op != OO_Call) {
10123 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10124 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010125 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010126 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010127 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010128 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010129 }
10130 }
10131
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010132 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10133 { false, false, false }
10134#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10135 , { Unary, Binary, MemberOnly }
10136#include "clang/Basic/OperatorKinds.def"
10137 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010138
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010139 bool CanBeUnaryOperator = OperatorUses[Op][0];
10140 bool CanBeBinaryOperator = OperatorUses[Op][1];
10141 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010142
10143 // C++ [over.oper]p8:
10144 // [...] Operator functions cannot have more or fewer parameters
10145 // than the number required for the corresponding operator, as
10146 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010147 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010148 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010149 if (Op != OO_Call &&
10150 ((NumParams == 1 && !CanBeUnaryOperator) ||
10151 (NumParams == 2 && !CanBeBinaryOperator) ||
10152 (NumParams < 1) || (NumParams > 2))) {
10153 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010154 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010155 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010156 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010157 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010158 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010159 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010160 assert(CanBeBinaryOperator &&
10161 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010162 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010163 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010164
Chris Lattner416e46f2008-11-21 07:57:12 +000010165 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010166 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010167 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010168
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010169 // Overloaded operators other than operator() cannot be variadic.
10170 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010171 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010172 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010173 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010174 }
10175
10176 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010177 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10178 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010179 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010180 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010181 }
10182
10183 // C++ [over.inc]p1:
10184 // The user-defined function called operator++ implements the
10185 // prefix and postfix ++ operator. If this function is a member
10186 // function with no parameters, or a non-member function with one
10187 // parameter of class or enumeration type, it defines the prefix
10188 // increment operator ++ for objects of that type. If the function
10189 // is a member function with one parameter (which shall be of type
10190 // int) or a non-member function with two parameters (the second
10191 // of which shall be of type int), it defines the postfix
10192 // increment operator ++ for objects of that type.
10193 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10194 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10195 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010196 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010197 ParamIsInt = BT->getKind() == BuiltinType::Int;
10198
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010199 if (!ParamIsInt)
10200 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010201 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010202 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010203 }
10204
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010205 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010206}
Chris Lattner5a003a42008-12-17 07:09:26 +000010207
Sean Hunta6c058d2010-01-13 09:01:02 +000010208/// CheckLiteralOperatorDeclaration - Check whether the declaration
10209/// of this literal operator function is well-formed. If so, returns
10210/// false; otherwise, emits appropriate diagnostics and returns true.
10211bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010212 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010213 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10214 << FnDecl->getDeclName();
10215 return true;
10216 }
10217
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010218 if (FnDecl->isExternC()) {
10219 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10220 return true;
10221 }
10222
Sean Hunta6c058d2010-01-13 09:01:02 +000010223 bool Valid = false;
10224
Richard Smith36f5cfe2012-03-09 08:00:36 +000010225 // This might be the definition of a literal operator template.
10226 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10227 // This might be a specialization of a literal operator template.
10228 if (!TpDecl)
10229 TpDecl = FnDecl->getPrimaryTemplate();
10230
Sean Hunt216c2782010-04-07 23:11:06 +000010231 // template <char...> type operator "" name() is the only valid template
10232 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010233 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010234 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010235 // Must have only one template parameter
10236 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10237 if (Params->size() == 1) {
10238 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010239 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010240
Sean Hunt216c2782010-04-07 23:11:06 +000010241 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010242 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10243 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10244 Valid = true;
10245 }
10246 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010247 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010248 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010249 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10250
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010251 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010252
Sean Hunt30019c02010-04-07 22:57:35 +000010253 // unsigned long long int, long double, and any character type are allowed
10254 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010255 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10256 Context.hasSameType(T, Context.LongDoubleTy) ||
10257 Context.hasSameType(T, Context.CharTy) ||
10258 Context.hasSameType(T, Context.WCharTy) ||
10259 Context.hasSameType(T, Context.Char16Ty) ||
10260 Context.hasSameType(T, Context.Char32Ty)) {
10261 if (++Param == FnDecl->param_end())
10262 Valid = true;
10263 goto FinishedParams;
10264 }
10265
Sean Hunt30019c02010-04-07 22:57:35 +000010266 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010267 const PointerType *PT = T->getAs<PointerType>();
10268 if (!PT)
10269 goto FinishedParams;
10270 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010271 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010272 goto FinishedParams;
10273 T = T.getUnqualifiedType();
10274
10275 // Move on to the second parameter;
10276 ++Param;
10277
10278 // If there is no second parameter, the first must be a const char *
10279 if (Param == FnDecl->param_end()) {
10280 if (Context.hasSameType(T, Context.CharTy))
10281 Valid = true;
10282 goto FinishedParams;
10283 }
10284
10285 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10286 // are allowed as the first parameter to a two-parameter function
10287 if (!(Context.hasSameType(T, Context.CharTy) ||
10288 Context.hasSameType(T, Context.WCharTy) ||
10289 Context.hasSameType(T, Context.Char16Ty) ||
10290 Context.hasSameType(T, Context.Char32Ty)))
10291 goto FinishedParams;
10292
10293 // The second and final parameter must be an std::size_t
10294 T = (*Param)->getType().getUnqualifiedType();
10295 if (Context.hasSameType(T, Context.getSizeType()) &&
10296 ++Param == FnDecl->param_end())
10297 Valid = true;
10298 }
10299
10300 // FIXME: This diagnostic is absolutely terrible.
10301FinishedParams:
10302 if (!Valid) {
10303 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10304 << FnDecl->getDeclName();
10305 return true;
10306 }
10307
Richard Smitha9e88b22012-03-09 08:16:22 +000010308 // A parameter-declaration-clause containing a default argument is not
10309 // equivalent to any of the permitted forms.
10310 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10311 ParamEnd = FnDecl->param_end();
10312 Param != ParamEnd; ++Param) {
10313 if ((*Param)->hasDefaultArg()) {
10314 Diag((*Param)->getDefaultArgRange().getBegin(),
10315 diag::err_literal_operator_default_argument)
10316 << (*Param)->getDefaultArgRange();
10317 break;
10318 }
10319 }
10320
Richard Smith2fb4ae32012-03-08 02:39:21 +000010321 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010322 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10323 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010324 // C++11 [usrlit.suffix]p1:
10325 // Literal suffix identifiers that do not start with an underscore
10326 // are reserved for future standardization.
10327 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010328 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010329
Sean Hunta6c058d2010-01-13 09:01:02 +000010330 return false;
10331}
10332
Douglas Gregor074149e2009-01-05 19:45:36 +000010333/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10334/// linkage specification, including the language and (if present)
10335/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10336/// the location of the language string literal, which is provided
10337/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10338/// the '{' brace. Otherwise, this linkage specification does not
10339/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010340Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10341 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010342 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010343 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010344 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010345 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010346 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010347 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010348 Language = LinkageSpecDecl::lang_cxx;
10349 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010350 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010351 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010352 }
Mike Stump1eb44332009-09-09 15:08:12 +000010353
Chris Lattnercc98eac2008-12-17 07:13:27 +000010354 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010355
Douglas Gregor074149e2009-01-05 19:45:36 +000010356 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010357 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010358 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010359 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010360 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010361}
10362
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010363/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010364/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10365/// valid, it's the position of the closing '}' brace in a linkage
10366/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010367Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010368 Decl *LinkageSpec,
10369 SourceLocation RBraceLoc) {
10370 if (LinkageSpec) {
10371 if (RBraceLoc.isValid()) {
10372 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10373 LSDecl->setRBraceLoc(RBraceLoc);
10374 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010375 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010376 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010377 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010378}
10379
Michael Han684aa732013-02-22 17:15:32 +000010380Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10381 AttributeList *AttrList,
10382 SourceLocation SemiLoc) {
10383 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10384 // Attribute declarations appertain to empty declaration so we handle
10385 // them here.
10386 if (AttrList)
10387 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010388
Michael Han684aa732013-02-22 17:15:32 +000010389 CurContext->addDecl(ED);
10390 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010391}
10392
Douglas Gregord308e622009-05-18 20:51:54 +000010393/// \brief Perform semantic analysis for the variable declaration that
10394/// occurs within a C++ catch clause, returning the newly-created
10395/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010396VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010397 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010398 SourceLocation StartLoc,
10399 SourceLocation Loc,
10400 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010401 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010402 QualType ExDeclType = TInfo->getType();
10403
Sebastian Redl4b07b292008-12-22 19:15:10 +000010404 // Arrays and functions decay.
10405 if (ExDeclType->isArrayType())
10406 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10407 else if (ExDeclType->isFunctionType())
10408 ExDeclType = Context.getPointerType(ExDeclType);
10409
10410 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10411 // The exception-declaration shall not denote a pointer or reference to an
10412 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010413 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010414 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010415 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010416 Invalid = true;
10417 }
Douglas Gregord308e622009-05-18 20:51:54 +000010418
Sebastian Redl4b07b292008-12-22 19:15:10 +000010419 QualType BaseType = ExDeclType;
10420 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010421 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010422 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010423 BaseType = Ptr->getPointeeType();
10424 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010425 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010426 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010427 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010428 BaseType = Ref->getPointeeType();
10429 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010430 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010431 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010432 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010433 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010434 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010435
Mike Stump1eb44332009-09-09 15:08:12 +000010436 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010437 RequireNonAbstractType(Loc, ExDeclType,
10438 diag::err_abstract_type_in_decl,
10439 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010440 Invalid = true;
10441
John McCall5a180392010-07-24 00:37:23 +000010442 // Only the non-fragile NeXT runtime currently supports C++ catches
10443 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010444 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010445 QualType T = ExDeclType;
10446 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10447 T = RT->getPointeeType();
10448
10449 if (T->isObjCObjectType()) {
10450 Diag(Loc, diag::err_objc_object_catch);
10451 Invalid = true;
10452 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010453 // FIXME: should this be a test for macosx-fragile specifically?
10454 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010455 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010456 }
10457 }
10458
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010459 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010460 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010461 ExDecl->setExceptionVariable(true);
10462
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010463 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010464 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010465 Invalid = true;
10466
Douglas Gregorc41b8782011-07-06 18:14:43 +000010467 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010468 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010469 // Insulate this from anything else we might currently be parsing.
10470 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10471
Douglas Gregor6d182892010-03-05 23:38:39 +000010472 // C++ [except.handle]p16:
10473 // The object declared in an exception-declaration or, if the
10474 // exception-declaration does not specify a name, a temporary (12.2) is
10475 // copy-initialized (8.5) from the exception object. [...]
10476 // The object is destroyed when the handler exits, after the destruction
10477 // of any automatic objects initialized within the handler.
10478 //
10479 // We just pretend to initialize the object with itself, then make sure
10480 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010481 QualType initType = ExDeclType;
10482
10483 InitializedEntity entity =
10484 InitializedEntity::InitializeVariable(ExDecl);
10485 InitializationKind initKind =
10486 InitializationKind::CreateCopy(Loc, SourceLocation());
10487
10488 Expr *opaqueValue =
10489 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10490 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10491 ExprResult result = sequence.Perform(*this, entity, initKind,
10492 MultiExprArg(&opaqueValue, 1));
10493 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010494 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010495 else {
10496 // If the constructor used was non-trivial, set this as the
10497 // "initializer".
10498 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10499 if (!construct->getConstructor()->isTrivial()) {
10500 Expr *init = MaybeCreateExprWithCleanups(construct);
10501 ExDecl->setInit(init);
10502 }
10503
10504 // And make sure it's destructable.
10505 FinalizeVarWithDestructor(ExDecl, recordType);
10506 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010507 }
10508 }
10509
Douglas Gregord308e622009-05-18 20:51:54 +000010510 if (Invalid)
10511 ExDecl->setInvalidDecl();
10512
10513 return ExDecl;
10514}
10515
10516/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10517/// handler.
John McCalld226f652010-08-21 09:40:31 +000010518Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010519 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010520 bool Invalid = D.isInvalidType();
10521
10522 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010523 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10524 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010525 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10526 D.getIdentifierLoc());
10527 Invalid = true;
10528 }
10529
Sebastian Redl4b07b292008-12-22 19:15:10 +000010530 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010531 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010532 LookupOrdinaryName,
10533 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010534 // The scope should be freshly made just for us. There is just no way
10535 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010536 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010537 if (PrevDecl->isTemplateParameter()) {
10538 // Maybe we will complain about the shadowed template parameter.
10539 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010540 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010541 }
10542 }
10543
Chris Lattnereaaebc72009-04-25 08:06:05 +000010544 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010545 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10546 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010547 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010548 }
10549
Douglas Gregor83cb9422010-09-09 17:09:21 +000010550 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010551 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010552 D.getIdentifierLoc(),
10553 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010554 if (Invalid)
10555 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010556
Sebastian Redl4b07b292008-12-22 19:15:10 +000010557 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010558 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010559 PushOnScopeChains(ExDecl, S);
10560 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010561 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010562
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010563 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010564 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010565}
Anders Carlssonfb311762009-03-14 00:25:26 +000010566
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010567Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010568 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010569 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010570 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010571 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010572
Richard Smithe3f470a2012-07-11 22:37:56 +000010573 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10574 return 0;
10575
10576 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10577 AssertMessage, RParenLoc, false);
10578}
10579
10580Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10581 Expr *AssertExpr,
10582 StringLiteral *AssertMessage,
10583 SourceLocation RParenLoc,
10584 bool Failed) {
10585 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10586 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010587 // In a static_assert-declaration, the constant-expression shall be a
10588 // constant expression that can be contextually converted to bool.
10589 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10590 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010591 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010592
Richard Smithdaaefc52011-12-14 23:32:26 +000010593 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010594 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010595 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010596 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010597 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010598
Richard Smithe3f470a2012-07-11 22:37:56 +000010599 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010600 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010601 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010602 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010603 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010604 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010605 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010606 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010607 }
Mike Stump1eb44332009-09-09 15:08:12 +000010608
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010609 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010610 AssertExpr, AssertMessage, RParenLoc,
10611 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010612
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010613 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010614 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010615}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010616
Douglas Gregor1d869352010-04-07 16:53:43 +000010617/// \brief Perform semantic analysis of the given friend type declaration.
10618///
10619/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010620FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010621 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010622 TypeSourceInfo *TSInfo) {
10623 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10624
10625 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010626 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010627
Richard Smith6b130222011-10-18 21:39:00 +000010628 // C++03 [class.friend]p2:
10629 // An elaborated-type-specifier shall be used in a friend declaration
10630 // for a class.*
10631 //
10632 // * The class-key of the elaborated-type-specifier is required.
10633 if (!ActiveTemplateInstantiations.empty()) {
10634 // Do not complain about the form of friend template types during
10635 // template instantiation; we will already have complained when the
10636 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010637 } else {
10638 if (!T->isElaboratedTypeSpecifier()) {
10639 // If we evaluated the type to a record type, suggest putting
10640 // a tag in front.
10641 if (const RecordType *RT = T->getAs<RecordType>()) {
10642 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010643
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010644 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010645
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010646 Diag(TypeRange.getBegin(),
10647 getLangOpts().CPlusPlus11 ?
10648 diag::warn_cxx98_compat_unelaborated_friend_type :
10649 diag::ext_unelaborated_friend_type)
10650 << (unsigned) RD->getTagKind()
10651 << T
10652 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10653 InsertionText);
10654 } else {
10655 Diag(FriendLoc,
10656 getLangOpts().CPlusPlus11 ?
10657 diag::warn_cxx98_compat_nonclass_type_friend :
10658 diag::ext_nonclass_type_friend)
10659 << T
10660 << TypeRange;
10661 }
10662 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010663 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010664 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010665 diag::warn_cxx98_compat_enum_friend :
10666 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010667 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010668 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010669 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010670
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010671 // C++11 [class.friend]p3:
10672 // A friend declaration that does not declare a function shall have one
10673 // of the following forms:
10674 // friend elaborated-type-specifier ;
10675 // friend simple-type-specifier ;
10676 // friend typename-specifier ;
10677 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10678 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10679 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010680
Douglas Gregor06245bf2010-04-07 17:57:12 +000010681 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010682 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010683 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010684 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010685}
10686
John McCall9a34edb2010-10-19 01:40:49 +000010687/// Handle a friend tag declaration where the scope specifier was
10688/// templated.
10689Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10690 unsigned TagSpec, SourceLocation TagLoc,
10691 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010692 IdentifierInfo *Name,
10693 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010694 AttributeList *Attr,
10695 MultiTemplateParamsArg TempParamLists) {
10696 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10697
10698 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010699 bool Invalid = false;
10700
10701 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010702 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010703 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010704 TempParamLists.size(),
10705 /*friend*/ true,
10706 isExplicitSpecialization,
10707 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010708 if (TemplateParams->size() > 0) {
10709 // This is a declaration of a class template.
10710 if (Invalid)
10711 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010712
Eric Christopher4110e132011-07-21 05:34:24 +000010713 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10714 SS, Name, NameLoc, Attr,
10715 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010716 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010717 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010718 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010719 } else {
10720 // The "template<>" header is extraneous.
10721 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10722 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10723 isExplicitSpecialization = true;
10724 }
10725 }
10726
10727 if (Invalid) return 0;
10728
John McCall9a34edb2010-10-19 01:40:49 +000010729 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010730 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010731 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010732 isAllExplicitSpecializations = false;
10733 break;
10734 }
10735 }
10736
10737 // FIXME: don't ignore attributes.
10738
10739 // If it's explicit specializations all the way down, just forget
10740 // about the template header and build an appropriate non-templated
10741 // friend. TODO: for source fidelity, remember the headers.
10742 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010743 if (SS.isEmpty()) {
10744 bool Owned = false;
10745 bool IsDependent = false;
10746 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10747 Attr, AS_public,
10748 /*ModulePrivateLoc=*/SourceLocation(),
10749 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010750 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010751 /*ScopedEnumUsesClassTag=*/false,
10752 /*UnderlyingType=*/TypeResult());
10753 }
10754
Douglas Gregor2494dd02011-03-01 01:34:45 +000010755 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010756 ElaboratedTypeKeyword Keyword
10757 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010758 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010759 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010760 if (T.isNull())
10761 return 0;
10762
10763 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10764 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010765 DependentNameTypeLoc TL =
10766 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010767 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010768 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010769 TL.setNameLoc(NameLoc);
10770 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010771 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010772 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010773 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010774 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010775 }
10776
10777 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010778 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010779 Friend->setAccess(AS_public);
10780 CurContext->addDecl(Friend);
10781 return Friend;
10782 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010783
10784 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10785
10786
John McCall9a34edb2010-10-19 01:40:49 +000010787
10788 // Handle the case of a templated-scope friend class. e.g.
10789 // template <class T> class A<T>::B;
10790 // FIXME: we don't support these right now.
10791 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10792 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10793 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000010794 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010795 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010796 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010797 TL.setNameLoc(NameLoc);
10798
10799 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010800 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010801 Friend->setAccess(AS_public);
10802 Friend->setUnsupportedFriend(true);
10803 CurContext->addDecl(Friend);
10804 return Friend;
10805}
10806
10807
John McCalldd4a3b02009-09-16 22:47:08 +000010808/// Handle a friend type declaration. This works in tandem with
10809/// ActOnTag.
10810///
10811/// Notes on friend class templates:
10812///
10813/// We generally treat friend class declarations as if they were
10814/// declaring a class. So, for example, the elaborated type specifier
10815/// in a friend declaration is required to obey the restrictions of a
10816/// class-head (i.e. no typedefs in the scope chain), template
10817/// parameters are required to match up with simple template-ids, &c.
10818/// However, unlike when declaring a template specialization, it's
10819/// okay to refer to a template specialization without an empty
10820/// template parameter declaration, e.g.
10821/// friend class A<T>::B<unsigned>;
10822/// We permit this as a special case; if there are any template
10823/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010824/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010825Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010826 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010827 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010828
10829 assert(DS.isFriendSpecified());
10830 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10831
John McCalldd4a3b02009-09-16 22:47:08 +000010832 // Try to convert the decl specifier to a type. This works for
10833 // friend templates because ActOnTag never produces a ClassTemplateDecl
10834 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010835 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010836 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10837 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010838 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010839 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010840
Douglas Gregor6ccab972010-12-16 01:14:37 +000010841 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10842 return 0;
10843
John McCalldd4a3b02009-09-16 22:47:08 +000010844 // This is definitely an error in C++98. It's probably meant to
10845 // be forbidden in C++0x, too, but the specification is just
10846 // poorly written.
10847 //
10848 // The problem is with declarations like the following:
10849 // template <T> friend A<T>::foo;
10850 // where deciding whether a class C is a friend or not now hinges
10851 // on whether there exists an instantiation of A that causes
10852 // 'foo' to equal C. There are restrictions on class-heads
10853 // (which we declare (by fiat) elaborated friend declarations to
10854 // be) that makes this tractable.
10855 //
10856 // FIXME: handle "template <> friend class A<T>;", which
10857 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010858 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010859 Diag(Loc, diag::err_tagless_friend_type_template)
10860 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010861 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010862 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010863
John McCall02cace72009-08-28 07:59:38 +000010864 // C++98 [class.friend]p1: A friend of a class is a function
10865 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010866 // This is fixed in DR77, which just barely didn't make the C++03
10867 // deadline. It's also a very silly restriction that seriously
10868 // affects inner classes and which nobody else seems to implement;
10869 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010870 //
10871 // But note that we could warn about it: it's always useless to
10872 // friend one of your own members (it's not, however, worthless to
10873 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010874
John McCalldd4a3b02009-09-16 22:47:08 +000010875 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010876 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010877 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010878 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010879 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010880 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010881 DS.getFriendSpecLoc());
10882 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010883 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010884
10885 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010886 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010887
John McCalldd4a3b02009-09-16 22:47:08 +000010888 D->setAccess(AS_public);
10889 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010890
John McCalld226f652010-08-21 09:40:31 +000010891 return D;
John McCall02cace72009-08-28 07:59:38 +000010892}
10893
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000010894NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10895 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010896 const DeclSpec &DS = D.getDeclSpec();
10897
10898 assert(DS.isFriendSpecified());
10899 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10900
10901 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010902 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010903
10904 // C++ [class.friend]p1
10905 // A friend of a class is a function or class....
10906 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010907 // It *doesn't* see through dependent types, which is correct
10908 // according to [temp.arg.type]p3:
10909 // If a declaration acquires a function type through a
10910 // type dependent on a template-parameter and this causes
10911 // a declaration that does not use the syntactic form of a
10912 // function declarator to have a function type, the program
10913 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010914 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010915 Diag(Loc, diag::err_unexpected_friend);
10916
10917 // It might be worthwhile to try to recover by creating an
10918 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010919 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010920 }
10921
10922 // C++ [namespace.memdef]p3
10923 // - If a friend declaration in a non-local class first declares a
10924 // class or function, the friend class or function is a member
10925 // of the innermost enclosing namespace.
10926 // - The name of the friend is not found by simple name lookup
10927 // until a matching declaration is provided in that namespace
10928 // scope (either before or after the class declaration granting
10929 // friendship).
10930 // - If a friend function is called, its name may be found by the
10931 // name lookup that considers functions from namespaces and
10932 // classes associated with the types of the function arguments.
10933 // - When looking for a prior declaration of a class or a function
10934 // declared as a friend, scopes outside the innermost enclosing
10935 // namespace scope are not considered.
10936
John McCall337ec3d2010-10-12 23:13:28 +000010937 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010938 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10939 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010940 assert(Name);
10941
Douglas Gregor6ccab972010-12-16 01:14:37 +000010942 // Check for unexpanded parameter packs.
10943 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10944 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10945 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10946 return 0;
10947
John McCall67d1a672009-08-06 02:15:43 +000010948 // The context we found the declaration in, or in which we should
10949 // create the declaration.
10950 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010951 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010952 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010953 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010954
John McCall337ec3d2010-10-12 23:13:28 +000010955 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010956
John McCall337ec3d2010-10-12 23:13:28 +000010957 // There are four cases here.
10958 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010959 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010960 // there as appropriate.
10961 // Recover from invalid scope qualifiers as if they just weren't there.
10962 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010963 // C++0x [namespace.memdef]p3:
10964 // If the name in a friend declaration is neither qualified nor
10965 // a template-id and the declaration is a function or an
10966 // elaborated-type-specifier, the lookup to determine whether
10967 // the entity has been previously declared shall not consider
10968 // any scopes outside the innermost enclosing namespace.
10969 // C++0x [class.friend]p11:
10970 // If a friend declaration appears in a local class and the name
10971 // specified is an unqualified name, a prior declaration is
10972 // looked up without considering scopes that are outside the
10973 // innermost enclosing non-class scope. For a friend function
10974 // declaration, if there is no prior declaration, the program is
10975 // ill-formed.
10976 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010977 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010978
John McCall29ae6e52010-10-13 05:45:15 +000010979 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010980 DC = CurContext;
10981 while (true) {
10982 // Skip class contexts. If someone can cite chapter and verse
10983 // for this behavior, that would be nice --- it's what GCC and
10984 // EDG do, and it seems like a reasonable intent, but the spec
10985 // really only says that checks for unqualified existing
10986 // declarations should stop at the nearest enclosing namespace,
10987 // not that they should only consider the nearest enclosing
10988 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010989 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010990 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010991
John McCall68263142009-11-18 22:49:29 +000010992 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010993
10994 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010995 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010996 break;
John McCall29ae6e52010-10-13 05:45:15 +000010997
John McCall8a407372010-10-14 22:22:28 +000010998 if (isTemplateId) {
10999 if (isa<TranslationUnitDecl>(DC)) break;
11000 } else {
11001 if (DC->isFileContext()) break;
11002 }
John McCall67d1a672009-08-06 02:15:43 +000011003 DC = DC->getParent();
11004 }
11005
John McCall380aaa42010-10-13 06:22:15 +000011006 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011007
Douglas Gregor883af832011-10-10 01:11:59 +000011008 // C++ [class.friend]p6:
11009 // A function can be defined in a friend declaration of a class if and
11010 // only if the class is a non-local class (9.8), the function name is
11011 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011012 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011013 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11014 }
11015
John McCall337ec3d2010-10-12 23:13:28 +000011016 // - There's a non-dependent scope specifier, in which case we
11017 // compute it and do a previous lookup there for a function
11018 // or function template.
11019 } else if (!SS.getScopeRep()->isDependent()) {
11020 DC = computeDeclContext(SS);
11021 if (!DC) return 0;
11022
11023 if (RequireCompleteDeclContext(SS, DC)) return 0;
11024
11025 LookupQualifiedName(Previous, DC);
11026
11027 // Ignore things found implicitly in the wrong scope.
11028 // TODO: better diagnostics for this case. Suggesting the right
11029 // qualified scope would be nice...
11030 LookupResult::Filter F = Previous.makeFilter();
11031 while (F.hasNext()) {
11032 NamedDecl *D = F.next();
11033 if (!DC->InEnclosingNamespaceSetOf(
11034 D->getDeclContext()->getRedeclContext()))
11035 F.erase();
11036 }
11037 F.done();
11038
11039 if (Previous.empty()) {
11040 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011041 Diag(Loc, diag::err_qualified_friend_not_found)
11042 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011043 return 0;
11044 }
11045
11046 // C++ [class.friend]p1: A friend of a class is a function or
11047 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011048 if (DC->Equals(CurContext))
11049 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011050 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011051 diag::warn_cxx98_compat_friend_is_member :
11052 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011053
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011054 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011055 // C++ [class.friend]p6:
11056 // A function can be defined in a friend declaration of a class if and
11057 // only if the class is a non-local class (9.8), the function name is
11058 // unqualified, and the function has namespace scope.
11059 SemaDiagnosticBuilder DB
11060 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11061
11062 DB << SS.getScopeRep();
11063 if (DC->isFileContext())
11064 DB << FixItHint::CreateRemoval(SS.getRange());
11065 SS.clear();
11066 }
John McCall337ec3d2010-10-12 23:13:28 +000011067
11068 // - There's a scope specifier that does not match any template
11069 // parameter lists, in which case we use some arbitrary context,
11070 // create a method or method template, and wait for instantiation.
11071 // - There's a scope specifier that does match some template
11072 // parameter lists, which we don't handle right now.
11073 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011074 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011075 // C++ [class.friend]p6:
11076 // A function can be defined in a friend declaration of a class if and
11077 // only if the class is a non-local class (9.8), the function name is
11078 // unqualified, and the function has namespace scope.
11079 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11080 << SS.getScopeRep();
11081 }
11082
John McCall337ec3d2010-10-12 23:13:28 +000011083 DC = CurContext;
11084 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011085 }
Douglas Gregor883af832011-10-10 01:11:59 +000011086
John McCall29ae6e52010-10-13 05:45:15 +000011087 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011088 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011089 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11090 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11091 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011092 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011093 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11094 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011095 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011096 }
John McCall67d1a672009-08-06 02:15:43 +000011097 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011098
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011099 // FIXME: This is an egregious hack to cope with cases where the scope stack
11100 // does not contain the declaration context, i.e., in an out-of-line
11101 // definition of a class.
11102 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11103 if (!DCScope) {
11104 FakeDCScope.setEntity(DC);
11105 DCScope = &FakeDCScope;
11106 }
11107
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011108 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011109 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011110 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011111 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011112
Douglas Gregor182ddf02009-09-28 00:08:27 +000011113 assert(ND->getDeclContext() == DC);
11114 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011115
John McCallab88d972009-08-31 22:39:49 +000011116 // Add the function declaration to the appropriate lookup tables,
11117 // adjusting the redeclarations list as necessary. We don't
11118 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011119 //
John McCallab88d972009-08-31 22:39:49 +000011120 // Also update the scope-based lookup if the target context's
11121 // lookup context is in lexical scope.
11122 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011123 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011124 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011125 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011126 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011127 }
John McCall02cace72009-08-28 07:59:38 +000011128
11129 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011130 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011131 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011132 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011133 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011134
John McCall1f2e1a92012-08-10 03:15:35 +000011135 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011136 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011137 } else {
11138 if (DC->isRecord()) CheckFriendAccess(ND);
11139
John McCall6102ca12010-10-16 06:59:13 +000011140 FunctionDecl *FD;
11141 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11142 FD = FTD->getTemplatedDecl();
11143 else
11144 FD = cast<FunctionDecl>(ND);
11145
11146 // Mark templated-scope function declarations as unsupported.
11147 if (FD->getNumTemplateParameterLists())
11148 FrD->setUnsupportedFriend(true);
11149 }
John McCall337ec3d2010-10-12 23:13:28 +000011150
John McCalld226f652010-08-21 09:40:31 +000011151 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011152}
11153
John McCalld226f652010-08-21 09:40:31 +000011154void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11155 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011156
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011157 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011158 if (!Fn) {
11159 Diag(DelLoc, diag::err_deleted_non_function);
11160 return;
11161 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011162
Douglas Gregoref96ee02012-01-14 16:38:05 +000011163 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011164 // Don't consider the implicit declaration we generate for explicit
11165 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011166 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11167 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011168 Diag(DelLoc, diag::err_deleted_decl_not_first);
11169 Diag(Prev->getLocation(), diag::note_previous_declaration);
11170 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011171 // If the declaration wasn't the first, we delete the function anyway for
11172 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011173 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011174 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011175
11176 if (Fn->isDeleted())
11177 return;
11178
11179 // See if we're deleting a function which is already known to override a
11180 // non-deleted virtual function.
11181 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11182 bool IssuedDiagnostic = false;
11183 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11184 E = MD->end_overridden_methods();
11185 I != E; ++I) {
11186 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11187 if (!IssuedDiagnostic) {
11188 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11189 IssuedDiagnostic = true;
11190 }
11191 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11192 }
11193 }
11194 }
11195
Sean Hunt10620eb2011-05-06 20:44:56 +000011196 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011197}
Sebastian Redl13e88542009-04-27 21:33:24 +000011198
Sean Hunte4246a62011-05-12 06:15:49 +000011199void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011200 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011201
11202 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011203 if (MD->getParent()->isDependentType()) {
11204 MD->setDefaulted();
11205 MD->setExplicitlyDefaulted();
11206 return;
11207 }
11208
Sean Hunte4246a62011-05-12 06:15:49 +000011209 CXXSpecialMember Member = getSpecialMember(MD);
11210 if (Member == CXXInvalid) {
11211 Diag(DefaultLoc, diag::err_default_special_members);
11212 return;
11213 }
11214
11215 MD->setDefaulted();
11216 MD->setExplicitlyDefaulted();
11217
Sean Huntcd10dec2011-05-23 23:14:04 +000011218 // If this definition appears within the record, do the checking when
11219 // the record is complete.
11220 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011221 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011222 // Find the uninstantiated declaration that actually had the '= default'
11223 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011224 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011225
Richard Smith12fef492013-03-27 00:22:47 +000011226 // If the method was defaulted on its first declaration, we will have
11227 // already performed the checking in CheckCompletedCXXClass. Such a
11228 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011229 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011230 return;
11231
Richard Smithb9d0b762012-07-27 04:22:15 +000011232 CheckExplicitlyDefaultedSpecialMember(MD);
11233
Richard Smith1d28caf2012-12-11 01:14:52 +000011234 // The exception specification is needed because we are defining the
11235 // function.
11236 ResolveExceptionSpec(DefaultLoc,
11237 MD->getType()->castAs<FunctionProtoType>());
11238
Sean Hunte4246a62011-05-12 06:15:49 +000011239 switch (Member) {
11240 case CXXDefaultConstructor: {
11241 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011242 if (!CD->isInvalidDecl())
11243 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11244 break;
11245 }
11246
11247 case CXXCopyConstructor: {
11248 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011249 if (!CD->isInvalidDecl())
11250 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011251 break;
11252 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011253
Sean Hunt2b188082011-05-14 05:23:28 +000011254 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011255 if (!MD->isInvalidDecl())
11256 DefineImplicitCopyAssignment(DefaultLoc, MD);
11257 break;
11258 }
11259
Sean Huntcb45a0f2011-05-12 22:46:25 +000011260 case CXXDestructor: {
11261 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011262 if (!DD->isInvalidDecl())
11263 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011264 break;
11265 }
11266
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011267 case CXXMoveConstructor: {
11268 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011269 if (!CD->isInvalidDecl())
11270 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011271 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011272 }
Sean Hunt82713172011-05-25 23:16:36 +000011273
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011274 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011275 if (!MD->isInvalidDecl())
11276 DefineImplicitMoveAssignment(DefaultLoc, MD);
11277 break;
11278 }
11279
11280 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011281 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011282 }
11283 } else {
11284 Diag(DefaultLoc, diag::err_default_special_members);
11285 }
11286}
11287
Sebastian Redl13e88542009-04-27 21:33:24 +000011288static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011289 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011290 Stmt *SubStmt = *CI;
11291 if (!SubStmt)
11292 continue;
11293 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011294 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011295 diag::err_return_in_constructor_handler);
11296 if (!isa<Expr>(SubStmt))
11297 SearchForReturnInStmt(Self, SubStmt);
11298 }
11299}
11300
11301void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11302 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11303 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11304 SearchForReturnInStmt(*this, Handler);
11305 }
11306}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011307
David Blaikie299adab2013-01-18 23:03:15 +000011308bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011309 const CXXMethodDecl *Old) {
11310 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11311 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11312
11313 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11314
11315 // If the calling conventions match, everything is fine
11316 if (NewCC == OldCC)
11317 return false;
11318
11319 // If either of the calling conventions are set to "default", we need to pick
11320 // something more sensible based on the target. This supports code where the
11321 // one method explicitly sets thiscall, and another has no explicit calling
11322 // convention.
11323 CallingConv Default =
11324 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11325 if (NewCC == CC_Default)
11326 NewCC = Default;
11327 if (OldCC == CC_Default)
11328 OldCC = Default;
11329
11330 // If the calling conventions still don't match, then report the error
11331 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011332 Diag(New->getLocation(),
11333 diag::err_conflicting_overriding_cc_attributes)
11334 << New->getDeclName() << New->getType() << Old->getType();
11335 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11336 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011337 }
11338
11339 return false;
11340}
11341
Mike Stump1eb44332009-09-09 15:08:12 +000011342bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011343 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011344 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11345 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011346
Chandler Carruth73857792010-02-15 11:53:20 +000011347 if (Context.hasSameType(NewTy, OldTy) ||
11348 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011349 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011350
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011351 // Check if the return types are covariant
11352 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011353
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011354 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011355 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11356 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011357 NewClassTy = NewPT->getPointeeType();
11358 OldClassTy = OldPT->getPointeeType();
11359 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011360 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11361 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11362 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11363 NewClassTy = NewRT->getPointeeType();
11364 OldClassTy = OldRT->getPointeeType();
11365 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011366 }
11367 }
Mike Stump1eb44332009-09-09 15:08:12 +000011368
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011369 // The return types aren't either both pointers or references to a class type.
11370 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011371 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011372 diag::err_different_return_type_for_overriding_virtual_function)
11373 << New->getDeclName() << NewTy << OldTy;
11374 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011375
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011376 return true;
11377 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011378
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011379 // C++ [class.virtual]p6:
11380 // If the return type of D::f differs from the return type of B::f, the
11381 // class type in the return type of D::f shall be complete at the point of
11382 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011383 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11384 if (!RT->isBeingDefined() &&
11385 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011386 diag::err_covariant_return_incomplete,
11387 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011388 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011389 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011390
Douglas Gregora4923eb2009-11-16 21:35:15 +000011391 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011392 // Check if the new class derives from the old class.
11393 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11394 Diag(New->getLocation(),
11395 diag::err_covariant_return_not_derived)
11396 << New->getDeclName() << NewTy << OldTy;
11397 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11398 return true;
11399 }
Mike Stump1eb44332009-09-09 15:08:12 +000011400
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011401 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011402 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011403 diag::err_covariant_return_inaccessible_base,
11404 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11405 // FIXME: Should this point to the return type?
11406 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011407 // FIXME: this note won't trigger for delayed access control
11408 // diagnostics, and it's impossible to get an undelayed error
11409 // here from access control during the original parse because
11410 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011411 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11412 return true;
11413 }
11414 }
Mike Stump1eb44332009-09-09 15:08:12 +000011415
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011416 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011417 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011418 Diag(New->getLocation(),
11419 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011420 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011421 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11422 return true;
11423 };
Mike Stump1eb44332009-09-09 15:08:12 +000011424
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011425
11426 // The new class type must have the same or less qualifiers as the old type.
11427 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11428 Diag(New->getLocation(),
11429 diag::err_covariant_return_type_class_type_more_qualified)
11430 << New->getDeclName() << NewTy << OldTy;
11431 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11432 return true;
11433 };
Mike Stump1eb44332009-09-09 15:08:12 +000011434
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011435 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011436}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011437
Douglas Gregor4ba31362009-12-01 17:24:26 +000011438/// \brief Mark the given method pure.
11439///
11440/// \param Method the method to be marked pure.
11441///
11442/// \param InitRange the source range that covers the "0" initializer.
11443bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011444 SourceLocation EndLoc = InitRange.getEnd();
11445 if (EndLoc.isValid())
11446 Method->setRangeEnd(EndLoc);
11447
Douglas Gregor4ba31362009-12-01 17:24:26 +000011448 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11449 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011450 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011451 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011452
11453 if (!Method->isInvalidDecl())
11454 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11455 << Method->getDeclName() << InitRange;
11456 return true;
11457}
11458
Douglas Gregor552e2992012-02-21 02:22:07 +000011459/// \brief Determine whether the given declaration is a static data member.
11460static bool isStaticDataMember(Decl *D) {
11461 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11462 if (!Var)
11463 return false;
11464
11465 return Var->isStaticDataMember();
11466}
John McCall731ad842009-12-19 09:28:58 +000011467/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11468/// an initializer for the out-of-line declaration 'Dcl'. The scope
11469/// is a fresh scope pushed for just this purpose.
11470///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011471/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11472/// static data member of class X, names should be looked up in the scope of
11473/// class X.
John McCalld226f652010-08-21 09:40:31 +000011474void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011475 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011476 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011477
John McCall731ad842009-12-19 09:28:58 +000011478 // We should only get called for declarations with scope specifiers, like:
11479 // int foo::bar;
11480 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011481 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011482
11483 // If we are parsing the initializer for a static data member, push a
11484 // new expression evaluation context that is associated with this static
11485 // data member.
11486 if (isStaticDataMember(D))
11487 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011488}
11489
11490/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011491/// initializer for the out-of-line declaration 'D'.
11492void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011493 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011494 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011495
Douglas Gregor552e2992012-02-21 02:22:07 +000011496 if (isStaticDataMember(D))
11497 PopExpressionEvaluationContext();
11498
John McCall731ad842009-12-19 09:28:58 +000011499 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011500 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011501}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011502
11503/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11504/// C++ if/switch/while/for statement.
11505/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011506DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011507 // C++ 6.4p2:
11508 // The declarator shall not specify a function or an array.
11509 // The type-specifier-seq shall not contain typedef and shall not declare a
11510 // new class or enumeration.
11511 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11512 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011513
11514 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011515 if (!Dcl)
11516 return true;
11517
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011518 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11519 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011520 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011521 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011522 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011523
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011524 return Dcl;
11525}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011526
Douglas Gregordfe65432011-07-28 19:11:31 +000011527void Sema::LoadExternalVTableUses() {
11528 if (!ExternalSource)
11529 return;
11530
11531 SmallVector<ExternalVTableUse, 4> VTables;
11532 ExternalSource->ReadUsedVTables(VTables);
11533 SmallVector<VTableUse, 4> NewUses;
11534 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11535 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11536 = VTablesUsed.find(VTables[I].Record);
11537 // Even if a definition wasn't required before, it may be required now.
11538 if (Pos != VTablesUsed.end()) {
11539 if (!Pos->second && VTables[I].DefinitionRequired)
11540 Pos->second = true;
11541 continue;
11542 }
11543
11544 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11545 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11546 }
11547
11548 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11549}
11550
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011551void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11552 bool DefinitionRequired) {
11553 // Ignore any vtable uses in unevaluated operands or for classes that do
11554 // not have a vtable.
11555 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11556 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011557 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011558 return;
11559
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011560 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011561 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011562 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11563 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11564 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11565 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011566 // If we already had an entry, check to see if we are promoting this vtable
11567 // to required a definition. If so, we need to reappend to the VTableUses
11568 // list, since we may have already processed the first entry.
11569 if (DefinitionRequired && !Pos.first->second) {
11570 Pos.first->second = true;
11571 } else {
11572 // Otherwise, we can early exit.
11573 return;
11574 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011575 }
11576
11577 // Local classes need to have their virtual members marked
11578 // immediately. For all other classes, we mark their virtual members
11579 // at the end of the translation unit.
11580 if (Class->isLocalClass())
11581 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011582 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011583 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011584}
11585
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011586bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011587 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011588 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011589 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011590
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011591 // Note: The VTableUses vector could grow as a result of marking
11592 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011593 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011594 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011595 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011596 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011597 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011598 if (!Class)
11599 continue;
11600
11601 SourceLocation Loc = VTableUses[I].second;
11602
Richard Smithb9d0b762012-07-27 04:22:15 +000011603 bool DefineVTable = true;
11604
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011605 // If this class has a key function, but that key function is
11606 // defined in another translation unit, we don't need to emit the
11607 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011608 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011609 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011610 switch (KeyFunction->getTemplateSpecializationKind()) {
11611 case TSK_Undeclared:
11612 case TSK_ExplicitSpecialization:
11613 case TSK_ExplicitInstantiationDeclaration:
11614 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011615 DefineVTable = false;
11616 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011617
11618 case TSK_ExplicitInstantiationDefinition:
11619 case TSK_ImplicitInstantiation:
11620 // We will be instantiating the key function.
11621 break;
11622 }
11623 } else if (!KeyFunction) {
11624 // If we have a class with no key function that is the subject
11625 // of an explicit instantiation declaration, suppress the
11626 // vtable; it will live with the explicit instantiation
11627 // definition.
11628 bool IsExplicitInstantiationDeclaration
11629 = Class->getTemplateSpecializationKind()
11630 == TSK_ExplicitInstantiationDeclaration;
11631 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11632 REnd = Class->redecls_end();
11633 R != REnd; ++R) {
11634 TemplateSpecializationKind TSK
11635 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11636 if (TSK == TSK_ExplicitInstantiationDeclaration)
11637 IsExplicitInstantiationDeclaration = true;
11638 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11639 IsExplicitInstantiationDeclaration = false;
11640 break;
11641 }
11642 }
11643
11644 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011645 DefineVTable = false;
11646 }
11647
11648 // The exception specifications for all virtual members may be needed even
11649 // if we are not providing an authoritative form of the vtable in this TU.
11650 // We may choose to emit it available_externally anyway.
11651 if (!DefineVTable) {
11652 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11653 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011654 }
11655
11656 // Mark all of the virtual members of this class as referenced, so
11657 // that we can build a vtable. Then, tell the AST consumer that a
11658 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011659 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011660 MarkVirtualMembersReferenced(Loc, Class);
11661 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11662 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11663
11664 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola531db822013-03-07 02:00:27 +000011665 if (Class->hasExternalLinkage() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011666 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011667 const FunctionDecl *KeyFunctionDef = 0;
11668 if (!KeyFunction ||
11669 (KeyFunction->hasBody(KeyFunctionDef) &&
11670 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011671 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11672 TSK_ExplicitInstantiationDefinition
11673 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11674 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011675 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011676 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011677 VTableUses.clear();
11678
Douglas Gregor78844032011-04-22 22:25:37 +000011679 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011680}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011681
Richard Smithb9d0b762012-07-27 04:22:15 +000011682void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11683 const CXXRecordDecl *RD) {
11684 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11685 E = RD->method_end(); I != E; ++I)
11686 if ((*I)->isVirtual() && !(*I)->isPure())
11687 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11688}
11689
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011690void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11691 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011692 // Mark all functions which will appear in RD's vtable as used.
11693 CXXFinalOverriderMap FinalOverriders;
11694 RD->getFinalOverriders(FinalOverriders);
11695 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11696 E = FinalOverriders.end();
11697 I != E; ++I) {
11698 for (OverridingMethods::const_iterator OI = I->second.begin(),
11699 OE = I->second.end();
11700 OI != OE; ++OI) {
11701 assert(OI->second.size() > 0 && "no final overrider");
11702 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011703
Richard Smithff817f72012-07-07 06:59:51 +000011704 // C++ [basic.def.odr]p2:
11705 // [...] A virtual member function is used if it is not pure. [...]
11706 if (!Overrider->isPure())
11707 MarkFunctionReferenced(Loc, Overrider);
11708 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011709 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011710
11711 // Only classes that have virtual bases need a VTT.
11712 if (RD->getNumVBases() == 0)
11713 return;
11714
11715 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11716 e = RD->bases_end(); i != e; ++i) {
11717 const CXXRecordDecl *Base =
11718 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011719 if (Base->getNumVBases() == 0)
11720 continue;
11721 MarkVirtualMembersReferenced(Loc, Base);
11722 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011723}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011724
11725/// SetIvarInitializers - This routine builds initialization ASTs for the
11726/// Objective-C implementation whose ivars need be initialized.
11727void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011728 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011729 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011730 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011731 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011732 CollectIvarsToConstructOrDestruct(OID, ivars);
11733 if (ivars.empty())
11734 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011735 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011736 for (unsigned i = 0; i < ivars.size(); i++) {
11737 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011738 if (Field->isInvalidDecl())
11739 continue;
11740
Sean Huntcbb67482011-01-08 20:30:50 +000011741 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011742 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11743 InitializationKind InitKind =
11744 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11745
11746 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011747 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011748 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011749 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011750 // Note, MemberInit could actually come back empty if no initialization
11751 // is required (e.g., because it would call a trivial default constructor)
11752 if (!MemberInit.get() || MemberInit.isInvalid())
11753 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011754
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011755 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011756 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11757 SourceLocation(),
11758 MemberInit.takeAs<Expr>(),
11759 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011760 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011761
11762 // Be sure that the destructor is accessible and is marked as referenced.
11763 if (const RecordType *RecordTy
11764 = Context.getBaseElementType(Field->getType())
11765 ->getAs<RecordType>()) {
11766 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011767 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011768 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011769 CheckDestructorAccess(Field->getLocation(), Destructor,
11770 PDiag(diag::err_access_dtor_ivar)
11771 << Context.getBaseElementType(Field->getType()));
11772 }
11773 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011774 }
11775 ObjCImplementation->setIvarInitializers(Context,
11776 AllToInit.data(), AllToInit.size());
11777 }
11778}
Sean Huntfe57eef2011-05-04 05:57:24 +000011779
Sean Huntebcbe1d2011-05-04 23:29:54 +000011780static
11781void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11782 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11783 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11784 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11785 Sema &S) {
11786 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11787 CE = Current.end();
11788 if (Ctor->isInvalidDecl())
11789 return;
11790
Richard Smitha8eaf002012-08-23 06:16:52 +000011791 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11792
11793 // Target may not be determinable yet, for instance if this is a dependent
11794 // call in an uninstantiated template.
11795 if (Target) {
11796 const FunctionDecl *FNTarget = 0;
11797 (void)Target->hasBody(FNTarget);
11798 Target = const_cast<CXXConstructorDecl*>(
11799 cast_or_null<CXXConstructorDecl>(FNTarget));
11800 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011801
11802 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11803 // Avoid dereferencing a null pointer here.
11804 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11805
11806 if (!Current.insert(Canonical))
11807 return;
11808
11809 // We know that beyond here, we aren't chaining into a cycle.
11810 if (!Target || !Target->isDelegatingConstructor() ||
11811 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11812 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11813 Valid.insert(*CI);
11814 Current.clear();
11815 // We've hit a cycle.
11816 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11817 Current.count(TCanonical)) {
11818 // If we haven't diagnosed this cycle yet, do so now.
11819 if (!Invalid.count(TCanonical)) {
11820 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011821 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011822 << Ctor;
11823
Richard Smitha8eaf002012-08-23 06:16:52 +000011824 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011825 if (TCanonical != Canonical)
11826 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11827
11828 CXXConstructorDecl *C = Target;
11829 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011830 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011831 (void)C->getTargetConstructor()->hasBody(FNTarget);
11832 assert(FNTarget && "Ctor cycle through bodiless function");
11833
Richard Smitha8eaf002012-08-23 06:16:52 +000011834 C = const_cast<CXXConstructorDecl*>(
11835 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011836 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11837 }
11838 }
11839
11840 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11841 Invalid.insert(*CI);
11842 Current.clear();
11843 } else {
11844 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11845 }
11846}
11847
11848
Sean Huntfe57eef2011-05-04 05:57:24 +000011849void Sema::CheckDelegatingCtorCycles() {
11850 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11851
Sean Huntebcbe1d2011-05-04 23:29:54 +000011852 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11853 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011854
Douglas Gregor0129b562011-07-27 21:57:17 +000011855 for (DelegatingCtorDeclsType::iterator
11856 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011857 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011858 I != E; ++I)
11859 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011860
11861 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11862 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011863}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011864
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011865namespace {
11866 /// \brief AST visitor that finds references to the 'this' expression.
11867 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11868 Sema &S;
11869
11870 public:
11871 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11872
11873 bool VisitCXXThisExpr(CXXThisExpr *E) {
11874 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11875 << E->isImplicit();
11876 return false;
11877 }
11878 };
11879}
11880
11881bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11882 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11883 if (!TSInfo)
11884 return false;
11885
11886 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011887 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011888 if (!ProtoTL)
11889 return false;
11890
11891 // C++11 [expr.prim.general]p3:
11892 // [The expression this] shall not appear before the optional
11893 // cv-qualifier-seq and it shall not appear within the declaration of a
11894 // static member function (although its type and value category are defined
11895 // within a static member function as they are within a non-static member
11896 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011897 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000011898 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011899 FindCXXThisExpr Finder(*this);
11900
11901 // If the return type came after the cv-qualifier-seq, check it now.
11902 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000011903 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011904 return true;
11905
11906 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011907 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11908 return true;
11909
11910 return checkThisInStaticMemberFunctionAttributes(Method);
11911}
11912
11913bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11914 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11915 if (!TSInfo)
11916 return false;
11917
11918 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011919 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011920 if (!ProtoTL)
11921 return false;
11922
David Blaikie39e6ab42013-02-18 22:06:02 +000011923 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011924 FindCXXThisExpr Finder(*this);
11925
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011926 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011927 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011928 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011929 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011930 case EST_DynamicNone:
11931 case EST_MSAny:
11932 case EST_None:
11933 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011934
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011935 case EST_ComputedNoexcept:
11936 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11937 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011938
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011939 case EST_Dynamic:
11940 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011941 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011942 E != EEnd; ++E) {
11943 if (!Finder.TraverseType(*E))
11944 return true;
11945 }
11946 break;
11947 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011948
11949 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011950}
11951
11952bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11953 FindCXXThisExpr Finder(*this);
11954
11955 // Check attributes.
11956 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11957 A != AEnd; ++A) {
11958 // FIXME: This should be emitted by tblgen.
11959 Expr *Arg = 0;
11960 ArrayRef<Expr *> Args;
11961 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11962 Arg = G->getArg();
11963 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11964 Arg = G->getArg();
11965 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11966 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11967 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11968 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11969 else if (ExclusiveLockFunctionAttr *ELF
11970 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11971 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11972 else if (SharedLockFunctionAttr *SLF
11973 = dyn_cast<SharedLockFunctionAttr>(*A))
11974 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11975 else if (ExclusiveTrylockFunctionAttr *ETLF
11976 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11977 Arg = ETLF->getSuccessValue();
11978 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11979 } else if (SharedTrylockFunctionAttr *STLF
11980 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11981 Arg = STLF->getSuccessValue();
11982 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11983 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11984 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11985 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11986 Arg = LR->getArg();
11987 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11988 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11989 else if (ExclusiveLocksRequiredAttr *ELR
11990 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11991 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11992 else if (SharedLocksRequiredAttr *SLR
11993 = dyn_cast<SharedLocksRequiredAttr>(*A))
11994 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11995
11996 if (Arg && !Finder.TraverseStmt(Arg))
11997 return true;
11998
11999 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12000 if (!Finder.TraverseStmt(Args[I]))
12001 return true;
12002 }
12003 }
12004
12005 return false;
12006}
12007
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012008void
12009Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12010 ArrayRef<ParsedType> DynamicExceptions,
12011 ArrayRef<SourceRange> DynamicExceptionRanges,
12012 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012013 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012014 FunctionProtoType::ExtProtoInfo &EPI) {
12015 Exceptions.clear();
12016 EPI.ExceptionSpecType = EST;
12017 if (EST == EST_Dynamic) {
12018 Exceptions.reserve(DynamicExceptions.size());
12019 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12020 // FIXME: Preserve type source info.
12021 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12022
12023 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12024 collectUnexpandedParameterPacks(ET, Unexpanded);
12025 if (!Unexpanded.empty()) {
12026 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12027 UPPC_ExceptionType,
12028 Unexpanded);
12029 continue;
12030 }
12031
12032 // Check that the type is valid for an exception spec, and
12033 // drop it if not.
12034 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12035 Exceptions.push_back(ET);
12036 }
12037 EPI.NumExceptions = Exceptions.size();
12038 EPI.Exceptions = Exceptions.data();
12039 return;
12040 }
12041
12042 if (EST == EST_ComputedNoexcept) {
12043 // If an error occurred, there's no expression here.
12044 if (NoexceptExpr) {
12045 assert((NoexceptExpr->isTypeDependent() ||
12046 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12047 Context.BoolTy) &&
12048 "Parser should have made sure that the expression is boolean");
12049 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12050 EPI.ExceptionSpecType = EST_BasicNoexcept;
12051 return;
12052 }
12053
12054 if (!NoexceptExpr->isValueDependent())
12055 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012056 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012057 /*AllowFold*/ false).take();
12058 EPI.NoexceptExpr = NoexceptExpr;
12059 }
12060 return;
12061 }
12062}
12063
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012064/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12065Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12066 // Implicitly declared functions (e.g. copy constructors) are
12067 // __host__ __device__
12068 if (D->isImplicit())
12069 return CFT_HostDevice;
12070
12071 if (D->hasAttr<CUDAGlobalAttr>())
12072 return CFT_Global;
12073
12074 if (D->hasAttr<CUDADeviceAttr>()) {
12075 if (D->hasAttr<CUDAHostAttr>())
12076 return CFT_HostDevice;
12077 else
12078 return CFT_Device;
12079 }
12080
12081 return CFT_Host;
12082}
12083
12084bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12085 CUDAFunctionTarget CalleeTarget) {
12086 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12087 // Callable from the device only."
12088 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12089 return true;
12090
12091 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12092 // Callable from the host only."
12093 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12094 // Callable from the host only."
12095 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12096 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12097 return true;
12098
12099 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12100 return true;
12101
12102 return false;
12103}
John McCall76da55d2013-04-16 07:28:30 +000012104
12105/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12106///
12107MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12108 SourceLocation DeclStart,
12109 Declarator &D, Expr *BitWidth,
12110 InClassInitStyle InitStyle,
12111 AccessSpecifier AS,
12112 AttributeList *MSPropertyAttr) {
12113 IdentifierInfo *II = D.getIdentifier();
12114 if (!II) {
12115 Diag(DeclStart, diag::err_anonymous_property);
12116 return NULL;
12117 }
12118 SourceLocation Loc = D.getIdentifierLoc();
12119
12120 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12121 QualType T = TInfo->getType();
12122 if (getLangOpts().CPlusPlus) {
12123 CheckExtraCXXDefaultArguments(D);
12124
12125 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12126 UPPC_DataMemberType)) {
12127 D.setInvalidType();
12128 T = Context.IntTy;
12129 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12130 }
12131 }
12132
12133 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12134
12135 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12136 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12137 diag::err_invalid_thread)
12138 << DeclSpec::getSpecifierName(TSCS);
12139
12140 // Check to see if this name was declared as a member previously
12141 NamedDecl *PrevDecl = 0;
12142 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12143 LookupName(Previous, S);
12144 switch (Previous.getResultKind()) {
12145 case LookupResult::Found:
12146 case LookupResult::FoundUnresolvedValue:
12147 PrevDecl = Previous.getAsSingle<NamedDecl>();
12148 break;
12149
12150 case LookupResult::FoundOverloaded:
12151 PrevDecl = Previous.getRepresentativeDecl();
12152 break;
12153
12154 case LookupResult::NotFound:
12155 case LookupResult::NotFoundInCurrentInstantiation:
12156 case LookupResult::Ambiguous:
12157 break;
12158 }
12159
12160 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12161 // Maybe we will complain about the shadowed template parameter.
12162 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12163 // Just pretend that we didn't see the previous declaration.
12164 PrevDecl = 0;
12165 }
12166
12167 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12168 PrevDecl = 0;
12169
12170 SourceLocation TSSL = D.getLocStart();
12171 MSPropertyDecl *NewPD;
12172 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12173 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12174 II, T, TInfo, TSSL,
12175 Data.GetterId, Data.SetterId);
12176 ProcessDeclAttributes(TUScope, NewPD, D);
12177 NewPD->setAccess(AS);
12178
12179 if (NewPD->isInvalidDecl())
12180 Record->setInvalidDecl();
12181
12182 if (D.getDeclSpec().isModulePrivateSpecified())
12183 NewPD->setModulePrivate();
12184
12185 if (NewPD->isInvalidDecl() && PrevDecl) {
12186 // Don't introduce NewFD into scope; there's already something
12187 // with the same name in the same scope.
12188 } else if (II) {
12189 PushOnScopeChains(NewPD, S);
12190 } else
12191 Record->addDecl(NewPD);
12192
12193 return NewPD;
12194}