blob: caf7affd0cc0e9d2563d517dd81a5b9e1c0ba4a5 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000040#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000041#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000042
43using namespace clang;
44
Chris Lattner8123a952008-04-10 02:22:51 +000045//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
Chris Lattner9e979552008-04-12 23:52:44 +000049namespace {
50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51 /// the default argument of a parameter to determine whether it
52 /// contains any ill-formed subexpressions. For example, this will
53 /// diagnose the use of local variables or parameters within the
54 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000055 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000056 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000057 Expr *DefaultArg;
58 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 public:
Mike Stump1eb44332009-09-09 15:08:12 +000061 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000062 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000063
Chris Lattner9e979552008-04-12 23:52:44 +000064 bool VisitExpr(Expr *Node);
65 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000066 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000067 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000068 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000069 };
Chris Lattner8123a952008-04-10 02:22:51 +000070
Chris Lattner9e979552008-04-12 23:52:44 +000071 /// VisitExpr - Visit all of the children of this expression.
72 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
73 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000074 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000075 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000076 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000077 }
78
Chris Lattner9e979552008-04-12 23:52:44 +000079 /// VisitDeclRefExpr - Visit a reference to a declaration, to
80 /// determine whether this declaration can be used in the default
81 /// argument expression.
82 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000083 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000084 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
85 // C++ [dcl.fct.default]p9
86 // Default arguments are evaluated each time the function is
87 // called. The order of evaluation of function arguments is
88 // unspecified. Consequently, parameters of a function shall not
89 // be used in default argument expressions, even if they are not
90 // evaluated. Parameters of a function declared before a default
91 // argument expression are in scope and can hide namespace and
92 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000093 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000094 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000095 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000096 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000097 // C++ [dcl.fct.default]p7
98 // Local variables shall not be used in default argument
99 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000100 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000101 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000102 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000103 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000104 }
Chris Lattner8123a952008-04-10 02:22:51 +0000105
Douglas Gregor3996f232008-11-04 13:41:56 +0000106 return false;
107 }
Chris Lattner9e979552008-04-12 23:52:44 +0000108
Douglas Gregor796da182008-11-04 14:32:21 +0000109 /// VisitCXXThisExpr - Visit a C++ "this" expression.
110 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
111 // C++ [dcl.fct.default]p8:
112 // The keyword this shall not be used in a default argument of a
113 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000114 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000115 diag::err_param_default_argument_references_this)
116 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000117 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000118
John McCall045d2522013-04-09 01:56:28 +0000119 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
120 bool Invalid = false;
121 for (PseudoObjectExpr::semantics_iterator
122 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
123 Expr *E = *i;
124
125 // Look through bindings.
126 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
127 E = OVE->getSourceExpr();
128 assert(E && "pseudo-object binding without source expression?");
129 }
130
131 Invalid |= Visit(E);
132 }
133 return Invalid;
134 }
135
Douglas Gregorf0459f82012-02-10 23:30:22 +0000136 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
137 // C++11 [expr.lambda.prim]p13:
138 // A lambda-expression appearing in a default argument shall not
139 // implicitly or explicitly capture any entity.
140 if (Lambda->capture_begin() == Lambda->capture_end())
141 return false;
142
143 return S->Diag(Lambda->getLocStart(),
144 diag::err_lambda_capture_default_arg);
145 }
Chris Lattner8123a952008-04-10 02:22:51 +0000146}
147
Richard Smith0b0ca472013-04-10 06:11:48 +0000148void
149Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
150 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000151 // If we have an MSAny spec already, don't bother.
152 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000153 return;
154
155 const FunctionProtoType *Proto
156 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000157 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
158 if (!Proto)
159 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000160
161 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
162
163 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000164 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000165 ClearExceptions();
166 ComputedEST = EST;
167 return;
168 }
169
Richard Smith7a614d82011-06-11 17:19:42 +0000170 // FIXME: If the call to this decl is using any of its default arguments, we
171 // need to search them for potentially-throwing calls.
172
Sean Hunt001cad92011-05-10 00:49:42 +0000173 // If this function has a basic noexcept, it doesn't affect the outcome.
174 if (EST == EST_BasicNoexcept)
175 return;
176
177 // If we have a throw-all spec at this point, ignore the function.
178 if (ComputedEST == EST_None)
179 return;
180
181 // If we're still at noexcept(true) and there's a nothrow() callee,
182 // change to that specification.
183 if (EST == EST_DynamicNone) {
184 if (ComputedEST == EST_BasicNoexcept)
185 ComputedEST = EST_DynamicNone;
186 return;
187 }
188
189 // Check out noexcept specs.
190 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000191 FunctionProtoType::NoexceptResult NR =
192 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000193 assert(NR != FunctionProtoType::NR_NoNoexcept &&
194 "Must have noexcept result for EST_ComputedNoexcept.");
195 assert(NR != FunctionProtoType::NR_Dependent &&
196 "Should not generate implicit declarations for dependent cases, "
197 "and don't know how to handle them anyway.");
198
199 // noexcept(false) -> no spec on the new function
200 if (NR == FunctionProtoType::NR_Throw) {
201 ClearExceptions();
202 ComputedEST = EST_None;
203 }
204 // noexcept(true) won't change anything either.
205 return;
206 }
207
208 assert(EST == EST_Dynamic && "EST case not considered earlier.");
209 assert(ComputedEST != EST_None &&
210 "Shouldn't collect exceptions when throw-all is guaranteed.");
211 ComputedEST = EST_Dynamic;
212 // Record the exceptions in this function's exception specification.
213 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
214 EEnd = Proto->exception_end();
215 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000217 Exceptions.push_back(*E);
218}
219
Richard Smith7a614d82011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithe6975e92012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssoned961f92009-08-25 02:29:20 +0000249bool
John McCall9ae2f072010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000271 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000273
Richard Smith6c3af3d2013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Anders Carlssoned961f92009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson9351c172009-08-25 03:18:48 +0000292 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000293}
294
Chris Lattner8123a952008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000298void
John McCalld226f652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000302 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCalld226f652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner3d1cee32008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6f526752010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlsson66e30672009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
John McCall9ae2f072010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000329}
330
Douglas Gregor61366e92008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCalld226f652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param)
343 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Anders Carlsson5e300d12009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000346}
347
Douglas Gregor72b505b2008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
John McCalld226f652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Anders Carlsson5e300d12009-06-12 16:51:40 +0000356 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Anders Carlsson5e300d12009-06-12 16:51:40 +0000358 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000359}
360
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000361/// CheckExtraCXXDefaultArguments - Check for any extra default
362/// arguments in the declarator, which is not a function declaration
363/// or definition and therefore is not permitted to have default
364/// arguments. This routine should be invoked for every declarator
365/// that is not a function declaration or definition.
366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367 // C++ [dcl.fct.default]p3
368 // A default argument expression shall be specified only in the
369 // parameter-declaration-clause of a function declaration or in a
370 // template-parameter (14.1). It shall not be specified for a
371 // parameter pack. If it is specified in a
372 // parameter-declaration-clause, it shall not occur within a
373 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000374 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000376 DeclaratorChunk &chunk = D.getTypeObject(i);
377 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000378 if (MightBeFunction) {
379 // This is a function declaration. It can have default arguments, but
380 // keep looking in case its return type is a function type with default
381 // arguments.
382 MightBeFunction = false;
383 continue;
384 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000385 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
386 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000387 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000388 if (Param->hasUnparsedDefaultArg()) {
389 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000391 << SourceRange((*Toks)[1].getLocation(),
392 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000393 delete Toks;
394 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000395 } else if (Param->getDefaultArg()) {
396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397 << Param->getDefaultArg()->getSourceRange();
398 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000399 }
400 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000401 } else if (chunk.Kind != DeclaratorChunk::Paren) {
402 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000403 }
404 }
405}
406
Craig Topper1a6eac82012-09-21 04:33:26 +0000407/// MergeCXXFunctionDecl - Merge two declarations of the same C++
408/// function, once we already know that they have the same
409/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
410/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000411bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
412 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000413 bool Invalid = false;
414
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000416 // For non-template functions, default arguments can be added in
417 // later declarations of a function in the same
418 // scope. Declarations in different scopes have completely
419 // distinct sets of default arguments. That is, declarations in
420 // inner scopes do not acquire default arguments from
421 // declarations in outer scopes, and vice versa. In a given
422 // function declaration, all parameters subsequent to a
423 // parameter with a default argument shall have default
424 // arguments supplied in this or previous declarations. A
425 // default argument shall not be redefined by a later
426 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000427 //
428 // C++ [dcl.fct.default]p6:
429 // Except for member functions of class templates, the default arguments
430 // in a member function definition that appears outside of the class
431 // definition are added to the set of default arguments provided by the
432 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000433 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
434 ParmVarDecl *OldParam = Old->getParamDecl(p);
435 ParmVarDecl *NewParam = New->getParamDecl(p);
436
James Molloy9cda03f2012-03-13 08:55:35 +0000437 bool OldParamHasDfl = OldParam->hasDefaultArg();
438 bool NewParamHasDfl = NewParam->hasDefaultArg();
439
440 NamedDecl *ND = Old;
441 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
442 // Ignore default parameters of old decl if they are not in
443 // the same scope.
444 OldParamHasDfl = false;
445
446 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000447
Francois Pichet8d051e02011-04-10 03:03:52 +0000448 unsigned DiagDefaultParamID =
449 diag::err_param_default_argument_redefinition;
450
451 // MSVC accepts that default parameters be redefined for member functions
452 // of template class. The new default parameter's value is ignored.
453 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000454 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000455 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
456 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000457 // Merge the old default argument into the new parameter.
458 NewParam->setHasInheritedDefaultArg();
459 if (OldParam->hasUninstantiatedDefaultArg())
460 NewParam->setUninstantiatedDefaultArg(
461 OldParam->getUninstantiatedDefaultArg());
462 else
463 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000464 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000465 Invalid = false;
466 }
467 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000468
Francois Pichet8cf90492011-04-10 04:58:30 +0000469 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
470 // hint here. Alternatively, we could walk the type-source information
471 // for NewParam to find the last source location in the type... but it
472 // isn't worth the effort right now. This is the kind of test case that
473 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000474 // int f(int);
475 // void g(int (*fp)(int) = f);
476 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000477 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000478 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000479
480 // Look for the function declaration where the default argument was
481 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000482 for (FunctionDecl *Older = Old->getPreviousDecl();
483 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000484 if (!Older->getParamDecl(p)->hasDefaultArg())
485 break;
486
487 OldParam = Older->getParamDecl(p);
488 }
489
490 Diag(OldParam->getLocation(), diag::note_previous_definition)
491 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000492 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000493 // Merge the old default argument into the new parameter.
494 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000495 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000496 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000497 if (OldParam->hasUninstantiatedDefaultArg())
498 NewParam->setUninstantiatedDefaultArg(
499 OldParam->getUninstantiatedDefaultArg());
500 else
John McCall3d6c1782010-05-04 01:53:42 +0000501 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000502 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000503 if (New->getDescribedFunctionTemplate()) {
504 // Paragraph 4, quoted above, only applies to non-template functions.
505 Diag(NewParam->getLocation(),
506 diag::err_param_default_argument_template_redecl)
507 << NewParam->getDefaultArgRange();
508 Diag(Old->getLocation(), diag::note_template_prev_declaration)
509 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000510 } else if (New->getTemplateSpecializationKind()
511 != TSK_ImplicitInstantiation &&
512 New->getTemplateSpecializationKind() != TSK_Undeclared) {
513 // C++ [temp.expr.spec]p21:
514 // Default function arguments shall not be specified in a declaration
515 // or a definition for one of the following explicit specializations:
516 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000517 // - the explicit specialization of a member function template;
518 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000519 // template where the class template specialization to which the
520 // member function specialization belongs is implicitly
521 // instantiated.
522 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
523 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
524 << New->getDeclName()
525 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000526 } else if (New->getDeclContext()->isDependentContext()) {
527 // C++ [dcl.fct.default]p6 (DR217):
528 // Default arguments for a member function of a class template shall
529 // be specified on the initial declaration of the member function
530 // within the class template.
531 //
532 // Reading the tea leaves a bit in DR217 and its reference to DR205
533 // leads me to the conclusion that one cannot add default function
534 // arguments for an out-of-line definition of a member function of a
535 // dependent type.
536 int WhichKind = 2;
537 if (CXXRecordDecl *Record
538 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
539 if (Record->getDescribedClassTemplate())
540 WhichKind = 0;
541 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
542 WhichKind = 1;
543 else
544 WhichKind = 2;
545 }
546
547 Diag(NewParam->getLocation(),
548 diag::err_param_default_argument_member_template_redecl)
549 << WhichKind
550 << NewParam->getDefaultArgRange();
551 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000552 }
553 }
554
Richard Smithb8abff62012-11-28 03:45:24 +0000555 // DR1344: If a default argument is added outside a class definition and that
556 // default argument makes the function a special member function, the program
557 // is ill-formed. This can only happen for constructors.
558 if (isa<CXXConstructorDecl>(New) &&
559 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
560 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
561 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
562 if (NewSM != OldSM) {
563 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
564 assert(NewParam->hasDefaultArg());
565 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
566 << NewParam->getDefaultArgRange() << NewSM;
567 Diag(Old->getLocation(), diag::note_previous_declaration);
568 }
569 }
570
Richard Smithff234882012-02-20 23:28:05 +0000571 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000572 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000573 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000574 if (New->isConstexpr() != Old->isConstexpr()) {
575 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
576 << New << New->isConstexpr();
577 Diag(Old->getLocation(), diag::note_previous_declaration);
578 Invalid = true;
579 }
580
Douglas Gregore13ad832010-02-12 07:32:17 +0000581 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000582 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000583
Douglas Gregorcda9c672009-02-16 17:45:42 +0000584 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000585}
586
Sebastian Redl60618fa2011-03-12 11:50:43 +0000587/// \brief Merge the exception specifications of two variable declarations.
588///
589/// This is called when there's a redeclaration of a VarDecl. The function
590/// checks if the redeclaration might have an exception specification and
591/// validates compatibility and merges the specs if necessary.
592void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
593 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000594 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000595 return;
596
597 assert(Context.hasSameType(New->getType(), Old->getType()) &&
598 "Should only be called if types are otherwise the same.");
599
600 QualType NewType = New->getType();
601 QualType OldType = Old->getType();
602
603 // We're only interested in pointers and references to functions, as well
604 // as pointers to member functions.
605 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
606 NewType = R->getPointeeType();
607 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
608 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
609 NewType = P->getPointeeType();
610 OldType = OldType->getAs<PointerType>()->getPointeeType();
611 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
612 NewType = M->getPointeeType();
613 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
614 }
615
616 if (!NewType->isFunctionProtoType())
617 return;
618
619 // There's lots of special cases for functions. For function pointers, system
620 // libraries are hopefully not as broken so that we don't need these
621 // workarounds.
622 if (CheckEquivalentExceptionSpec(
623 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
624 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
625 New->setInvalidDecl();
626 }
627}
628
Chris Lattner3d1cee32008-04-08 05:04:30 +0000629/// CheckCXXDefaultArguments - Verify that the default arguments for a
630/// function declaration are well-formed according to C++
631/// [dcl.fct.default].
632void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
633 unsigned NumParams = FD->getNumParams();
634 unsigned p;
635
636 // Find first parameter with a default argument
637 for (p = 0; p < NumParams; ++p) {
638 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000639 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000640 break;
641 }
642
643 // C++ [dcl.fct.default]p4:
644 // In a given function declaration, all parameters
645 // subsequent to a parameter with a default argument shall
646 // have default arguments supplied in this or previous
647 // declarations. A default argument shall not be redefined
648 // by a later declaration (not even to the same value).
649 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000650 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000651 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000652 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000653 if (Param->isInvalidDecl())
654 /* We already complained about this parameter. */;
655 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000656 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000657 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000658 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000659 else
Mike Stump1eb44332009-09-09 15:08:12 +0000660 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000661 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Chris Lattner3d1cee32008-04-08 05:04:30 +0000663 LastMissingDefaultArg = p;
664 }
665 }
666
667 if (LastMissingDefaultArg > 0) {
668 // Some default arguments were missing. Clear out all of the
669 // default arguments up to (and including) the last missing
670 // default argument, so that we leave the function parameters
671 // in a semantically valid state.
672 for (p = 0; p <= LastMissingDefaultArg; ++p) {
673 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000674 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000675 Param->setDefaultArg(0);
676 }
677 }
678 }
679}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000680
Richard Smith9f569cc2011-10-01 02:31:28 +0000681// CheckConstexprParameterTypes - Check whether a function's parameter types
682// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000683// diagnostic and return false.
684static bool CheckConstexprParameterTypes(Sema &SemaRef,
685 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000686 unsigned ArgIndex = 0;
687 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
688 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
689 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
690 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
691 SourceLocation ParamLoc = PD->getLocation();
692 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000693 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000694 diag::err_constexpr_non_literal_param,
695 ArgIndex+1, PD->getSourceRange(),
696 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000697 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000698 }
Joao Matos17d35c32012-08-31 22:18:20 +0000699 return true;
700}
701
702/// \brief Get diagnostic %select index for tag kind for
703/// record diagnostic message.
704/// WARNING: Indexes apply to particular diagnostics only!
705///
706/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000707static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000708 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000709 case TTK_Struct: return 0;
710 case TTK_Interface: return 1;
711 case TTK_Class: return 2;
712 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000713 }
Joao Matos17d35c32012-08-31 22:18:20 +0000714}
715
716// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
717// the requirements of a constexpr function definition or a constexpr
718// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000719// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000720//
Richard Smith86c3ae42012-02-13 03:54:03 +0000721// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
722bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000723 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
724 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000725 // C++11 [dcl.constexpr]p4:
726 // The definition of a constexpr constructor shall satisfy the following
727 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000728 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000729 const CXXRecordDecl *RD = MD->getParent();
730 if (RD->getNumVBases()) {
731 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
732 << isa<CXXConstructorDecl>(NewFD)
733 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
734 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
735 E = RD->vbases_end(); I != E; ++I)
736 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000737 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000738 return false;
739 }
Richard Smith35340502012-01-13 04:54:00 +0000740 }
741
742 if (!isa<CXXConstructorDecl>(NewFD)) {
743 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000744 // The definition of a constexpr function shall satisfy the following
745 // constraints:
746 // - it shall not be virtual;
747 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
748 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000749 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000750
Richard Smith86c3ae42012-02-13 03:54:03 +0000751 // If it's not obvious why this function is virtual, find an overridden
752 // function which uses the 'virtual' keyword.
753 const CXXMethodDecl *WrittenVirtual = Method;
754 while (!WrittenVirtual->isVirtualAsWritten())
755 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
756 if (WrittenVirtual != Method)
757 Diag(WrittenVirtual->getLocation(),
758 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000759 return false;
760 }
761
762 // - its return type shall be a literal type;
763 QualType RT = NewFD->getResultType();
764 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000765 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000766 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000767 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000768 }
769
Richard Smith35340502012-01-13 04:54:00 +0000770 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000771 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000772 return false;
773
Richard Smith9f569cc2011-10-01 02:31:28 +0000774 return true;
775}
776
777/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000778/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000779///
Richard Smitha10b9782013-04-22 15:31:51 +0000780/// \return true if the body is OK (maybe only as an extension), false if we
781/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000782static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000783 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
784 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000785 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
786 // contain only
787 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
788 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
789 switch ((*DclIt)->getKind()) {
790 case Decl::StaticAssert:
791 case Decl::Using:
792 case Decl::UsingShadow:
793 case Decl::UsingDirective:
794 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000795 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000796 // - static_assert-declarations
797 // - using-declarations,
798 // - using-directives,
799 continue;
800
801 case Decl::Typedef:
802 case Decl::TypeAlias: {
803 // - typedef declarations and alias-declarations that do not define
804 // classes or enumerations,
805 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
806 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
807 // Don't allow variably-modified types in constexpr functions.
808 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
809 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
810 << TL.getSourceRange() << TL.getType()
811 << isa<CXXConstructorDecl>(Dcl);
812 return false;
813 }
814 continue;
815 }
816
817 case Decl::Enum:
818 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000819 // C++1y allows types to be defined, not just declared.
820 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
821 SemaRef.Diag(DS->getLocStart(),
822 SemaRef.getLangOpts().CPlusPlus1y
823 ? diag::warn_cxx11_compat_constexpr_type_definition
824 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000825 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000826 continue;
827
Richard Smitha10b9782013-04-22 15:31:51 +0000828 case Decl::EnumConstant:
829 case Decl::IndirectField:
830 case Decl::ParmVar:
831 // These can only appear with other declarations which are banned in
832 // C++11 and permitted in C++1y, so ignore them.
833 continue;
834
835 case Decl::Var: {
836 // C++1y [dcl.constexpr]p3 allows anything except:
837 // a definition of a variable of non-literal type or of static or
838 // thread storage duration or for which no initialization is performed.
839 VarDecl *VD = cast<VarDecl>(*DclIt);
840 if (VD->isThisDeclarationADefinition()) {
841 if (VD->isStaticLocal()) {
842 SemaRef.Diag(VD->getLocation(),
843 diag::err_constexpr_local_var_static)
844 << isa<CXXConstructorDecl>(Dcl)
845 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
846 return false;
847 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000848 if (!VD->getType()->isDependentType() &&
849 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000850 VD->getLocation(), VD->getType(),
851 diag::err_constexpr_local_var_non_literal_type,
852 isa<CXXConstructorDecl>(Dcl)))
853 return false;
854 if (!VD->hasInit()) {
855 SemaRef.Diag(VD->getLocation(),
856 diag::err_constexpr_local_var_no_init)
857 << isa<CXXConstructorDecl>(Dcl);
858 return false;
859 }
860 }
861 SemaRef.Diag(VD->getLocation(),
862 SemaRef.getLangOpts().CPlusPlus1y
863 ? diag::warn_cxx11_compat_constexpr_local_var
864 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000865 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000866 continue;
867 }
868
869 case Decl::NamespaceAlias:
870 case Decl::Function:
871 // These are disallowed in C++11 and permitted in C++1y. Allow them
872 // everywhere as an extension.
873 if (!Cxx1yLoc.isValid())
874 Cxx1yLoc = DS->getLocStart();
875 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000876
877 default:
878 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
879 << isa<CXXConstructorDecl>(Dcl);
880 return false;
881 }
882 }
883
884 return true;
885}
886
887/// Check that the given field is initialized within a constexpr constructor.
888///
889/// \param Dcl The constexpr constructor being checked.
890/// \param Field The field being checked. This may be a member of an anonymous
891/// struct or union nested within the class being checked.
892/// \param Inits All declarations, including anonymous struct/union members and
893/// indirect members, for which any initialization was provided.
894/// \param Diagnosed Set to true if an error is produced.
895static void CheckConstexprCtorInitializer(Sema &SemaRef,
896 const FunctionDecl *Dcl,
897 FieldDecl *Field,
898 llvm::SmallSet<Decl*, 16> &Inits,
899 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000900 if (Field->isUnnamedBitfield())
901 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000902
903 if (Field->isAnonymousStructOrUnion() &&
904 Field->getType()->getAsCXXRecordDecl()->isEmpty())
905 return;
906
Richard Smith9f569cc2011-10-01 02:31:28 +0000907 if (!Inits.count(Field)) {
908 if (!Diagnosed) {
909 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
910 Diagnosed = true;
911 }
912 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
913 } else if (Field->isAnonymousStructOrUnion()) {
914 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
915 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
916 I != E; ++I)
917 // If an anonymous union contains an anonymous struct of which any member
918 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000919 if (!RD->isUnion() || Inits.count(*I))
920 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000921 }
922}
923
Richard Smitha10b9782013-04-22 15:31:51 +0000924/// Check the provided statement is allowed in a constexpr function
925/// definition.
926static bool
927CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
928 llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
929 SourceLocation &Cxx1yLoc) {
930 // - its function-body shall be [...] a compound-statement that contains only
931 switch (S->getStmtClass()) {
932 case Stmt::NullStmtClass:
933 // - null statements,
934 return true;
935
936 case Stmt::DeclStmtClass:
937 // - static_assert-declarations
938 // - using-declarations,
939 // - using-directives,
940 // - typedef declarations and alias-declarations that do not define
941 // classes or enumerations,
942 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
943 return false;
944 return true;
945
946 case Stmt::ReturnStmtClass:
947 // - and exactly one return statement;
948 if (isa<CXXConstructorDecl>(Dcl)) {
949 // C++1y allows return statements in constexpr constructors.
950 if (!Cxx1yLoc.isValid())
951 Cxx1yLoc = S->getLocStart();
952 return true;
953 }
954
955 ReturnStmts.push_back(S->getLocStart());
956 return true;
957
958 case Stmt::CompoundStmtClass: {
959 // C++1y allows compound-statements.
960 if (!Cxx1yLoc.isValid())
961 Cxx1yLoc = S->getLocStart();
962
963 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
964 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
965 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
966 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
967 Cxx1yLoc))
968 return false;
969 }
970 return true;
971 }
972
973 case Stmt::AttributedStmtClass:
974 if (!Cxx1yLoc.isValid())
975 Cxx1yLoc = S->getLocStart();
976 return true;
977
978 case Stmt::IfStmtClass: {
979 // C++1y allows if-statements.
980 if (!Cxx1yLoc.isValid())
981 Cxx1yLoc = S->getLocStart();
982
983 IfStmt *If = cast<IfStmt>(S);
984 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
985 Cxx1yLoc))
986 return false;
987 if (If->getElse() &&
988 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
989 Cxx1yLoc))
990 return false;
991 return true;
992 }
993
994 case Stmt::WhileStmtClass:
995 case Stmt::DoStmtClass:
996 case Stmt::ForStmtClass:
997 case Stmt::CXXForRangeStmtClass:
998 case Stmt::ContinueStmtClass:
999 // C++1y allows all of these. We don't allow them as extensions in C++11,
1000 // because they don't make sense without variable mutation.
1001 if (!SemaRef.getLangOpts().CPlusPlus1y)
1002 break;
1003 if (!Cxx1yLoc.isValid())
1004 Cxx1yLoc = S->getLocStart();
1005 for (Stmt::child_range Children = S->children(); Children; ++Children)
1006 if (*Children &&
1007 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1008 Cxx1yLoc))
1009 return false;
1010 return true;
1011
1012 case Stmt::SwitchStmtClass:
1013 case Stmt::CaseStmtClass:
1014 case Stmt::DefaultStmtClass:
1015 case Stmt::BreakStmtClass:
1016 // C++1y allows switch-statements, and since they don't need variable
1017 // mutation, we can reasonably allow them in C++11 as an extension.
1018 if (!Cxx1yLoc.isValid())
1019 Cxx1yLoc = S->getLocStart();
1020 for (Stmt::child_range Children = S->children(); Children; ++Children)
1021 if (*Children &&
1022 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1023 Cxx1yLoc))
1024 return false;
1025 return true;
1026
1027 default:
1028 if (!isa<Expr>(S))
1029 break;
1030
1031 // C++1y allows expression-statements.
1032 if (!Cxx1yLoc.isValid())
1033 Cxx1yLoc = S->getLocStart();
1034 return true;
1035 }
1036
1037 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1038 << isa<CXXConstructorDecl>(Dcl);
1039 return false;
1040}
1041
Richard Smith9f569cc2011-10-01 02:31:28 +00001042/// Check the body for the given constexpr function declaration only contains
1043/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1044///
1045/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001046bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001047 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001048 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001049 // The definition of a constexpr function shall satisfy the following
1050 // constraints: [...]
1051 // - its function-body shall be = delete, = default, or a
1052 // compound-statement
1053 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001054 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001055 // In the definition of a constexpr constructor, [...]
1056 // - its function-body shall not be a function-try-block;
1057 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1058 << isa<CXXConstructorDecl>(Dcl);
1059 return false;
1060 }
1061
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001062 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001063
1064 // - its function-body shall be [...] a compound-statement that contains only
1065 // [... list of cases ...]
1066 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1067 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001068 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1069 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001070 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1071 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001072 }
1073
Richard Smitha10b9782013-04-22 15:31:51 +00001074 if (Cxx1yLoc.isValid())
1075 Diag(Cxx1yLoc,
1076 getLangOpts().CPlusPlus1y
1077 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1078 : diag::ext_constexpr_body_invalid_stmt)
1079 << isa<CXXConstructorDecl>(Dcl);
1080
Richard Smith9f569cc2011-10-01 02:31:28 +00001081 if (const CXXConstructorDecl *Constructor
1082 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1083 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001084 // DR1359:
1085 // - every non-variant non-static data member and base class sub-object
1086 // shall be initialized;
1087 // - if the class is a non-empty union, or for each non-empty anonymous
1088 // union member of a non-union class, exactly one non-static data member
1089 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001090 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001091 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001092 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1093 return false;
1094 }
Richard Smith6e433752011-10-10 16:38:04 +00001095 } else if (!Constructor->isDependentContext() &&
1096 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001097 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1098
1099 // Skip detailed checking if we have enough initializers, and we would
1100 // allow at most one initializer per member.
1101 bool AnyAnonStructUnionMembers = false;
1102 unsigned Fields = 0;
1103 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1104 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001105 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001106 AnyAnonStructUnionMembers = true;
1107 break;
1108 }
1109 }
1110 if (AnyAnonStructUnionMembers ||
1111 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1112 // Check initialization of non-static data members. Base classes are
1113 // always initialized so do not need to be checked. Dependent bases
1114 // might not have initializers in the member initializer list.
1115 llvm::SmallSet<Decl*, 16> Inits;
1116 for (CXXConstructorDecl::init_const_iterator
1117 I = Constructor->init_begin(), E = Constructor->init_end();
1118 I != E; ++I) {
1119 if (FieldDecl *FD = (*I)->getMember())
1120 Inits.insert(FD);
1121 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1122 Inits.insert(ID->chain_begin(), ID->chain_end());
1123 }
1124
1125 bool Diagnosed = false;
1126 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1127 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001128 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001129 if (Diagnosed)
1130 return false;
1131 }
1132 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001133 } else {
1134 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001135 // C++1y doesn't require constexpr functions to contain a 'return'
1136 // statement. We still do, unless the return type is void, because
1137 // otherwise if there's no return statement, the function cannot
1138 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001139 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001140 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001141 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1142 : diag::err_constexpr_body_no_return);
1143 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001144 }
1145 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001146 Diag(ReturnStmts.back(),
1147 getLangOpts().CPlusPlus1y
1148 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1149 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001150 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1151 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001152 }
1153 }
1154
Richard Smith5ba73e12012-02-04 00:33:54 +00001155 // C++11 [dcl.constexpr]p5:
1156 // if no function argument values exist such that the function invocation
1157 // substitution would produce a constant expression, the program is
1158 // ill-formed; no diagnostic required.
1159 // C++11 [dcl.constexpr]p3:
1160 // - every constructor call and implicit conversion used in initializing the
1161 // return value shall be one of those allowed in a constant expression.
1162 // C++11 [dcl.constexpr]p4:
1163 // - every constructor involved in initializing non-static data members and
1164 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001165 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001166 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001167 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001168 << isa<CXXConstructorDecl>(Dcl);
1169 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1170 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001171 // Don't return false here: we allow this for compatibility in
1172 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001173 }
1174
Richard Smith9f569cc2011-10-01 02:31:28 +00001175 return true;
1176}
1177
Douglas Gregorb48fe382008-10-31 09:07:45 +00001178/// isCurrentClassName - Determine whether the identifier II is the
1179/// name of the class type currently being defined. In the case of
1180/// nested classes, this will only return true if II is the name of
1181/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001182bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1183 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001184 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001185
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001186 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001187 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001188 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001189 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1190 } else
1191 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1192
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001193 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001194 return &II == CurDecl->getIdentifier();
1195 else
1196 return false;
1197}
1198
Douglas Gregor229d47a2012-11-10 07:24:09 +00001199/// \brief Determine whether the given class is a base class of the given
1200/// class, including looking at dependent bases.
1201static bool findCircularInheritance(const CXXRecordDecl *Class,
1202 const CXXRecordDecl *Current) {
1203 SmallVector<const CXXRecordDecl*, 8> Queue;
1204
1205 Class = Class->getCanonicalDecl();
1206 while (true) {
1207 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1208 E = Current->bases_end();
1209 I != E; ++I) {
1210 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1211 if (!Base)
1212 continue;
1213
1214 Base = Base->getDefinition();
1215 if (!Base)
1216 continue;
1217
1218 if (Base->getCanonicalDecl() == Class)
1219 return true;
1220
1221 Queue.push_back(Base);
1222 }
1223
1224 if (Queue.empty())
1225 return false;
1226
1227 Current = Queue.back();
1228 Queue.pop_back();
1229 }
1230
1231 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001232}
1233
Mike Stump1eb44332009-09-09 15:08:12 +00001234/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001235///
1236/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1237/// and returns NULL otherwise.
1238CXXBaseSpecifier *
1239Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1240 SourceRange SpecifierRange,
1241 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001242 TypeSourceInfo *TInfo,
1243 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001244 QualType BaseType = TInfo->getType();
1245
Douglas Gregor2943aed2009-03-03 04:44:36 +00001246 // C++ [class.union]p1:
1247 // A union shall not have base classes.
1248 if (Class->isUnion()) {
1249 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1250 << SpecifierRange;
1251 return 0;
1252 }
1253
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001254 if (EllipsisLoc.isValid() &&
1255 !TInfo->getType()->containsUnexpandedParameterPack()) {
1256 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1257 << TInfo->getTypeLoc().getSourceRange();
1258 EllipsisLoc = SourceLocation();
1259 }
Douglas Gregord777e282012-11-10 01:18:17 +00001260
1261 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1262
1263 if (BaseType->isDependentType()) {
1264 // Make sure that we don't have circular inheritance among our dependent
1265 // bases. For non-dependent bases, the check for completeness below handles
1266 // this.
1267 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1268 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1269 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001270 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001271 Diag(BaseLoc, diag::err_circular_inheritance)
1272 << BaseType << Context.getTypeDeclType(Class);
1273
1274 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1275 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1276 << BaseType;
1277
1278 return 0;
1279 }
1280 }
1281
Mike Stump1eb44332009-09-09 15:08:12 +00001282 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001283 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001284 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001285 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001286
1287 // Base specifiers must be record types.
1288 if (!BaseType->isRecordType()) {
1289 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1290 return 0;
1291 }
1292
1293 // C++ [class.union]p1:
1294 // A union shall not be used as a base class.
1295 if (BaseType->isUnionType()) {
1296 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1297 return 0;
1298 }
1299
1300 // C++ [class.derived]p2:
1301 // The class-name in a base-specifier shall not be an incompletely
1302 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001303 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001304 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001305 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001306 return 0;
John McCall572fc622010-08-17 07:23:57 +00001307 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001308
Eli Friedman1d954f62009-08-15 21:55:26 +00001309 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001310 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001311 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001312 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001313 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer2f686692013-06-22 06:43:58 +00001314 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001315 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001316
Anders Carlsson1d209272011-03-25 14:55:14 +00001317 // C++ [class]p3:
1318 // If a class is marked final and it appears as a base-type-specifier in
1319 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001320 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001321 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1322 << CXXBaseDecl->getDeclName();
1323 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1324 << CXXBaseDecl->getDeclName();
1325 return 0;
1326 }
1327
John McCall572fc622010-08-17 07:23:57 +00001328 if (BaseDecl->isInvalidDecl())
1329 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001330
1331 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001332 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001333 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001334 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001335}
1336
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001337/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1338/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001339/// example:
1340/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001341/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001342BaseResult
John McCalld226f652010-08-21 09:40:31 +00001343Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001344 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001345 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001346 ParsedType basetype, SourceLocation BaseLoc,
1347 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001348 if (!classdecl)
1349 return true;
1350
Douglas Gregor40808ce2009-03-09 23:48:35 +00001351 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001352 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001353 if (!Class)
1354 return true;
1355
Richard Smith05321402013-02-19 23:47:15 +00001356 // We do not support any C++11 attributes on base-specifiers yet.
1357 // Diagnose any attributes we see.
1358 if (!Attributes.empty()) {
1359 for (AttributeList *Attr = Attributes.getList(); Attr;
1360 Attr = Attr->getNext()) {
1361 if (Attr->isInvalid() ||
1362 Attr->getKind() == AttributeList::IgnoredAttribute)
1363 continue;
1364 Diag(Attr->getLoc(),
1365 Attr->getKind() == AttributeList::UnknownAttribute
1366 ? diag::warn_unknown_attribute_ignored
1367 : diag::err_base_specifier_attribute)
1368 << Attr->getName();
1369 }
1370 }
1371
Nick Lewycky56062202010-07-26 16:56:01 +00001372 TypeSourceInfo *TInfo = 0;
1373 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001374
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001375 if (EllipsisLoc.isInvalid() &&
1376 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001377 UPPC_BaseType))
1378 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001379
Douglas Gregor2943aed2009-03-03 04:44:36 +00001380 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001381 Virtual, Access, TInfo,
1382 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001383 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001384 else
1385 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Douglas Gregor2943aed2009-03-03 04:44:36 +00001387 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001388}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001389
Douglas Gregor2943aed2009-03-03 04:44:36 +00001390/// \brief Performs the actual work of attaching the given base class
1391/// specifiers to a C++ class.
1392bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1393 unsigned NumBases) {
1394 if (NumBases == 0)
1395 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001396
1397 // Used to keep track of which base types we have already seen, so
1398 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001399 // that the key is always the unqualified canonical type of the base
1400 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001401 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1402
1403 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001404 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001405 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001406 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001407 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001408 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001409 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001410
1411 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1412 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001413 // C++ [class.mi]p3:
1414 // A class shall not be specified as a direct base class of a
1415 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001416 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001417 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001418 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001419 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001420
1421 // Delete the duplicate base class specifier; we're going to
1422 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001423 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001424
1425 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001426 } else {
1427 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001428 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001429 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001430 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1431 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1432 if (Class->isInterface() &&
1433 (!RD->isInterface() ||
1434 KnownBase->getAccessSpecifier() != AS_public)) {
1435 // The Microsoft extension __interface does not permit bases that
1436 // are not themselves public interfaces.
1437 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1438 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1439 << RD->getSourceRange();
1440 Invalid = true;
1441 }
1442 if (RD->hasAttr<WeakAttr>())
1443 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1444 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001445 }
1446 }
1447
1448 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001449 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001450
1451 // Delete the remaining (good) base class specifiers, since their
1452 // data has been copied into the CXXRecordDecl.
1453 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001454 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001455
1456 return Invalid;
1457}
1458
1459/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1460/// class, after checking whether there are any duplicate base
1461/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001462void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001463 unsigned NumBases) {
1464 if (!ClassDecl || !Bases || !NumBases)
1465 return;
1466
1467 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001468 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001469 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001470}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001471
Douglas Gregora8f32e02009-10-06 17:59:45 +00001472/// \brief Determine whether the type \p Derived is a C++ class that is
1473/// derived from the type \p Base.
1474bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001475 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001476 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001477
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001478 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001479 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001480 return false;
1481
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001482 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001483 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001484 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001485
1486 // If either the base or the derived type is invalid, don't try to
1487 // check whether one is derived from the other.
1488 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1489 return false;
1490
John McCall86ff3082010-02-04 22:26:26 +00001491 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1492 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001493}
1494
1495/// \brief Determine whether the type \p Derived is a C++ class that is
1496/// derived from the type \p Base.
1497bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001498 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001499 return false;
1500
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001501 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001502 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001503 return false;
1504
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001505 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001506 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001507 return false;
1508
Douglas Gregora8f32e02009-10-06 17:59:45 +00001509 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1510}
1511
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001512void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001513 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001514 assert(BasePathArray.empty() && "Base path array must be empty!");
1515 assert(Paths.isRecordingPaths() && "Must record paths!");
1516
1517 const CXXBasePath &Path = Paths.front();
1518
1519 // We first go backward and check if we have a virtual base.
1520 // FIXME: It would be better if CXXBasePath had the base specifier for
1521 // the nearest virtual base.
1522 unsigned Start = 0;
1523 for (unsigned I = Path.size(); I != 0; --I) {
1524 if (Path[I - 1].Base->isVirtual()) {
1525 Start = I - 1;
1526 break;
1527 }
1528 }
1529
1530 // Now add all bases.
1531 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001532 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001533}
1534
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001535/// \brief Determine whether the given base path includes a virtual
1536/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001537bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1538 for (CXXCastPath::const_iterator B = BasePath.begin(),
1539 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001540 B != BEnd; ++B)
1541 if ((*B)->isVirtual())
1542 return true;
1543
1544 return false;
1545}
1546
Douglas Gregora8f32e02009-10-06 17:59:45 +00001547/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1548/// conversion (where Derived and Base are class types) is
1549/// well-formed, meaning that the conversion is unambiguous (and
1550/// that all of the base classes are accessible). Returns true
1551/// and emits a diagnostic if the code is ill-formed, returns false
1552/// otherwise. Loc is the location where this routine should point to
1553/// if there is an error, and Range is the source range to highlight
1554/// if there is an error.
1555bool
1556Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001557 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001558 unsigned AmbigiousBaseConvID,
1559 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001560 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001561 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001562 // First, determine whether the path from Derived to Base is
1563 // ambiguous. This is slightly more expensive than checking whether
1564 // the Derived to Base conversion exists, because here we need to
1565 // explore multiple paths to determine if there is an ambiguity.
1566 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1567 /*DetectVirtual=*/false);
1568 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1569 assert(DerivationOkay &&
1570 "Can only be used with a derived-to-base conversion");
1571 (void)DerivationOkay;
1572
1573 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001574 if (InaccessibleBaseID) {
1575 // Check that the base class can be accessed.
1576 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1577 InaccessibleBaseID)) {
1578 case AR_inaccessible:
1579 return true;
1580 case AR_accessible:
1581 case AR_dependent:
1582 case AR_delayed:
1583 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001584 }
John McCall6b2accb2010-02-10 09:31:12 +00001585 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001586
1587 // Build a base path if necessary.
1588 if (BasePath)
1589 BuildBasePathArray(Paths, *BasePath);
1590 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001591 }
1592
David Majnemer2f686692013-06-22 06:43:58 +00001593 if (AmbigiousBaseConvID) {
1594 // We know that the derived-to-base conversion is ambiguous, and
1595 // we're going to produce a diagnostic. Perform the derived-to-base
1596 // search just one more time to compute all of the possible paths so
1597 // that we can print them out. This is more expensive than any of
1598 // the previous derived-to-base checks we've done, but at this point
1599 // performance isn't as much of an issue.
1600 Paths.clear();
1601 Paths.setRecordingPaths(true);
1602 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1603 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1604 (void)StillOkay;
1605
1606 // Build up a textual representation of the ambiguous paths, e.g.,
1607 // D -> B -> A, that will be used to illustrate the ambiguous
1608 // conversions in the diagnostic. We only print one of the paths
1609 // to each base class subobject.
1610 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1611
1612 Diag(Loc, AmbigiousBaseConvID)
1613 << Derived << Base << PathDisplayStr << Range << Name;
1614 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001615 return true;
1616}
1617
1618bool
1619Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001620 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001621 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001622 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001623 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001624 IgnoreAccess ? 0
1625 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001626 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001627 Loc, Range, DeclarationName(),
1628 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001629}
1630
1631
1632/// @brief Builds a string representing ambiguous paths from a
1633/// specific derived class to different subobjects of the same base
1634/// class.
1635///
1636/// This function builds a string that can be used in error messages
1637/// to show the different paths that one can take through the
1638/// inheritance hierarchy to go from the derived class to different
1639/// subobjects of a base class. The result looks something like this:
1640/// @code
1641/// struct D -> struct B -> struct A
1642/// struct D -> struct C -> struct A
1643/// @endcode
1644std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1645 std::string PathDisplayStr;
1646 std::set<unsigned> DisplayedPaths;
1647 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1648 Path != Paths.end(); ++Path) {
1649 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1650 // We haven't displayed a path to this particular base
1651 // class subobject yet.
1652 PathDisplayStr += "\n ";
1653 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1654 for (CXXBasePath::const_iterator Element = Path->begin();
1655 Element != Path->end(); ++Element)
1656 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1657 }
1658 }
1659
1660 return PathDisplayStr;
1661}
1662
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001663//===----------------------------------------------------------------------===//
1664// C++ class member Handling
1665//===----------------------------------------------------------------------===//
1666
Abramo Bagnara6206d532010-06-05 05:09:32 +00001667/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001668bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1669 SourceLocation ASLoc,
1670 SourceLocation ColonLoc,
1671 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001672 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001673 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001674 ASLoc, ColonLoc);
1675 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001676 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001677}
1678
Richard Smitha4b39652012-08-06 03:25:17 +00001679/// CheckOverrideControl - Check C++11 override control semantics.
1680void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001681 if (D->isInvalidDecl())
1682 return;
1683
Chris Lattner5f9e2722011-07-23 10:55:15 +00001684 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001685
Richard Smitha4b39652012-08-06 03:25:17 +00001686 // Do we know which functions this declaration might be overriding?
1687 bool OverridesAreKnown = !MD ||
1688 (!MD->getParent()->hasAnyDependentBases() &&
1689 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001690
Richard Smitha4b39652012-08-06 03:25:17 +00001691 if (!MD || !MD->isVirtual()) {
1692 if (OverridesAreKnown) {
1693 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1694 Diag(OA->getLocation(),
1695 diag::override_keyword_only_allowed_on_virtual_member_functions)
1696 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1697 D->dropAttr<OverrideAttr>();
1698 }
1699 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1700 Diag(FA->getLocation(),
1701 diag::override_keyword_only_allowed_on_virtual_member_functions)
1702 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1703 D->dropAttr<FinalAttr>();
1704 }
1705 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001706 return;
1707 }
Richard Smitha4b39652012-08-06 03:25:17 +00001708
1709 if (!OverridesAreKnown)
1710 return;
1711
1712 // C++11 [class.virtual]p5:
1713 // If a virtual function is marked with the virt-specifier override and
1714 // does not override a member function of a base class, the program is
1715 // ill-formed.
1716 bool HasOverriddenMethods =
1717 MD->begin_overridden_methods() != MD->end_overridden_methods();
1718 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1719 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1720 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001721}
1722
Richard Smitha4b39652012-08-06 03:25:17 +00001723/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001724/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001725/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001726bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1727 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001728 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001729 return false;
1730
1731 Diag(New->getLocation(), diag::err_final_function_overridden)
1732 << New->getDeclName();
1733 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1734 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001735}
1736
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001737static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001738 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1739 // FIXME: Destruction of ObjC lifetime types has side-effects.
1740 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1741 return !RD->isCompleteDefinition() ||
1742 !RD->hasTrivialDefaultConstructor() ||
1743 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001744 return false;
1745}
1746
John McCall76da55d2013-04-16 07:28:30 +00001747static AttributeList *getMSPropertyAttr(AttributeList *list) {
1748 for (AttributeList* it = list; it != 0; it = it->getNext())
1749 if (it->isDeclspecPropertyAttribute())
1750 return it;
1751 return 0;
1752}
1753
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001754/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1755/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001756/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001757/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1758/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001759NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001760Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001761 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001762 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001763 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001764 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001765 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1766 DeclarationName Name = NameInfo.getName();
1767 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001768
1769 // For anonymous bitfields, the location should point to the type.
1770 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001771 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001772
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001773 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001774
John McCall4bde1e12010-06-04 08:34:12 +00001775 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001776 assert(!DS.isFriendSpecified());
1777
Richard Smith1ab0d902011-06-25 02:28:38 +00001778 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001779
John McCalle402e722012-09-25 07:32:39 +00001780 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1781 // The Microsoft extension __interface only permits public member functions
1782 // and prohibits constructors, destructors, operators, non-public member
1783 // functions, static methods and data members.
1784 unsigned InvalidDecl;
1785 bool ShowDeclName = true;
1786 if (!isFunc)
1787 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1788 else if (AS != AS_public)
1789 InvalidDecl = 2;
1790 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1791 InvalidDecl = 3;
1792 else switch (Name.getNameKind()) {
1793 case DeclarationName::CXXConstructorName:
1794 InvalidDecl = 4;
1795 ShowDeclName = false;
1796 break;
1797
1798 case DeclarationName::CXXDestructorName:
1799 InvalidDecl = 5;
1800 ShowDeclName = false;
1801 break;
1802
1803 case DeclarationName::CXXOperatorName:
1804 case DeclarationName::CXXConversionFunctionName:
1805 InvalidDecl = 6;
1806 break;
1807
1808 default:
1809 InvalidDecl = 0;
1810 break;
1811 }
1812
1813 if (InvalidDecl) {
1814 if (ShowDeclName)
1815 Diag(Loc, diag::err_invalid_member_in_interface)
1816 << (InvalidDecl-1) << Name;
1817 else
1818 Diag(Loc, diag::err_invalid_member_in_interface)
1819 << (InvalidDecl-1) << "";
1820 return 0;
1821 }
1822 }
1823
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001824 // C++ 9.2p6: A member shall not be declared to have automatic storage
1825 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001826 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1827 // data members and cannot be applied to names declared const or static,
1828 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001829 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001830 case DeclSpec::SCS_unspecified:
1831 case DeclSpec::SCS_typedef:
1832 case DeclSpec::SCS_static:
1833 break;
1834 case DeclSpec::SCS_mutable:
1835 if (isFunc) {
1836 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001837
Richard Smithec642442013-04-12 22:46:28 +00001838 // FIXME: It would be nicer if the keyword was ignored only for this
1839 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001840 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001841 }
1842 break;
1843 default:
1844 Diag(DS.getStorageClassSpecLoc(),
1845 diag::err_storageclass_invalid_for_member);
1846 D.getMutableDeclSpec().ClearStorageClassSpecs();
1847 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001848 }
1849
Sebastian Redl669d5d72008-11-14 23:42:31 +00001850 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1851 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001852 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001853
David Blaikie1d87fba2013-01-30 01:22:18 +00001854 if (DS.isConstexprSpecified() && isInstField) {
1855 SemaDiagnosticBuilder B =
1856 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1857 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1858 if (InitStyle == ICIS_NoInit) {
1859 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1860 D.getMutableDeclSpec().ClearConstexprSpec();
1861 const char *PrevSpec;
1862 unsigned DiagID;
1863 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1864 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001865 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001866 assert(!Failed && "Making a constexpr member const shouldn't fail");
1867 } else {
1868 B << 1;
1869 const char *PrevSpec;
1870 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001871 if (D.getMutableDeclSpec().SetStorageClassSpec(
1872 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001873 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001874 "This is the only DeclSpec that should fail to be applied");
1875 B << 1;
1876 } else {
1877 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1878 isInstField = false;
1879 }
1880 }
1881 }
1882
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001883 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001884 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001885 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001886
1887 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001888 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001889 Diag(Loc, diag::err_bad_variable_name)
1890 << Name;
1891 return 0;
1892 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001893
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001894 IdentifierInfo *II = Name.getAsIdentifierInfo();
1895
Douglas Gregorf2503652011-09-21 14:40:46 +00001896 // Member field could not be with "template" keyword.
1897 // So TemplateParameterLists should be empty in this case.
1898 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001899 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001900 if (TemplateParams->size()) {
1901 // There is no such thing as a member field template.
1902 Diag(D.getIdentifierLoc(), diag::err_template_member)
1903 << II
1904 << SourceRange(TemplateParams->getTemplateLoc(),
1905 TemplateParams->getRAngleLoc());
1906 } else {
1907 // There is an extraneous 'template<>' for this member.
1908 Diag(TemplateParams->getTemplateLoc(),
1909 diag::err_template_member_noparams)
1910 << II
1911 << SourceRange(TemplateParams->getTemplateLoc(),
1912 TemplateParams->getRAngleLoc());
1913 }
1914 return 0;
1915 }
1916
Douglas Gregor922fff22010-10-13 22:19:53 +00001917 if (SS.isSet() && !SS.isInvalid()) {
1918 // The user provided a superfluous scope specifier inside a class
1919 // definition:
1920 //
1921 // class X {
1922 // int X::member;
1923 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001924 if (DeclContext *DC = computeDeclContext(SS, false))
1925 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001926 else
1927 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1928 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001929
Douglas Gregor922fff22010-10-13 22:19:53 +00001930 SS.clear();
1931 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001932
John McCall76da55d2013-04-16 07:28:30 +00001933 AttributeList *MSPropertyAttr =
1934 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1935 if (MSPropertyAttr) {
1936 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1937 BitWidth, InitStyle, AS, MSPropertyAttr);
1938 isInstField = false;
1939 } else {
1940 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1941 BitWidth, InitStyle, AS);
1942 }
Chris Lattner6f8ce142009-03-05 23:03:49 +00001943 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001944 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001945 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001946
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001947 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001948 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001949 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001950 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001951
1952 // Non-instance-fields can't have a bitfield.
1953 if (BitWidth) {
1954 if (Member->isInvalidDecl()) {
1955 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001956 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001957 // C++ 9.6p3: A bit-field shall not be a static member.
1958 // "static member 'A' cannot be a bit-field"
1959 Diag(Loc, diag::err_static_not_bitfield)
1960 << Name << BitWidth->getSourceRange();
1961 } else if (isa<TypedefDecl>(Member)) {
1962 // "typedef member 'x' cannot be a bit-field"
1963 Diag(Loc, diag::err_typedef_not_bitfield)
1964 << Name << BitWidth->getSourceRange();
1965 } else {
1966 // A function typedef ("typedef int f(); f a;").
1967 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1968 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001969 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001970 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001971 }
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Chris Lattner8b963ef2009-03-05 23:01:03 +00001973 BitWidth = 0;
1974 Member->setInvalidDecl();
1975 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001976
1977 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Douglas Gregor37b372b2009-08-20 22:52:58 +00001979 // If we have declared a member function template, set the access of the
1980 // templated declaration as well.
1981 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1982 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001983 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001984
Richard Smitha4b39652012-08-06 03:25:17 +00001985 if (VS.isOverrideSpecified())
1986 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1987 if (VS.isFinalSpecified())
1988 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001989
Douglas Gregorf5251602011-03-08 17:10:18 +00001990 if (VS.getLastLocation().isValid()) {
1991 // Update the end location of a method that has a virt-specifiers.
1992 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1993 MD->setRangeEnd(VS.getLastLocation());
1994 }
Richard Smitha4b39652012-08-06 03:25:17 +00001995
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001996 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001997
Douglas Gregor10bd3682008-11-17 22:58:34 +00001998 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001999
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002000 if (isInstField) {
2001 FieldDecl *FD = cast<FieldDecl>(Member);
2002 FieldCollector->Add(FD);
2003
2004 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2005 FD->getLocation())
2006 != DiagnosticsEngine::Ignored) {
2007 // Remember all explicit private FieldDecls that have a name, no side
2008 // effects and are not part of a dependent type declaration.
2009 if (!FD->isImplicit() && FD->getDeclName() &&
2010 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002011 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002012 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002013 !InitializationHasSideEffects(*FD))
2014 UnusedPrivateFields.insert(FD);
2015 }
2016 }
2017
John McCalld226f652010-08-21 09:40:31 +00002018 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002019}
2020
Hans Wennborg471f9852012-09-18 15:58:06 +00002021namespace {
2022 class UninitializedFieldVisitor
2023 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2024 Sema &S;
2025 ValueDecl *VD;
2026 public:
2027 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2028 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002029 S(S) {
2030 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2031 this->VD = IFD->getAnonField();
2032 else
2033 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002034 }
2035
2036 void HandleExpr(Expr *E) {
2037 if (!E) return;
2038
2039 // Expressions like x(x) sometimes lack the surrounding expressions
2040 // but need to be checked anyways.
2041 HandleValue(E);
2042 Visit(E);
2043 }
2044
2045 void HandleValue(Expr *E) {
2046 E = E->IgnoreParens();
2047
2048 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2049 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002050 return;
2051
2052 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2053 // or union.
2054 MemberExpr *FieldME = ME;
2055
Hans Wennborg471f9852012-09-18 15:58:06 +00002056 Expr *Base = E;
2057 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002058 ME = cast<MemberExpr>(Base);
2059
2060 if (isa<VarDecl>(ME->getMemberDecl()))
2061 return;
2062
2063 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2064 if (!FD->isAnonymousStructOrUnion())
2065 FieldME = ME;
2066
Hans Wennborg471f9852012-09-18 15:58:06 +00002067 Base = ME->getBase();
2068 }
2069
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002070 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00002071 unsigned diag = VD->getType()->isReferenceType()
2072 ? diag::warn_reference_field_is_uninit
2073 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002074 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002075 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002076 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002077 }
2078
2079 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2080 HandleValue(CO->getTrueExpr());
2081 HandleValue(CO->getFalseExpr());
2082 return;
2083 }
2084
2085 if (BinaryConditionalOperator *BCO =
2086 dyn_cast<BinaryConditionalOperator>(E)) {
2087 HandleValue(BCO->getCommon());
2088 HandleValue(BCO->getFalseExpr());
2089 return;
2090 }
2091
2092 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2093 switch (BO->getOpcode()) {
2094 default:
2095 return;
2096 case(BO_PtrMemD):
2097 case(BO_PtrMemI):
2098 HandleValue(BO->getLHS());
2099 return;
2100 case(BO_Comma):
2101 HandleValue(BO->getRHS());
2102 return;
2103 }
2104 }
2105 }
2106
2107 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2108 if (E->getCastKind() == CK_LValueToRValue)
2109 HandleValue(E->getSubExpr());
2110
2111 Inherited::VisitImplicitCastExpr(E);
2112 }
2113
2114 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2115 Expr *Callee = E->getCallee();
2116 if (isa<MemberExpr>(Callee))
2117 HandleValue(Callee);
2118
2119 Inherited::VisitCXXMemberCallExpr(E);
2120 }
2121 };
2122 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2123 ValueDecl *VD) {
2124 UninitializedFieldVisitor(S, VD).HandleExpr(E);
2125 }
2126} // namespace
2127
Richard Smith7a614d82011-06-11 17:19:42 +00002128/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002129/// in-class initializer for a non-static C++ class member, and after
2130/// instantiating an in-class initializer in a class template. Such actions
2131/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002132void
Richard Smithca523302012-06-10 03:12:00 +00002133Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002134 Expr *InitExpr) {
2135 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002136 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2137 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002138
2139 if (!InitExpr) {
2140 FD->setInvalidDecl();
2141 FD->removeInClassInitializer();
2142 return;
2143 }
2144
Peter Collingbournefef21892011-10-23 18:59:44 +00002145 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2146 FD->setInvalidDecl();
2147 FD->removeInClassInitializer();
2148 return;
2149 }
2150
Hans Wennborg471f9852012-09-18 15:58:06 +00002151 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2152 != DiagnosticsEngine::Ignored) {
2153 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2154 }
2155
Richard Smith7a614d82011-06-11 17:19:42 +00002156 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002157 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002158 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002159 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002160 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002161 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002162 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2163 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002164 if (Init.isInvalid()) {
2165 FD->setInvalidDecl();
2166 return;
2167 }
Richard Smith7a614d82011-06-11 17:19:42 +00002168 }
2169
Richard Smith41956372013-01-14 22:39:08 +00002170 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002171 // The initialization of each base and member constitutes a
2172 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002173 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002174 if (Init.isInvalid()) {
2175 FD->setInvalidDecl();
2176 return;
2177 }
2178
2179 InitExpr = Init.release();
2180
2181 FD->setInClassInitializer(InitExpr);
2182}
2183
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002184/// \brief Find the direct and/or virtual base specifiers that
2185/// correspond to the given base type, for use in base initialization
2186/// within a constructor.
2187static bool FindBaseInitializer(Sema &SemaRef,
2188 CXXRecordDecl *ClassDecl,
2189 QualType BaseType,
2190 const CXXBaseSpecifier *&DirectBaseSpec,
2191 const CXXBaseSpecifier *&VirtualBaseSpec) {
2192 // First, check for a direct base class.
2193 DirectBaseSpec = 0;
2194 for (CXXRecordDecl::base_class_const_iterator Base
2195 = ClassDecl->bases_begin();
2196 Base != ClassDecl->bases_end(); ++Base) {
2197 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2198 // We found a direct base of this type. That's what we're
2199 // initializing.
2200 DirectBaseSpec = &*Base;
2201 break;
2202 }
2203 }
2204
2205 // Check for a virtual base class.
2206 // FIXME: We might be able to short-circuit this if we know in advance that
2207 // there are no virtual bases.
2208 VirtualBaseSpec = 0;
2209 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2210 // We haven't found a base yet; search the class hierarchy for a
2211 // virtual base class.
2212 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2213 /*DetectVirtual=*/false);
2214 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2215 BaseType, Paths)) {
2216 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2217 Path != Paths.end(); ++Path) {
2218 if (Path->back().Base->isVirtual()) {
2219 VirtualBaseSpec = Path->back().Base;
2220 break;
2221 }
2222 }
2223 }
2224 }
2225
2226 return DirectBaseSpec || VirtualBaseSpec;
2227}
2228
Sebastian Redl6df65482011-09-24 17:48:25 +00002229/// \brief Handle a C++ member initializer using braced-init-list syntax.
2230MemInitResult
2231Sema::ActOnMemInitializer(Decl *ConstructorD,
2232 Scope *S,
2233 CXXScopeSpec &SS,
2234 IdentifierInfo *MemberOrBase,
2235 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002236 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002237 SourceLocation IdLoc,
2238 Expr *InitList,
2239 SourceLocation EllipsisLoc) {
2240 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002241 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002242 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002243}
2244
2245/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002246MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002247Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002248 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002249 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002250 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002251 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002252 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002253 SourceLocation IdLoc,
2254 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002255 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002256 SourceLocation RParenLoc,
2257 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002258 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002259 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002260 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002261 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002262}
2263
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002264namespace {
2265
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002266// Callback to only accept typo corrections that can be a valid C++ member
2267// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002268class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2269 public:
2270 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2271 : ClassDecl(ClassDecl) {}
2272
2273 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2274 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2275 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2276 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2277 else
2278 return isa<TypeDecl>(ND);
2279 }
2280 return false;
2281 }
2282
2283 private:
2284 CXXRecordDecl *ClassDecl;
2285};
2286
2287}
2288
Sebastian Redl6df65482011-09-24 17:48:25 +00002289/// \brief Handle a C++ member initializer.
2290MemInitResult
2291Sema::BuildMemInitializer(Decl *ConstructorD,
2292 Scope *S,
2293 CXXScopeSpec &SS,
2294 IdentifierInfo *MemberOrBase,
2295 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002296 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002297 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002298 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002299 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002300 if (!ConstructorD)
2301 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002302
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002303 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002304
2305 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002306 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002307 if (!Constructor) {
2308 // The user wrote a constructor initializer on a function that is
2309 // not a C++ constructor. Ignore the error for now, because we may
2310 // have more member initializers coming; we'll diagnose it just
2311 // once in ActOnMemInitializers.
2312 return true;
2313 }
2314
2315 CXXRecordDecl *ClassDecl = Constructor->getParent();
2316
2317 // C++ [class.base.init]p2:
2318 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002319 // constructor's class and, if not found in that scope, are looked
2320 // up in the scope containing the constructor's definition.
2321 // [Note: if the constructor's class contains a member with the
2322 // same name as a direct or virtual base class of the class, a
2323 // mem-initializer-id naming the member or base class and composed
2324 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002325 // mem-initializer-id for the hidden base class may be specified
2326 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002327 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002328 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002329 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002330 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002331 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002332 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002333 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2334 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002335 if (EllipsisLoc.isValid())
2336 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002337 << MemberOrBase
2338 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002339
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002340 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002341 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002342 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002343 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002344 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002345 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002346 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002347
2348 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002349 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002350 } else if (DS.getTypeSpecType() == TST_decltype) {
2351 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002352 } else {
2353 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2354 LookupParsedName(R, S, &SS);
2355
2356 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2357 if (!TyD) {
2358 if (R.isAmbiguous()) return true;
2359
John McCallfd225442010-04-09 19:01:14 +00002360 // We don't want access-control diagnostics here.
2361 R.suppressDiagnostics();
2362
Douglas Gregor7a886e12010-01-19 06:46:48 +00002363 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2364 bool NotUnknownSpecialization = false;
2365 DeclContext *DC = computeDeclContext(SS, false);
2366 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2367 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2368
2369 if (!NotUnknownSpecialization) {
2370 // When the scope specifier can refer to a member of an unknown
2371 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002372 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2373 SS.getWithLocInContext(Context),
2374 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002375 if (BaseType.isNull())
2376 return true;
2377
Douglas Gregor7a886e12010-01-19 06:46:48 +00002378 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002379 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002380 }
2381 }
2382
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002383 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002384 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002385 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002386 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002387 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002388 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002389 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2390 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002391 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002392 // We have found a non-static data member with a similar
2393 // name to what was typed; complain and initialize that
2394 // member.
2395 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2396 << MemberOrBase << true << CorrectedQuotedStr
2397 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2398 Diag(Member->getLocation(), diag::note_previous_decl)
2399 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002400
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002401 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002402 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002403 const CXXBaseSpecifier *DirectBaseSpec;
2404 const CXXBaseSpecifier *VirtualBaseSpec;
2405 if (FindBaseInitializer(*this, ClassDecl,
2406 Context.getTypeDeclType(Type),
2407 DirectBaseSpec, VirtualBaseSpec)) {
2408 // We have found a direct or virtual base class with a
2409 // similar name to what was typed; complain and initialize
2410 // that base class.
2411 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002412 << MemberOrBase << false << CorrectedQuotedStr
2413 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002414
2415 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2416 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002417 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002418 diag::note_base_class_specified_here)
2419 << BaseSpec->getType()
2420 << BaseSpec->getSourceRange();
2421
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002422 TyD = Type;
2423 }
2424 }
2425 }
2426
Douglas Gregor7a886e12010-01-19 06:46:48 +00002427 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002428 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002429 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002430 return true;
2431 }
John McCall2b194412009-12-21 10:41:20 +00002432 }
2433
Douglas Gregor7a886e12010-01-19 06:46:48 +00002434 if (BaseType.isNull()) {
2435 BaseType = Context.getTypeDeclType(TyD);
2436 if (SS.isSet()) {
2437 NestedNameSpecifier *Qualifier =
2438 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002439
Douglas Gregor7a886e12010-01-19 06:46:48 +00002440 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002441 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002442 }
John McCall2b194412009-12-21 10:41:20 +00002443 }
2444 }
Mike Stump1eb44332009-09-09 15:08:12 +00002445
John McCalla93c9342009-12-07 02:54:59 +00002446 if (!TInfo)
2447 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002448
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002449 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002450}
2451
Chandler Carruth81c64772011-09-03 01:14:15 +00002452/// Checks a member initializer expression for cases where reference (or
2453/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002454static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2455 Expr *Init,
2456 SourceLocation IdLoc) {
2457 QualType MemberTy = Member->getType();
2458
2459 // We only handle pointers and references currently.
2460 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2461 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2462 return;
2463
2464 const bool IsPointer = MemberTy->isPointerType();
2465 if (IsPointer) {
2466 if (const UnaryOperator *Op
2467 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2468 // The only case we're worried about with pointers requires taking the
2469 // address.
2470 if (Op->getOpcode() != UO_AddrOf)
2471 return;
2472
2473 Init = Op->getSubExpr();
2474 } else {
2475 // We only handle address-of expression initializers for pointers.
2476 return;
2477 }
2478 }
2479
Richard Smitha4bb99c2013-06-12 21:51:50 +00002480 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002481 // We only warn when referring to a non-reference parameter declaration.
2482 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2483 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002484 return;
2485
2486 S.Diag(Init->getExprLoc(),
2487 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2488 : diag::warn_bind_ref_member_to_parameter)
2489 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002490 } else {
2491 // Other initializers are fine.
2492 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002493 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002494
2495 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2496 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002497}
2498
John McCallf312b1e2010-08-26 23:41:50 +00002499MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002500Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002501 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002502 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2503 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2504 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002505 "Member must be a FieldDecl or IndirectFieldDecl");
2506
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002507 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002508 return true;
2509
Douglas Gregor464b2f02010-11-05 22:21:31 +00002510 if (Member->isInvalidDecl())
2511 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002512
John McCallb4190042009-11-04 23:02:40 +00002513 // Diagnose value-uses of fields to initialize themselves, e.g.
2514 // foo(foo)
2515 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002516 // TODO: implement -Wuninitialized and fold this into that framework.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002517 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002518 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002519 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002520 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002521 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002522 } else {
2523 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002524 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002525 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002526
Richard Trieude5e75c2012-06-14 23:11:34 +00002527 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2528 != DiagnosticsEngine::Ignored)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002529 for (unsigned i = 0, e = Args.size(); i != e; ++i)
Richard Trieude5e75c2012-06-14 23:11:34 +00002530 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002531 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002532 // initializing the i'th field, throw a warning if any of the >= i'th
2533 // fields are used, as they are not yet initialized.
2534 // Right now we are only handling the case where the i'th field uses
2535 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002536 // Also need to take into account that some fields may be initialized by
2537 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002538 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002539
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002540 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002541
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002542 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002543 // Can't check initialization for a member of dependent type or when
2544 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002545 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002546 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002547 bool InitList = false;
2548 if (isa<InitListExpr>(Init)) {
2549 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002550 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002551 }
2552
Chandler Carruth894aed92010-12-06 09:23:57 +00002553 // Initialize the member.
2554 InitializedEntity MemberEntity =
2555 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2556 : InitializedEntity::InitializeMember(IndirectMember, 0);
2557 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002558 InitList ? InitializationKind::CreateDirectList(IdLoc)
2559 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2560 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002561
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002562 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2563 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002564 if (MemberInit.isInvalid())
2565 return true;
2566
Richard Smith8a07cd32013-06-12 20:42:33 +00002567 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2568
Richard Smith41956372013-01-14 22:39:08 +00002569 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002570 // The initialization of each base and member constitutes a
2571 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002572 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002573 if (MemberInit.isInvalid())
2574 return true;
2575
Richard Smithc83c2302012-12-19 01:39:02 +00002576 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002577 }
2578
Chandler Carruth894aed92010-12-06 09:23:57 +00002579 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002580 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2581 InitRange.getBegin(), Init,
2582 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002583 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002584 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2585 InitRange.getBegin(), Init,
2586 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002587 }
Eli Friedman59c04372009-07-29 19:44:27 +00002588}
2589
John McCallf312b1e2010-08-26 23:41:50 +00002590MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002591Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002592 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002593 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002594 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002595 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002596 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002597 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002598
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002599 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002600 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002601 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2602 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002603 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002604 }
2605
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002606 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002607 // Initialize the object.
2608 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2609 QualType(ClassDecl->getTypeForDecl(), 0));
2610 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002611 InitList ? InitializationKind::CreateDirectList(NameLoc)
2612 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2613 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002614 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002615 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002616 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002617 if (DelegationInit.isInvalid())
2618 return true;
2619
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002620 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2621 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002622
Richard Smith41956372013-01-14 22:39:08 +00002623 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002624 // The initialization of each base and member constitutes a
2625 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002626 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2627 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002628 if (DelegationInit.isInvalid())
2629 return true;
2630
Eli Friedmand21016f2012-05-19 23:35:23 +00002631 // If we are in a dependent context, template instantiation will
2632 // perform this type-checking again. Just save the arguments that we
2633 // received in a ParenListExpr.
2634 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2635 // of the information that we have about the base
2636 // initializer. However, deconstructing the ASTs is a dicey process,
2637 // and this approach is far more likely to get the corner cases right.
2638 if (CurContext->isDependentContext())
2639 DelegationInit = Owned(Init);
2640
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002641 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002642 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002643 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002644}
2645
2646MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002647Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002648 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002649 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002650 SourceLocation BaseLoc
2651 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002652
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002653 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2654 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2655 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2656
2657 // C++ [class.base.init]p2:
2658 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002659 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002660 // of that class, the mem-initializer is ill-formed. A
2661 // mem-initializer-list can initialize a base class using any
2662 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002663 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002664
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002665 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002666 if (EllipsisLoc.isValid()) {
2667 // This is a pack expansion.
2668 if (!BaseType->containsUnexpandedParameterPack()) {
2669 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002670 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002671
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002672 EllipsisLoc = SourceLocation();
2673 }
2674 } else {
2675 // Check for any unexpanded parameter packs.
2676 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2677 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002678
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002679 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002680 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002681 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002682
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002683 // Check for direct and virtual base classes.
2684 const CXXBaseSpecifier *DirectBaseSpec = 0;
2685 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2686 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002687 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2688 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002689 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002690
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002691 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2692 VirtualBaseSpec);
2693
2694 // C++ [base.class.init]p2:
2695 // Unless the mem-initializer-id names a nonstatic data member of the
2696 // constructor's class or a direct or virtual base of that class, the
2697 // mem-initializer is ill-formed.
2698 if (!DirectBaseSpec && !VirtualBaseSpec) {
2699 // If the class has any dependent bases, then it's possible that
2700 // one of those types will resolve to the same type as
2701 // BaseType. Therefore, just treat this as a dependent base
2702 // class initialization. FIXME: Should we try to check the
2703 // initialization anyway? It seems odd.
2704 if (ClassDecl->hasAnyDependentBases())
2705 Dependent = true;
2706 else
2707 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2708 << BaseType << Context.getTypeDeclType(ClassDecl)
2709 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2710 }
2711 }
2712
2713 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002714 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002715
Sebastian Redl6df65482011-09-24 17:48:25 +00002716 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2717 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002718 InitRange.getBegin(), Init,
2719 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002720 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002721
2722 // C++ [base.class.init]p2:
2723 // If a mem-initializer-id is ambiguous because it designates both
2724 // a direct non-virtual base class and an inherited virtual base
2725 // class, the mem-initializer is ill-formed.
2726 if (DirectBaseSpec && VirtualBaseSpec)
2727 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002728 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002729
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002730 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002731 if (!BaseSpec)
2732 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2733
2734 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002735 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002736 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002737 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002738 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002739 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002740 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002741
2742 InitializedEntity BaseEntity =
2743 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2744 InitializationKind Kind =
2745 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2746 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2747 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002748 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2749 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002750 if (BaseInit.isInvalid())
2751 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002752
Richard Smith41956372013-01-14 22:39:08 +00002753 // C++11 [class.base.init]p7:
2754 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002755 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002756 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002757 if (BaseInit.isInvalid())
2758 return true;
2759
2760 // If we are in a dependent context, template instantiation will
2761 // perform this type-checking again. Just save the arguments that we
2762 // received in a ParenListExpr.
2763 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2764 // of the information that we have about the base
2765 // initializer. However, deconstructing the ASTs is a dicey process,
2766 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002767 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002768 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002769
Sean Huntcbb67482011-01-08 20:30:50 +00002770 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002771 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002772 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002773 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002774 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002775}
2776
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002777// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002778static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2779 if (T.isNull()) T = E->getType();
2780 QualType TargetType = SemaRef.BuildReferenceType(
2781 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002782 SourceLocation ExprLoc = E->getLocStart();
2783 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2784 TargetType, ExprLoc);
2785
2786 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2787 SourceRange(ExprLoc, ExprLoc),
2788 E->getSourceRange()).take();
2789}
2790
Anders Carlssone5ef7402010-04-23 03:10:23 +00002791/// ImplicitInitializerKind - How an implicit base or member initializer should
2792/// initialize its base or member.
2793enum ImplicitInitializerKind {
2794 IIK_Default,
2795 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002796 IIK_Move,
2797 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002798};
2799
Anders Carlssondefefd22010-04-23 02:00:02 +00002800static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002801BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002802 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002803 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002804 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002805 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002806 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002807 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2808 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002809
John McCall60d7b3a2010-08-24 06:29:42 +00002810 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002811
2812 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002813 case IIK_Inherit: {
2814 const CXXRecordDecl *Inherited =
2815 Constructor->getInheritedConstructor()->getParent();
2816 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2817 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2818 // C++11 [class.inhctor]p8:
2819 // Each expression in the expression-list is of the form
2820 // static_cast<T&&>(p), where p is the name of the corresponding
2821 // constructor parameter and T is the declared type of p.
2822 SmallVector<Expr*, 16> Args;
2823 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2824 ParmVarDecl *PD = Constructor->getParamDecl(I);
2825 ExprResult ArgExpr =
2826 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2827 VK_LValue, SourceLocation());
2828 if (ArgExpr.isInvalid())
2829 return true;
2830 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2831 }
2832
2833 InitializationKind InitKind = InitializationKind::CreateDirect(
2834 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002835 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002836 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2837 break;
2838 }
2839 }
2840 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002841 case IIK_Default: {
2842 InitializationKind InitKind
2843 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002844 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2845 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002846 break;
2847 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002848
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002849 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002850 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002851 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002852 ParmVarDecl *Param = Constructor->getParamDecl(0);
2853 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002854
Anders Carlssone5ef7402010-04-23 03:10:23 +00002855 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002856 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002857 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002858 Constructor->getLocation(), ParamType,
2859 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002860
Eli Friedman5f2987c2012-02-02 03:46:19 +00002861 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2862
Anders Carlssonc7957502010-04-24 22:02:54 +00002863 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002864 QualType ArgTy =
2865 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2866 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002867
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002868 if (Moving) {
2869 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2870 }
2871
John McCallf871d0c2010-08-07 06:22:56 +00002872 CXXCastPath BasePath;
2873 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002874 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2875 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002876 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002877 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002878
Anders Carlssone5ef7402010-04-23 03:10:23 +00002879 InitializationKind InitKind
2880 = InitializationKind::CreateDirect(Constructor->getLocation(),
2881 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002882 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2883 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002884 break;
2885 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002886 }
John McCall9ae2f072010-08-23 23:25:46 +00002887
Douglas Gregor53c374f2010-12-07 00:41:46 +00002888 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002889 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002890 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002891
Anders Carlssondefefd22010-04-23 02:00:02 +00002892 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002893 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002894 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2895 SourceLocation()),
2896 BaseSpec->isVirtual(),
2897 SourceLocation(),
2898 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002899 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002900 SourceLocation());
2901
Anders Carlssondefefd22010-04-23 02:00:02 +00002902 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002903}
2904
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002905static bool RefersToRValueRef(Expr *MemRef) {
2906 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2907 return Referenced->getType()->isRValueReferenceType();
2908}
2909
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002910static bool
2911BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002912 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002913 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002914 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002915 if (Field->isInvalidDecl())
2916 return true;
2917
Chandler Carruthf186b542010-06-29 23:50:44 +00002918 SourceLocation Loc = Constructor->getLocation();
2919
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002920 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2921 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002922 ParmVarDecl *Param = Constructor->getParamDecl(0);
2923 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002924
2925 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002926 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2927 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002928
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002929 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002930 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002931 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002932 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002933
Eli Friedman5f2987c2012-02-02 03:46:19 +00002934 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2935
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002936 if (Moving) {
2937 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2938 }
2939
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002940 // Build a reference to this field within the parameter.
2941 CXXScopeSpec SS;
2942 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2943 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002944 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2945 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002946 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002947 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002948 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002949 ParamType, Loc,
2950 /*IsArrow=*/false,
2951 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002952 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002953 /*FirstQualifierInScope=*/0,
2954 MemberLookup,
2955 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002956 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002957 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002958
2959 // C++11 [class.copy]p15:
2960 // - if a member m has rvalue reference type T&&, it is direct-initialized
2961 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002962 if (RefersToRValueRef(CtorArg.get())) {
2963 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002964 }
2965
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002966 // When the field we are copying is an array, create index variables for
2967 // each dimension of the array. We use these index variables to subscript
2968 // the source array, and other clients (e.g., CodeGen) will perform the
2969 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002970 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002971 QualType BaseType = Field->getType();
2972 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002973 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002974 while (const ConstantArrayType *Array
2975 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002976 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002977 // Create the iteration variable for this array index.
2978 IdentifierInfo *IterationVarName = 0;
2979 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002980 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002981 llvm::raw_svector_ostream OS(Str);
2982 OS << "__i" << IndexVariables.size();
2983 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2984 }
2985 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002986 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002987 IterationVarName, SizeType,
2988 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002989 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002990 IndexVariables.push_back(IterationVar);
2991
2992 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002993 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002994 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002995 assert(!IterationVarRef.isInvalid() &&
2996 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002997 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2998 assert(!IterationVarRef.isInvalid() &&
2999 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003000
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003001 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003002 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003003 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003004 Loc);
3005 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003006 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003007
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003008 BaseType = Array->getElementType();
3009 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003010
3011 // The array subscript expression is an lvalue, which is wrong for moving.
3012 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003013 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003014
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003015 // Construct the entity that we will be initializing. For an array, this
3016 // will be first element in the array, which may require several levels
3017 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003018 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003019 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003020 if (Indirect)
3021 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3022 else
3023 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003024 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3025 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3026 0,
3027 Entities.back()));
3028
3029 // Direct-initialize to use the copy constructor.
3030 InitializationKind InitKind =
3031 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3032
Sebastian Redl74e611a2011-09-04 18:14:28 +00003033 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003034 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003035
John McCall60d7b3a2010-08-24 06:29:42 +00003036 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003037 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003038 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003039 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003040 if (MemberInit.isInvalid())
3041 return true;
3042
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003043 if (Indirect) {
3044 assert(IndexVariables.size() == 0 &&
3045 "Indirect field improperly initialized");
3046 CXXMemberInit
3047 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3048 Loc, Loc,
3049 MemberInit.takeAs<Expr>(),
3050 Loc);
3051 } else
3052 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3053 Loc, MemberInit.takeAs<Expr>(),
3054 Loc,
3055 IndexVariables.data(),
3056 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003057 return false;
3058 }
3059
Richard Smith07b0fdc2013-03-18 21:12:30 +00003060 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3061 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003062
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003063 QualType FieldBaseElementType =
3064 SemaRef.Context.getBaseElementType(Field->getType());
3065
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003066 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003067 InitializedEntity InitEntity
3068 = Indirect? InitializedEntity::InitializeMember(Indirect)
3069 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003070 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003071 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003072
3073 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3074 ExprResult MemberInit =
3075 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003076
Douglas Gregor53c374f2010-12-07 00:41:46 +00003077 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003078 if (MemberInit.isInvalid())
3079 return true;
3080
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003081 if (Indirect)
3082 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3083 Indirect, Loc,
3084 Loc,
3085 MemberInit.get(),
3086 Loc);
3087 else
3088 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3089 Field, Loc, Loc,
3090 MemberInit.get(),
3091 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003092 return false;
3093 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003094
Sean Hunt1f2f3842011-05-17 00:19:05 +00003095 if (!Field->getParent()->isUnion()) {
3096 if (FieldBaseElementType->isReferenceType()) {
3097 SemaRef.Diag(Constructor->getLocation(),
3098 diag::err_uninitialized_member_in_ctor)
3099 << (int)Constructor->isImplicit()
3100 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3101 << 0 << Field->getDeclName();
3102 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3103 return true;
3104 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003105
Sean Hunt1f2f3842011-05-17 00:19:05 +00003106 if (FieldBaseElementType.isConstQualified()) {
3107 SemaRef.Diag(Constructor->getLocation(),
3108 diag::err_uninitialized_member_in_ctor)
3109 << (int)Constructor->isImplicit()
3110 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3111 << 1 << Field->getDeclName();
3112 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3113 return true;
3114 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003115 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003116
David Blaikie4e4d0842012-03-11 07:00:24 +00003117 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003118 FieldBaseElementType->isObjCRetainableType() &&
3119 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3120 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003121 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003122 // Default-initialize Objective-C pointers to NULL.
3123 CXXMemberInit
3124 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3125 Loc, Loc,
3126 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3127 Loc);
3128 return false;
3129 }
3130
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003131 // Nothing to initialize.
3132 CXXMemberInit = 0;
3133 return false;
3134}
John McCallf1860e52010-05-20 23:23:51 +00003135
3136namespace {
3137struct BaseAndFieldInfo {
3138 Sema &S;
3139 CXXConstructorDecl *Ctor;
3140 bool AnyErrorsInInits;
3141 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003142 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003143 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003144
3145 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3146 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003147 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3148 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003149 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003150 else if (Generated && Ctor->isMoveConstructor())
3151 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003152 else if (Ctor->getInheritedConstructor())
3153 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003154 else
3155 IIK = IIK_Default;
3156 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003157
3158 bool isImplicitCopyOrMove() const {
3159 switch (IIK) {
3160 case IIK_Copy:
3161 case IIK_Move:
3162 return true;
3163
3164 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003165 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003166 return false;
3167 }
David Blaikie30263482012-01-20 21:50:17 +00003168
3169 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003170 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003171
3172 bool addFieldInitializer(CXXCtorInitializer *Init) {
3173 AllToInit.push_back(Init);
3174
3175 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003176 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003177 S.UnusedPrivateFields.remove(Init->getAnyMember());
3178
3179 return false;
3180 }
John McCallf1860e52010-05-20 23:23:51 +00003181};
3182}
3183
Richard Smitha4950662011-09-19 13:34:43 +00003184/// \brief Determine whether the given indirect field declaration is somewhere
3185/// within an anonymous union.
3186static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3187 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3188 CEnd = F->chain_end();
3189 C != CEnd; ++C)
3190 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3191 if (Record->isUnion())
3192 return true;
3193
3194 return false;
3195}
3196
Douglas Gregorddb21472011-11-02 23:04:16 +00003197/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3198/// array type.
3199static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3200 if (T->isIncompleteArrayType())
3201 return true;
3202
3203 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3204 if (!ArrayT->getSize())
3205 return true;
3206
3207 T = ArrayT->getElementType();
3208 }
3209
3210 return false;
3211}
3212
Richard Smith7a614d82011-06-11 17:19:42 +00003213static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003214 FieldDecl *Field,
3215 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003216
Chandler Carruthe861c602010-06-30 02:59:29 +00003217 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003218 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3219 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003220
Richard Smith0b8220a2012-08-07 21:30:42 +00003221 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003222 // has a brace-or-equal-initializer, the entity is initialized as specified
3223 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003224 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003225 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3226 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003227 CXXCtorInitializer *Init;
3228 if (Indirect)
3229 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3230 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003231 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003232 SourceLocation());
3233 else
3234 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3235 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003236 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003237 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003238 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003239 }
3240
Richard Smithc115f632011-09-18 11:14:50 +00003241 // Don't build an implicit initializer for union members if none was
3242 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003243 if (Field->getParent()->isUnion() ||
3244 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003245 return false;
3246
Douglas Gregorddb21472011-11-02 23:04:16 +00003247 // Don't initialize incomplete or zero-length arrays.
3248 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3249 return false;
3250
John McCallf1860e52010-05-20 23:23:51 +00003251 // Don't try to build an implicit initializer if there were semantic
3252 // errors in any of the initializers (and therefore we might be
3253 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003254 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003255 return false;
3256
Sean Huntcbb67482011-01-08 20:30:50 +00003257 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003258 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3259 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003260 return true;
John McCallf1860e52010-05-20 23:23:51 +00003261
Richard Smith0b8220a2012-08-07 21:30:42 +00003262 if (!Init)
3263 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003264
Richard Smith0b8220a2012-08-07 21:30:42 +00003265 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003266}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003267
3268bool
3269Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3270 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003271 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003272 Constructor->setNumCtorInitializers(1);
3273 CXXCtorInitializer **initializer =
3274 new (Context) CXXCtorInitializer*[1];
3275 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3276 Constructor->setCtorInitializers(initializer);
3277
Sean Huntb76af9c2011-05-03 23:05:34 +00003278 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003279 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003280 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3281 }
3282
Sean Huntc1598702011-05-05 00:05:47 +00003283 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003284
Sean Hunt059ce0d2011-05-01 07:04:31 +00003285 return false;
3286}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003287
David Blaikie93c86172013-01-17 05:26:25 +00003288bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3289 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003290 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003291 // Just store the initializers as written, they will be checked during
3292 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003293 if (!Initializers.empty()) {
3294 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003295 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003296 new (Context) CXXCtorInitializer*[Initializers.size()];
3297 memcpy(baseOrMemberInitializers, Initializers.data(),
3298 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003299 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003300 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003301
3302 // Let template instantiation know whether we had errors.
3303 if (AnyErrors)
3304 Constructor->setInvalidDecl();
3305
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003306 return false;
3307 }
3308
John McCallf1860e52010-05-20 23:23:51 +00003309 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003310
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003311 // We need to build the initializer AST according to order of construction
3312 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003313 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003314 if (!ClassDecl)
3315 return true;
3316
Eli Friedman80c30da2009-11-09 19:20:36 +00003317 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003318
David Blaikie93c86172013-01-17 05:26:25 +00003319 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003320 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003321
3322 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003323 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003324 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003325 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003326 }
3327
Anders Carlsson711f34a2010-04-21 19:52:01 +00003328 // Keep track of the direct virtual bases.
3329 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3330 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3331 E = ClassDecl->bases_end(); I != E; ++I) {
3332 if (I->isVirtual())
3333 DirectVBases.insert(I);
3334 }
3335
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003336 // Push virtual bases before others.
3337 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3338 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3339
Sean Huntcbb67482011-01-08 20:30:50 +00003340 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003341 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3342 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003343 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003344 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003345 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003346 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003347 VBase, IsInheritedVirtualBase,
3348 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003349 HadError = true;
3350 continue;
3351 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003352
John McCallf1860e52010-05-20 23:23:51 +00003353 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003354 }
3355 }
Mike Stump1eb44332009-09-09 15:08:12 +00003356
John McCallf1860e52010-05-20 23:23:51 +00003357 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003358 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3359 E = ClassDecl->bases_end(); Base != E; ++Base) {
3360 // Virtuals are in the virtual base list and already constructed.
3361 if (Base->isVirtual())
3362 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003363
Sean Huntcbb67482011-01-08 20:30:50 +00003364 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003365 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3366 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003367 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003368 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003369 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003370 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003371 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003372 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003373 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003374 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003375
John McCallf1860e52010-05-20 23:23:51 +00003376 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003377 }
3378 }
Mike Stump1eb44332009-09-09 15:08:12 +00003379
John McCallf1860e52010-05-20 23:23:51 +00003380 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003381 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3382 MemEnd = ClassDecl->decls_end();
3383 Mem != MemEnd; ++Mem) {
3384 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003385 // C++ [class.bit]p2:
3386 // A declaration for a bit-field that omits the identifier declares an
3387 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3388 // initialized.
3389 if (F->isUnnamedBitfield())
3390 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003391
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003392 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003393 // handle anonymous struct/union fields based on their individual
3394 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003395 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003396 continue;
3397
3398 if (CollectFieldInitializer(*this, Info, F))
3399 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003400 continue;
3401 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003402
3403 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003404 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003405 continue;
3406
3407 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3408 if (F->getType()->isIncompleteArrayType()) {
3409 assert(ClassDecl->hasFlexibleArrayMember() &&
3410 "Incomplete array type is not valid");
3411 continue;
3412 }
3413
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003414 // Initialize each field of an anonymous struct individually.
3415 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3416 HadError = true;
3417
3418 continue;
3419 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003420 }
Mike Stump1eb44332009-09-09 15:08:12 +00003421
David Blaikie93c86172013-01-17 05:26:25 +00003422 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003423 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003424 Constructor->setNumCtorInitializers(NumInitializers);
3425 CXXCtorInitializer **baseOrMemberInitializers =
3426 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003427 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003428 NumInitializers * sizeof(CXXCtorInitializer*));
3429 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003430
John McCallef027fe2010-03-16 21:39:52 +00003431 // Constructors implicitly reference the base and member
3432 // destructors.
3433 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3434 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003435 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003436
3437 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003438}
3439
David Blaikieee000bb2013-01-17 08:49:22 +00003440static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003441 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003442 const RecordDecl *RD = RT->getDecl();
3443 if (RD->isAnonymousStructOrUnion()) {
3444 for (RecordDecl::field_iterator Field = RD->field_begin(),
3445 E = RD->field_end(); Field != E; ++Field)
3446 PopulateKeysForFields(*Field, IdealInits);
3447 return;
3448 }
Eli Friedman6347f422009-07-21 19:28:10 +00003449 }
David Blaikieee000bb2013-01-17 08:49:22 +00003450 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003451}
3452
Anders Carlssonea356fb2010-04-02 05:42:15 +00003453static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003454 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003455}
3456
Anders Carlssonea356fb2010-04-02 05:42:15 +00003457static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003458 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003459 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003460 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003461
David Blaikieee000bb2013-01-17 08:49:22 +00003462 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003463}
3464
David Blaikie93c86172013-01-17 05:26:25 +00003465static void DiagnoseBaseOrMemInitializerOrder(
3466 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3467 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003468 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003469 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003470
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003471 // Don't check initializers order unless the warning is enabled at the
3472 // location of at least one initializer.
3473 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003474 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003475 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003476 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3477 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003478 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003479 ShouldCheckOrder = true;
3480 break;
3481 }
3482 }
3483 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003484 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003485
John McCalld6ca8da2010-04-10 07:37:23 +00003486 // Build the list of bases and members in the order that they'll
3487 // actually be initialized. The explicit initializers should be in
3488 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003489 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003490
Anders Carlsson071d6102010-04-02 03:38:04 +00003491 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3492
John McCalld6ca8da2010-04-10 07:37:23 +00003493 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003494 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003495 ClassDecl->vbases_begin(),
3496 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003497 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003498
John McCalld6ca8da2010-04-10 07:37:23 +00003499 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003500 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003501 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003502 if (Base->isVirtual())
3503 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003504 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003505 }
Mike Stump1eb44332009-09-09 15:08:12 +00003506
John McCalld6ca8da2010-04-10 07:37:23 +00003507 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003508 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003509 E = ClassDecl->field_end(); Field != E; ++Field) {
3510 if (Field->isUnnamedBitfield())
3511 continue;
3512
David Blaikieee000bb2013-01-17 08:49:22 +00003513 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003514 }
3515
John McCalld6ca8da2010-04-10 07:37:23 +00003516 unsigned NumIdealInits = IdealInitKeys.size();
3517 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003518
Sean Huntcbb67482011-01-08 20:30:50 +00003519 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003520 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003521 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003522 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003523
3524 // Scan forward to try to find this initializer in the idealized
3525 // initializers list.
3526 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3527 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003528 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003529
3530 // If we didn't find this initializer, it must be because we
3531 // scanned past it on a previous iteration. That can only
3532 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003533 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003534 Sema::SemaDiagnosticBuilder D =
3535 SemaRef.Diag(PrevInit->getSourceLocation(),
3536 diag::warn_initializer_out_of_order);
3537
Francois Pichet00eb3f92010-12-04 09:14:42 +00003538 if (PrevInit->isAnyMemberInitializer())
3539 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003540 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003541 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003542
Francois Pichet00eb3f92010-12-04 09:14:42 +00003543 if (Init->isAnyMemberInitializer())
3544 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003545 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003546 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003547
3548 // Move back to the initializer's location in the ideal list.
3549 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3550 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003551 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003552
3553 assert(IdealIndex != NumIdealInits &&
3554 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003555 }
John McCalld6ca8da2010-04-10 07:37:23 +00003556
3557 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003558 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003559}
3560
John McCall3c3ccdb2010-04-10 09:28:51 +00003561namespace {
3562bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003563 CXXCtorInitializer *Init,
3564 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003565 if (!PrevInit) {
3566 PrevInit = Init;
3567 return false;
3568 }
3569
Douglas Gregordc392c12013-03-25 23:28:23 +00003570 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003571 S.Diag(Init->getSourceLocation(),
3572 diag::err_multiple_mem_initialization)
3573 << Field->getDeclName()
3574 << Init->getSourceRange();
3575 else {
John McCallf4c73712011-01-19 06:33:43 +00003576 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003577 assert(BaseClass && "neither field nor base");
3578 S.Diag(Init->getSourceLocation(),
3579 diag::err_multiple_base_initialization)
3580 << QualType(BaseClass, 0)
3581 << Init->getSourceRange();
3582 }
3583 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3584 << 0 << PrevInit->getSourceRange();
3585
3586 return true;
3587}
3588
Sean Huntcbb67482011-01-08 20:30:50 +00003589typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003590typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3591
3592bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003593 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003594 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003595 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003596 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003597 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003598
3599 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003600 if (Parent->isUnion()) {
3601 UnionEntry &En = Unions[Parent];
3602 if (En.first && En.first != Child) {
3603 S.Diag(Init->getSourceLocation(),
3604 diag::err_multiple_mem_union_initialization)
3605 << Field->getDeclName()
3606 << Init->getSourceRange();
3607 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3608 << 0 << En.second->getSourceRange();
3609 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003610 }
3611 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003612 En.first = Child;
3613 En.second = Init;
3614 }
David Blaikie6fe29652011-11-17 06:01:57 +00003615 if (!Parent->isAnonymousStructOrUnion())
3616 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003617 }
3618
3619 Child = Parent;
3620 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003621 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003622
3623 return false;
3624}
3625}
3626
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003627/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003628void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003629 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003630 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003631 bool AnyErrors) {
3632 if (!ConstructorDecl)
3633 return;
3634
3635 AdjustDeclIfTemplate(ConstructorDecl);
3636
3637 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003638 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003639
3640 if (!Constructor) {
3641 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3642 return;
3643 }
3644
John McCall3c3ccdb2010-04-10 09:28:51 +00003645 // Mapping for the duplicate initializers check.
3646 // For member initializers, this is keyed with a FieldDecl*.
3647 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003648 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003649
3650 // Mapping for the inconsistent anonymous-union initializers check.
3651 RedundantUnionMap MemberUnions;
3652
Anders Carlssonea356fb2010-04-02 05:42:15 +00003653 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003654 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003655 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003656
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003657 // Set the source order index.
3658 Init->setSourceOrder(i);
3659
Francois Pichet00eb3f92010-12-04 09:14:42 +00003660 if (Init->isAnyMemberInitializer()) {
3661 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003662 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3663 CheckRedundantUnionInit(*this, Init, MemberUnions))
3664 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003665 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003666 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3667 if (CheckRedundantInit(*this, Init, Members[Key]))
3668 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003669 } else {
3670 assert(Init->isDelegatingInitializer());
3671 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003672 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003673 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003674 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003675 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003676 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003677 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003678 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003679 // Return immediately as the initializer is set.
3680 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003681 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003682 }
3683
Anders Carlssonea356fb2010-04-02 05:42:15 +00003684 if (HadError)
3685 return;
3686
David Blaikie93c86172013-01-17 05:26:25 +00003687 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003688
David Blaikie93c86172013-01-17 05:26:25 +00003689 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003690}
3691
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003692void
John McCallef027fe2010-03-16 21:39:52 +00003693Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3694 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003695 // Ignore dependent contexts. Also ignore unions, since their members never
3696 // have destructors implicitly called.
3697 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003698 return;
John McCall58e6f342010-03-16 05:22:47 +00003699
3700 // FIXME: all the access-control diagnostics are positioned on the
3701 // field/base declaration. That's probably good; that said, the
3702 // user might reasonably want to know why the destructor is being
3703 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003704
Anders Carlsson9f853df2009-11-17 04:44:12 +00003705 // Non-static data members.
3706 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3707 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003708 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003709 if (Field->isInvalidDecl())
3710 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003711
3712 // Don't destroy incomplete or zero-length arrays.
3713 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3714 continue;
3715
Anders Carlsson9f853df2009-11-17 04:44:12 +00003716 QualType FieldType = Context.getBaseElementType(Field->getType());
3717
3718 const RecordType* RT = FieldType->getAs<RecordType>();
3719 if (!RT)
3720 continue;
3721
3722 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003723 if (FieldClassDecl->isInvalidDecl())
3724 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003725 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003726 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003727 // The destructor for an implicit anonymous union member is never invoked.
3728 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3729 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003730
Douglas Gregordb89f282010-07-01 22:47:18 +00003731 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003732 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003733 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003734 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003735 << Field->getDeclName()
3736 << FieldType);
3737
Eli Friedman5f2987c2012-02-02 03:46:19 +00003738 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003739 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003740 }
3741
John McCall58e6f342010-03-16 05:22:47 +00003742 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3743
Anders Carlsson9f853df2009-11-17 04:44:12 +00003744 // Bases.
3745 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3746 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003747 // Bases are always records in a well-formed non-dependent class.
3748 const RecordType *RT = Base->getType()->getAs<RecordType>();
3749
3750 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003751 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003752 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003753
John McCall58e6f342010-03-16 05:22:47 +00003754 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003755 // If our base class is invalid, we probably can't get its dtor anyway.
3756 if (BaseClassDecl->isInvalidDecl())
3757 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003758 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003759 continue;
John McCall58e6f342010-03-16 05:22:47 +00003760
Douglas Gregordb89f282010-07-01 22:47:18 +00003761 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003762 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003763
3764 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003765 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003766 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003767 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003768 << Base->getSourceRange(),
3769 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003770
Eli Friedman5f2987c2012-02-02 03:46:19 +00003771 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003772 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003773 }
3774
3775 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003776 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3777 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003778
3779 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003780 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003781
3782 // Ignore direct virtual bases.
3783 if (DirectVirtualBases.count(RT))
3784 continue;
3785
John McCall58e6f342010-03-16 05:22:47 +00003786 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003787 // If our base class is invalid, we probably can't get its dtor anyway.
3788 if (BaseClassDecl->isInvalidDecl())
3789 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003790 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003791 continue;
John McCall58e6f342010-03-16 05:22:47 +00003792
Douglas Gregordb89f282010-07-01 22:47:18 +00003793 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003794 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00003795 if (CheckDestructorAccess(
3796 ClassDecl->getLocation(), Dtor,
3797 PDiag(diag::err_access_dtor_vbase)
3798 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3799 Context.getTypeDeclType(ClassDecl)) ==
3800 AR_accessible) {
3801 CheckDerivedToBaseConversion(
3802 Context.getTypeDeclType(ClassDecl), VBase->getType(),
3803 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3804 SourceRange(), DeclarationName(), 0);
3805 }
John McCall58e6f342010-03-16 05:22:47 +00003806
Eli Friedman5f2987c2012-02-02 03:46:19 +00003807 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003808 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003809 }
3810}
3811
John McCalld226f652010-08-21 09:40:31 +00003812void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003813 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003814 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003815
Mike Stump1eb44332009-09-09 15:08:12 +00003816 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003817 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003818 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003819}
3820
Mike Stump1eb44332009-09-09 15:08:12 +00003821bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003822 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003823 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3824 unsigned DiagID;
3825 AbstractDiagSelID SelID;
3826
3827 public:
3828 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3829 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3830
3831 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003832 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003833 if (SelID == -1)
3834 S.Diag(Loc, DiagID) << T;
3835 else
3836 S.Diag(Loc, DiagID) << SelID << T;
3837 }
3838 } Diagnoser(DiagID, SelID);
3839
3840 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003841}
3842
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003843bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003844 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003845 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003846 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003847
Anders Carlsson11f21a02009-03-23 19:10:31 +00003848 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003849 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003850
Ted Kremenek6217b802009-07-29 21:53:49 +00003851 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003852 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003853 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003854 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003855
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003856 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003857 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003858 }
Mike Stump1eb44332009-09-09 15:08:12 +00003859
Ted Kremenek6217b802009-07-29 21:53:49 +00003860 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003861 if (!RT)
3862 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003863
John McCall86ff3082010-02-04 22:26:26 +00003864 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003865
John McCall94c3b562010-08-18 09:41:07 +00003866 // We can't answer whether something is abstract until it has a
3867 // definition. If it's currently being defined, we'll walk back
3868 // over all the declarations when we have a full definition.
3869 const CXXRecordDecl *Def = RD->getDefinition();
3870 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003871 return false;
3872
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003873 if (!RD->isAbstract())
3874 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003875
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003876 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003877 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003878
John McCall94c3b562010-08-18 09:41:07 +00003879 return true;
3880}
3881
3882void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3883 // Check if we've already emitted the list of pure virtual functions
3884 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003885 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003886 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003887
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003888 CXXFinalOverriderMap FinalOverriders;
3889 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003890
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003891 // Keep a set of seen pure methods so we won't diagnose the same method
3892 // more than once.
3893 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3894
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003895 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3896 MEnd = FinalOverriders.end();
3897 M != MEnd;
3898 ++M) {
3899 for (OverridingMethods::iterator SO = M->second.begin(),
3900 SOEnd = M->second.end();
3901 SO != SOEnd; ++SO) {
3902 // C++ [class.abstract]p4:
3903 // A class is abstract if it contains or inherits at least one
3904 // pure virtual function for which the final overrider is pure
3905 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003906
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003907 //
3908 if (SO->second.size() != 1)
3909 continue;
3910
3911 if (!SO->second.front().Method->isPure())
3912 continue;
3913
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003914 if (!SeenPureMethods.insert(SO->second.front().Method))
3915 continue;
3916
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003917 Diag(SO->second.front().Method->getLocation(),
3918 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003919 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003920 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003921 }
3922
3923 if (!PureVirtualClassDiagSet)
3924 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3925 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003926}
3927
Anders Carlsson8211eff2009-03-24 01:19:16 +00003928namespace {
John McCall94c3b562010-08-18 09:41:07 +00003929struct AbstractUsageInfo {
3930 Sema &S;
3931 CXXRecordDecl *Record;
3932 CanQualType AbstractType;
3933 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003934
John McCall94c3b562010-08-18 09:41:07 +00003935 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3936 : S(S), Record(Record),
3937 AbstractType(S.Context.getCanonicalType(
3938 S.Context.getTypeDeclType(Record))),
3939 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003940
John McCall94c3b562010-08-18 09:41:07 +00003941 void DiagnoseAbstractType() {
3942 if (Invalid) return;
3943 S.DiagnoseAbstractType(Record);
3944 Invalid = true;
3945 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003946
John McCall94c3b562010-08-18 09:41:07 +00003947 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3948};
3949
3950struct CheckAbstractUsage {
3951 AbstractUsageInfo &Info;
3952 const NamedDecl *Ctx;
3953
3954 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3955 : Info(Info), Ctx(Ctx) {}
3956
3957 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3958 switch (TL.getTypeLocClass()) {
3959#define ABSTRACT_TYPELOC(CLASS, PARENT)
3960#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003961 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003962#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003963 }
John McCall94c3b562010-08-18 09:41:07 +00003964 }
Mike Stump1eb44332009-09-09 15:08:12 +00003965
John McCall94c3b562010-08-18 09:41:07 +00003966 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3967 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3968 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003969 if (!TL.getArg(I))
3970 continue;
3971
John McCall94c3b562010-08-18 09:41:07 +00003972 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3973 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003974 }
John McCall94c3b562010-08-18 09:41:07 +00003975 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003976
John McCall94c3b562010-08-18 09:41:07 +00003977 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3978 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3979 }
Mike Stump1eb44332009-09-09 15:08:12 +00003980
John McCall94c3b562010-08-18 09:41:07 +00003981 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3982 // Visit the type parameters from a permissive context.
3983 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3984 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3985 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3986 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3987 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3988 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003989 }
John McCall94c3b562010-08-18 09:41:07 +00003990 }
Mike Stump1eb44332009-09-09 15:08:12 +00003991
John McCall94c3b562010-08-18 09:41:07 +00003992 // Visit pointee types from a permissive context.
3993#define CheckPolymorphic(Type) \
3994 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3995 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3996 }
3997 CheckPolymorphic(PointerTypeLoc)
3998 CheckPolymorphic(ReferenceTypeLoc)
3999 CheckPolymorphic(MemberPointerTypeLoc)
4000 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004001 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004002
John McCall94c3b562010-08-18 09:41:07 +00004003 /// Handle all the types we haven't given a more specific
4004 /// implementation for above.
4005 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4006 // Every other kind of type that we haven't called out already
4007 // that has an inner type is either (1) sugar or (2) contains that
4008 // inner type in some way as a subobject.
4009 if (TypeLoc Next = TL.getNextTypeLoc())
4010 return Visit(Next, Sel);
4011
4012 // If there's no inner type and we're in a permissive context,
4013 // don't diagnose.
4014 if (Sel == Sema::AbstractNone) return;
4015
4016 // Check whether the type matches the abstract type.
4017 QualType T = TL.getType();
4018 if (T->isArrayType()) {
4019 Sel = Sema::AbstractArrayType;
4020 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004021 }
John McCall94c3b562010-08-18 09:41:07 +00004022 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4023 if (CT != Info.AbstractType) return;
4024
4025 // It matched; do some magic.
4026 if (Sel == Sema::AbstractArrayType) {
4027 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4028 << T << TL.getSourceRange();
4029 } else {
4030 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4031 << Sel << T << TL.getSourceRange();
4032 }
4033 Info.DiagnoseAbstractType();
4034 }
4035};
4036
4037void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4038 Sema::AbstractDiagSelID Sel) {
4039 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4040}
4041
4042}
4043
4044/// Check for invalid uses of an abstract type in a method declaration.
4045static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4046 CXXMethodDecl *MD) {
4047 // No need to do the check on definitions, which require that
4048 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004049 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004050 return;
4051
4052 // For safety's sake, just ignore it if we don't have type source
4053 // information. This should never happen for non-implicit methods,
4054 // but...
4055 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4056 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4057}
4058
4059/// Check for invalid uses of an abstract type within a class definition.
4060static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4061 CXXRecordDecl *RD) {
4062 for (CXXRecordDecl::decl_iterator
4063 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4064 Decl *D = *I;
4065 if (D->isImplicit()) continue;
4066
4067 // Methods and method templates.
4068 if (isa<CXXMethodDecl>(D)) {
4069 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4070 } else if (isa<FunctionTemplateDecl>(D)) {
4071 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4072 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4073
4074 // Fields and static variables.
4075 } else if (isa<FieldDecl>(D)) {
4076 FieldDecl *FD = cast<FieldDecl>(D);
4077 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4078 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4079 } else if (isa<VarDecl>(D)) {
4080 VarDecl *VD = cast<VarDecl>(D);
4081 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4082 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4083
4084 // Nested classes and class templates.
4085 } else if (isa<CXXRecordDecl>(D)) {
4086 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4087 } else if (isa<ClassTemplateDecl>(D)) {
4088 CheckAbstractClassUsage(Info,
4089 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4090 }
4091 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004092}
4093
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004094/// \brief Perform semantic checks on a class definition that has been
4095/// completing, introducing implicitly-declared members, checking for
4096/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004097void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004098 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004099 return;
4100
John McCall94c3b562010-08-18 09:41:07 +00004101 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4102 AbstractUsageInfo Info(*this, Record);
4103 CheckAbstractClassUsage(Info, Record);
4104 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004105
4106 // If this is not an aggregate type and has no user-declared constructor,
4107 // complain about any non-static data members of reference or const scalar
4108 // type, since they will never get initializers.
4109 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004110 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4111 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004112 bool Complained = false;
4113 for (RecordDecl::field_iterator F = Record->field_begin(),
4114 FEnd = Record->field_end();
4115 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004116 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004117 continue;
4118
Douglas Gregor325e5932010-04-15 00:00:53 +00004119 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004120 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004121 if (!Complained) {
4122 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4123 << Record->getTagKind() << Record;
4124 Complained = true;
4125 }
4126
4127 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4128 << F->getType()->isReferenceType()
4129 << F->getDeclName();
4130 }
4131 }
4132 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004133
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004134 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004135 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004136
4137 if (Record->getIdentifier()) {
4138 // C++ [class.mem]p13:
4139 // If T is the name of a class, then each of the following shall have a
4140 // name different from T:
4141 // - every member of every anonymous union that is a member of class T.
4142 //
4143 // C++ [class.mem]p14:
4144 // In addition, if class T has a user-declared constructor (12.1), every
4145 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004146 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4147 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4148 ++I) {
4149 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004150 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4151 isa<IndirectFieldDecl>(D)) {
4152 Diag(D->getLocation(), diag::err_member_name_of_class)
4153 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004154 break;
4155 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004156 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004157 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004158
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004159 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004160 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004161 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004162 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004163 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4164 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4165 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004166
David Blaikieb6b5b972012-09-21 03:21:07 +00004167 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4168 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4169 DiagnoseAbstractType(Record);
4170 }
4171
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004172 if (!Record->isDependentType()) {
4173 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4174 MEnd = Record->method_end();
4175 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004176 // See if a method overloads virtual methods in a base
4177 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004178 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004179 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004180
4181 // Check whether the explicitly-defaulted special members are valid.
4182 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4183 CheckExplicitlyDefaultedSpecialMember(*M);
4184
4185 // For an explicitly defaulted or deleted special member, we defer
4186 // determining triviality until the class is complete. That time is now!
4187 if (!M->isImplicit() && !M->isUserProvided()) {
4188 CXXSpecialMember CSM = getSpecialMember(*M);
4189 if (CSM != CXXInvalid) {
4190 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4191
4192 // Inform the class that we've finished declaring this member.
4193 Record->finishedDefaultedOrDeletedMember(*M);
4194 }
4195 }
4196 }
4197 }
4198
4199 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4200 // function that is not a constructor declares that member function to be
4201 // const. [...] The class of which that function is a member shall be
4202 // a literal type.
4203 //
4204 // If the class has virtual bases, any constexpr members will already have
4205 // been diagnosed by the checks performed on the member declaration, so
4206 // suppress this (less useful) diagnostic.
4207 //
4208 // We delay this until we know whether an explicitly-defaulted (or deleted)
4209 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004210 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004211 !Record->isLiteral() && !Record->getNumVBases()) {
4212 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4213 MEnd = Record->method_end();
4214 M != MEnd; ++M) {
4215 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4216 switch (Record->getTemplateSpecializationKind()) {
4217 case TSK_ImplicitInstantiation:
4218 case TSK_ExplicitInstantiationDeclaration:
4219 case TSK_ExplicitInstantiationDefinition:
4220 // If a template instantiates to a non-literal type, but its members
4221 // instantiate to constexpr functions, the template is technically
4222 // ill-formed, but we allow it for sanity.
4223 continue;
4224
4225 case TSK_Undeclared:
4226 case TSK_ExplicitSpecialization:
4227 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4228 diag::err_constexpr_method_non_literal);
4229 break;
4230 }
4231
4232 // Only produce one error per class.
4233 break;
4234 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004235 }
4236 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004237
Richard Smith07b0fdc2013-03-18 21:12:30 +00004238 // Declare inheriting constructors. We do this eagerly here because:
4239 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004240 // constructors from different classes.
4241 // - The lazy declaration of the other implicit constructors is so as to not
4242 // waste space and performance on classes that are not meant to be
4243 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004244 // have inheriting constructors.
4245 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004246}
4247
Richard Smith7756afa2012-06-10 05:43:50 +00004248/// Is the special member function which would be selected to perform the
4249/// specified operation on the specified class type a constexpr constructor?
4250static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4251 Sema::CXXSpecialMember CSM,
4252 bool ConstArg) {
4253 Sema::SpecialMemberOverloadResult *SMOR =
4254 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4255 false, false, false, false);
4256 if (!SMOR || !SMOR->getMethod())
4257 // A constructor we wouldn't select can't be "involved in initializing"
4258 // anything.
4259 return true;
4260 return SMOR->getMethod()->isConstexpr();
4261}
4262
4263/// Determine whether the specified special member function would be constexpr
4264/// if it were implicitly defined.
4265static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4266 Sema::CXXSpecialMember CSM,
4267 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004268 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004269 return false;
4270
4271 // C++11 [dcl.constexpr]p4:
4272 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004273 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004274 switch (CSM) {
4275 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004276 // Since default constructor lookup is essentially trivial (and cannot
4277 // involve, for instance, template instantiation), we compute whether a
4278 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4279 //
4280 // This is important for performance; we need to know whether the default
4281 // constructor is constexpr to determine whether the type is a literal type.
4282 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4283
Richard Smith7756afa2012-06-10 05:43:50 +00004284 case Sema::CXXCopyConstructor:
4285 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004286 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004287 break;
4288
4289 case Sema::CXXCopyAssignment:
4290 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004291 if (!S.getLangOpts().CPlusPlus1y)
4292 return false;
4293 // In C++1y, we need to perform overload resolution.
4294 Ctor = false;
4295 break;
4296
Richard Smith7756afa2012-06-10 05:43:50 +00004297 case Sema::CXXDestructor:
4298 case Sema::CXXInvalid:
4299 return false;
4300 }
4301
4302 // -- if the class is a non-empty union, or for each non-empty anonymous
4303 // union member of a non-union class, exactly one non-static data member
4304 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004305 //
4306 // If we squint, this is guaranteed, since exactly one non-static data member
4307 // will be initialized (if the constructor isn't deleted), we just don't know
4308 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004309 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004310 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004311
4312 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004313 if (Ctor && ClassDecl->getNumVBases())
4314 return false;
4315
4316 // C++1y [class.copy]p26:
4317 // -- [the class] is a literal type, and
4318 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004319 return false;
4320
4321 // -- every constructor involved in initializing [...] base class
4322 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004323 // -- the assignment operator selected to copy/move each direct base
4324 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004325 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4326 BEnd = ClassDecl->bases_end();
4327 B != BEnd; ++B) {
4328 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4329 if (!BaseType) continue;
4330
4331 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4332 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4333 return false;
4334 }
4335
4336 // -- every constructor involved in initializing non-static data members
4337 // [...] shall be a constexpr constructor;
4338 // -- every non-static data member and base class sub-object shall be
4339 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004340 // -- for each non-stastic data member of X that is of class type (or array
4341 // thereof), the assignment operator selected to copy/move that member is
4342 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004343 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4344 FEnd = ClassDecl->field_end();
4345 F != FEnd; ++F) {
4346 if (F->isInvalidDecl())
4347 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004348 if (const RecordType *RecordTy =
4349 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004350 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4351 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4352 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004353 }
4354 }
4355
4356 // All OK, it's constexpr!
4357 return true;
4358}
4359
Richard Smithb9d0b762012-07-27 04:22:15 +00004360static Sema::ImplicitExceptionSpecification
4361computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4362 switch (S.getSpecialMember(MD)) {
4363 case Sema::CXXDefaultConstructor:
4364 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4365 case Sema::CXXCopyConstructor:
4366 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4367 case Sema::CXXCopyAssignment:
4368 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4369 case Sema::CXXMoveConstructor:
4370 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4371 case Sema::CXXMoveAssignment:
4372 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4373 case Sema::CXXDestructor:
4374 return S.ComputeDefaultedDtorExceptionSpec(MD);
4375 case Sema::CXXInvalid:
4376 break;
4377 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004378 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4379 "only special members have implicit exception specs");
4380 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004381}
4382
Richard Smithdd25e802012-07-30 23:48:14 +00004383static void
4384updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4385 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4386 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4387 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004388 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4389 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004390}
4391
Richard Smithb9d0b762012-07-27 04:22:15 +00004392void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4393 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4394 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4395 return;
4396
Richard Smithdd25e802012-07-30 23:48:14 +00004397 // Evaluate the exception specification.
4398 ImplicitExceptionSpecification ExceptSpec =
4399 computeImplicitExceptionSpec(*this, Loc, MD);
4400
4401 // Update the type of the special member to use it.
4402 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4403
4404 // A user-provided destructor can be defined outside the class. When that
4405 // happens, be sure to update the exception specification on both
4406 // declarations.
4407 const FunctionProtoType *CanonicalFPT =
4408 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4409 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4410 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4411 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004412}
4413
Richard Smith3003e1d2012-05-15 04:39:51 +00004414void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4415 CXXRecordDecl *RD = MD->getParent();
4416 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004417
Richard Smith3003e1d2012-05-15 04:39:51 +00004418 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4419 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004420
4421 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004422 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004423 bool First = MD == MD->getCanonicalDecl();
4424
4425 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004426
4427 // C++11 [dcl.fct.def.default]p1:
4428 // A function that is explicitly defaulted shall
4429 // -- be a special member function (checked elsewhere),
4430 // -- have the same type (except for ref-qualifiers, and except that a
4431 // copy operation can take a non-const reference) as an implicit
4432 // declaration, and
4433 // -- not have default arguments.
4434 unsigned ExpectedParams = 1;
4435 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4436 ExpectedParams = 0;
4437 if (MD->getNumParams() != ExpectedParams) {
4438 // This also checks for default arguments: a copy or move constructor with a
4439 // default argument is classified as a default constructor, and assignment
4440 // operations and destructors can't have default arguments.
4441 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4442 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004443 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004444 } else if (MD->isVariadic()) {
4445 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4446 << CSM << MD->getSourceRange();
4447 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004448 }
4449
Richard Smith3003e1d2012-05-15 04:39:51 +00004450 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004451
Richard Smith7756afa2012-06-10 05:43:50 +00004452 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004453 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004454 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004455 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004456 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004457
Richard Smith3003e1d2012-05-15 04:39:51 +00004458 QualType ReturnType = Context.VoidTy;
4459 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4460 // Check for return type matching.
4461 ReturnType = Type->getResultType();
4462 QualType ExpectedReturnType =
4463 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4464 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4465 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4466 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4467 HadError = true;
4468 }
4469
4470 // A defaulted special member cannot have cv-qualifiers.
4471 if (Type->getTypeQuals()) {
4472 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004473 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004474 HadError = true;
4475 }
4476 }
4477
4478 // Check for parameter type matching.
4479 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004480 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004481 if (ExpectedParams && ArgType->isReferenceType()) {
4482 // Argument must be reference to possibly-const T.
4483 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004484 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004485
4486 if (ReferentType.isVolatileQualified()) {
4487 Diag(MD->getLocation(),
4488 diag::err_defaulted_special_member_volatile_param) << CSM;
4489 HadError = true;
4490 }
4491
Richard Smith7756afa2012-06-10 05:43:50 +00004492 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004493 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4494 Diag(MD->getLocation(),
4495 diag::err_defaulted_special_member_copy_const_param)
4496 << (CSM == CXXCopyAssignment);
4497 // FIXME: Explain why this special member can't be const.
4498 } else {
4499 Diag(MD->getLocation(),
4500 diag::err_defaulted_special_member_move_const_param)
4501 << (CSM == CXXMoveAssignment);
4502 }
4503 HadError = true;
4504 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004505 } else if (ExpectedParams) {
4506 // A copy assignment operator can take its argument by value, but a
4507 // defaulted one cannot.
4508 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004509 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004510 HadError = true;
4511 }
Sean Huntbe631222011-05-17 20:44:43 +00004512
Richard Smith61802452011-12-22 02:22:31 +00004513 // C++11 [dcl.fct.def.default]p2:
4514 // An explicitly-defaulted function may be declared constexpr only if it
4515 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004516 // Do not apply this rule to members of class templates, since core issue 1358
4517 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004518 // functions which cannot be constexpr (for non-constructors in C++11 and for
4519 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004520 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4521 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004522 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4523 : isa<CXXConstructorDecl>(MD)) &&
4524 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004525 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4526 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004527 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004528 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004529 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004530
Richard Smith61802452011-12-22 02:22:31 +00004531 // and may have an explicit exception-specification only if it is compatible
4532 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004533 if (Type->hasExceptionSpec()) {
4534 // Delay the check if this is the first declaration of the special member,
4535 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004536 if (First) {
4537 // If the exception specification needs to be instantiated, do so now,
4538 // before we clobber it with an EST_Unevaluated specification below.
4539 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4540 InstantiateExceptionSpec(MD->getLocStart(), MD);
4541 Type = MD->getType()->getAs<FunctionProtoType>();
4542 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004543 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004544 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004545 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4546 }
Richard Smith61802452011-12-22 02:22:31 +00004547
4548 // If a function is explicitly defaulted on its first declaration,
4549 if (First) {
4550 // -- it is implicitly considered to be constexpr if the implicit
4551 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004552 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004553
Richard Smith3003e1d2012-05-15 04:39:51 +00004554 // -- it is implicitly considered to have the same exception-specification
4555 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004556 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4557 EPI.ExceptionSpecType = EST_Unevaluated;
4558 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004559 MD->setType(Context.getFunctionType(ReturnType,
4560 ArrayRef<QualType>(&ArgType,
4561 ExpectedParams),
4562 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004563 }
4564
Richard Smith3003e1d2012-05-15 04:39:51 +00004565 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004566 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004567 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004568 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004569 // C++11 [dcl.fct.def.default]p4:
4570 // [For a] user-provided explicitly-defaulted function [...] if such a
4571 // function is implicitly defined as deleted, the program is ill-formed.
4572 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4573 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004574 }
4575 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004576
Richard Smith3003e1d2012-05-15 04:39:51 +00004577 if (HadError)
4578 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004579}
4580
Richard Smith1d28caf2012-12-11 01:14:52 +00004581/// Check whether the exception specification provided for an
4582/// explicitly-defaulted special member matches the exception specification
4583/// that would have been generated for an implicit special member, per
4584/// C++11 [dcl.fct.def.default]p2.
4585void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4586 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4587 // Compute the implicit exception specification.
4588 FunctionProtoType::ExtProtoInfo EPI;
4589 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4590 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004591 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004592
4593 // Ensure that it matches.
4594 CheckEquivalentExceptionSpec(
4595 PDiag(diag::err_incorrect_defaulted_exception_spec)
4596 << getSpecialMember(MD), PDiag(),
4597 ImplicitType, SourceLocation(),
4598 SpecifiedType, MD->getLocation());
4599}
4600
4601void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4602 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4603 I != N; ++I)
4604 CheckExplicitlyDefaultedMemberExceptionSpec(
4605 DelayedDefaultedMemberExceptionSpecs[I].first,
4606 DelayedDefaultedMemberExceptionSpecs[I].second);
4607
4608 DelayedDefaultedMemberExceptionSpecs.clear();
4609}
4610
Richard Smith7d5088a2012-02-18 02:02:13 +00004611namespace {
4612struct SpecialMemberDeletionInfo {
4613 Sema &S;
4614 CXXMethodDecl *MD;
4615 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004616 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004617
4618 // Properties of the special member, computed for convenience.
4619 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4620 SourceLocation Loc;
4621
4622 bool AllFieldsAreConst;
4623
4624 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004625 Sema::CXXSpecialMember CSM, bool Diagnose)
4626 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004627 IsConstructor(false), IsAssignment(false), IsMove(false),
4628 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4629 AllFieldsAreConst(true) {
4630 switch (CSM) {
4631 case Sema::CXXDefaultConstructor:
4632 case Sema::CXXCopyConstructor:
4633 IsConstructor = true;
4634 break;
4635 case Sema::CXXMoveConstructor:
4636 IsConstructor = true;
4637 IsMove = true;
4638 break;
4639 case Sema::CXXCopyAssignment:
4640 IsAssignment = true;
4641 break;
4642 case Sema::CXXMoveAssignment:
4643 IsAssignment = true;
4644 IsMove = true;
4645 break;
4646 case Sema::CXXDestructor:
4647 break;
4648 case Sema::CXXInvalid:
4649 llvm_unreachable("invalid special member kind");
4650 }
4651
4652 if (MD->getNumParams()) {
4653 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4654 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4655 }
4656 }
4657
4658 bool inUnion() const { return MD->getParent()->isUnion(); }
4659
4660 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004661 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4662 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004663 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004664 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4665 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4666 Quals = 0;
4667 return S.LookupSpecialMember(Class, CSM,
4668 ConstArg || (Quals & Qualifiers::Const),
4669 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004670 MD->getRefQualifier() == RQ_RValue,
4671 TQ & Qualifiers::Const,
4672 TQ & Qualifiers::Volatile);
4673 }
4674
Richard Smith6c4c36c2012-03-30 20:53:28 +00004675 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004676
Richard Smith6c4c36c2012-03-30 20:53:28 +00004677 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004678 bool shouldDeleteForField(FieldDecl *FD);
4679 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004680
Richard Smith517bb842012-07-18 03:51:16 +00004681 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4682 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004683 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4684 Sema::SpecialMemberOverloadResult *SMOR,
4685 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004686
4687 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004688};
4689}
4690
John McCall12d8d802012-04-09 20:53:23 +00004691/// Is the given special member inaccessible when used on the given
4692/// sub-object.
4693bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4694 CXXMethodDecl *target) {
4695 /// If we're operating on a base class, the object type is the
4696 /// type of this special member.
4697 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004698 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004699 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4700 objectTy = S.Context.getTypeDeclType(MD->getParent());
4701 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4702
4703 // If we're operating on a field, the object type is the type of the field.
4704 } else {
4705 objectTy = S.Context.getTypeDeclType(target->getParent());
4706 }
4707
4708 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4709}
4710
Richard Smith6c4c36c2012-03-30 20:53:28 +00004711/// Check whether we should delete a special member due to the implicit
4712/// definition containing a call to a special member of a subobject.
4713bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4714 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4715 bool IsDtorCallInCtor) {
4716 CXXMethodDecl *Decl = SMOR->getMethod();
4717 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4718
4719 int DiagKind = -1;
4720
4721 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4722 DiagKind = !Decl ? 0 : 1;
4723 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4724 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004725 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004726 DiagKind = 3;
4727 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4728 !Decl->isTrivial()) {
4729 // A member of a union must have a trivial corresponding special member.
4730 // As a weird special case, a destructor call from a union's constructor
4731 // must be accessible and non-deleted, but need not be trivial. Such a
4732 // destructor is never actually called, but is semantically checked as
4733 // if it were.
4734 DiagKind = 4;
4735 }
4736
4737 if (DiagKind == -1)
4738 return false;
4739
4740 if (Diagnose) {
4741 if (Field) {
4742 S.Diag(Field->getLocation(),
4743 diag::note_deleted_special_member_class_subobject)
4744 << CSM << MD->getParent() << /*IsField*/true
4745 << Field << DiagKind << IsDtorCallInCtor;
4746 } else {
4747 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4748 S.Diag(Base->getLocStart(),
4749 diag::note_deleted_special_member_class_subobject)
4750 << CSM << MD->getParent() << /*IsField*/false
4751 << Base->getType() << DiagKind << IsDtorCallInCtor;
4752 }
4753
4754 if (DiagKind == 1)
4755 S.NoteDeletedFunction(Decl);
4756 // FIXME: Explain inaccessibility if DiagKind == 3.
4757 }
4758
4759 return true;
4760}
4761
Richard Smith9a561d52012-02-26 09:11:52 +00004762/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004763/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004764bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004765 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004766 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004767
4768 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004769 // -- any direct or virtual base class, or non-static data member with no
4770 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004771 // either M has no default constructor or overload resolution as applied
4772 // to M's default constructor results in an ambiguity or in a function
4773 // that is deleted or inaccessible
4774 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4775 // -- a direct or virtual base class B that cannot be copied/moved because
4776 // overload resolution, as applied to B's corresponding special member,
4777 // results in an ambiguity or a function that is deleted or inaccessible
4778 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004779 // C++11 [class.dtor]p5:
4780 // -- any direct or virtual base class [...] has a type with a destructor
4781 // that is deleted or inaccessible
4782 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004783 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004784 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004785 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004786
Richard Smith6c4c36c2012-03-30 20:53:28 +00004787 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4788 // -- any direct or virtual base class or non-static data member has a
4789 // type with a destructor that is deleted or inaccessible
4790 if (IsConstructor) {
4791 Sema::SpecialMemberOverloadResult *SMOR =
4792 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4793 false, false, false, false, false);
4794 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4795 return true;
4796 }
4797
Richard Smith9a561d52012-02-26 09:11:52 +00004798 return false;
4799}
4800
4801/// Check whether we should delete a special member function due to the class
4802/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004803bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004804 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004805 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004806}
4807
4808/// Check whether we should delete a special member function due to the class
4809/// having a particular non-static data member.
4810bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4811 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4812 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4813
4814 if (CSM == Sema::CXXDefaultConstructor) {
4815 // For a default constructor, all references must be initialized in-class
4816 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004817 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4818 if (Diagnose)
4819 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4820 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004821 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004822 }
Richard Smith79363f52012-02-27 06:07:25 +00004823 // C++11 [class.ctor]p5: any non-variant non-static data member of
4824 // const-qualified type (or array thereof) with no
4825 // brace-or-equal-initializer does not have a user-provided default
4826 // constructor.
4827 if (!inUnion() && FieldType.isConstQualified() &&
4828 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004829 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4830 if (Diagnose)
4831 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004832 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004833 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004834 }
4835
4836 if (inUnion() && !FieldType.isConstQualified())
4837 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004838 } else if (CSM == Sema::CXXCopyConstructor) {
4839 // For a copy constructor, data members must not be of rvalue reference
4840 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004841 if (FieldType->isRValueReferenceType()) {
4842 if (Diagnose)
4843 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4844 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004845 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004846 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004847 } else if (IsAssignment) {
4848 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004849 if (FieldType->isReferenceType()) {
4850 if (Diagnose)
4851 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4852 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004853 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004854 }
4855 if (!FieldRecord && FieldType.isConstQualified()) {
4856 // C++11 [class.copy]p23:
4857 // -- a non-static data member of const non-class type (or array thereof)
4858 if (Diagnose)
4859 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004860 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004861 return true;
4862 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004863 }
4864
4865 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004866 // Some additional restrictions exist on the variant members.
4867 if (!inUnion() && FieldRecord->isUnion() &&
4868 FieldRecord->isAnonymousStructOrUnion()) {
4869 bool AllVariantFieldsAreConst = true;
4870
Richard Smithdf8dc862012-03-29 19:00:10 +00004871 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004872 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4873 UE = FieldRecord->field_end();
4874 UI != UE; ++UI) {
4875 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004876
4877 if (!UnionFieldType.isConstQualified())
4878 AllVariantFieldsAreConst = false;
4879
Richard Smith9a561d52012-02-26 09:11:52 +00004880 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4881 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004882 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4883 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004884 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004885 }
4886
4887 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004888 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004889 FieldRecord->field_begin() != FieldRecord->field_end()) {
4890 if (Diagnose)
4891 S.Diag(FieldRecord->getLocation(),
4892 diag::note_deleted_default_ctor_all_const)
4893 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004894 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004895 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004896
Richard Smithdf8dc862012-03-29 19:00:10 +00004897 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004898 // This is technically non-conformant, but sanity demands it.
4899 return false;
4900 }
4901
Richard Smith517bb842012-07-18 03:51:16 +00004902 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4903 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004904 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004905 }
4906
4907 return false;
4908}
4909
4910/// C++11 [class.ctor] p5:
4911/// A defaulted default constructor for a class X is defined as deleted if
4912/// X is a union and all of its variant members are of const-qualified type.
4913bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004914 // This is a silly definition, because it gives an empty union a deleted
4915 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004916 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4917 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4918 if (Diagnose)
4919 S.Diag(MD->getParent()->getLocation(),
4920 diag::note_deleted_default_ctor_all_const)
4921 << MD->getParent() << /*not anonymous union*/0;
4922 return true;
4923 }
4924 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004925}
4926
4927/// Determine whether a defaulted special member function should be defined as
4928/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4929/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004930bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4931 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004932 if (MD->isInvalidDecl())
4933 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004934 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004935 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004936 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004937 return false;
4938
Richard Smith7d5088a2012-02-18 02:02:13 +00004939 // C++11 [expr.lambda.prim]p19:
4940 // The closure type associated with a lambda-expression has a
4941 // deleted (8.4.3) default constructor and a deleted copy
4942 // assignment operator.
4943 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004944 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4945 if (Diagnose)
4946 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004947 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004948 }
4949
Richard Smith5bdaac52012-04-02 20:59:25 +00004950 // For an anonymous struct or union, the copy and assignment special members
4951 // will never be used, so skip the check. For an anonymous union declared at
4952 // namespace scope, the constructor and destructor are used.
4953 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4954 RD->isAnonymousStructOrUnion())
4955 return false;
4956
Richard Smith6c4c36c2012-03-30 20:53:28 +00004957 // C++11 [class.copy]p7, p18:
4958 // If the class definition declares a move constructor or move assignment
4959 // operator, an implicitly declared copy constructor or copy assignment
4960 // operator is defined as deleted.
4961 if (MD->isImplicit() &&
4962 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4963 CXXMethodDecl *UserDeclaredMove = 0;
4964
4965 // In Microsoft mode, a user-declared move only causes the deletion of the
4966 // corresponding copy operation, not both copy operations.
4967 if (RD->hasUserDeclaredMoveConstructor() &&
4968 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4969 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004970
4971 // Find any user-declared move constructor.
4972 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4973 E = RD->ctor_end(); I != E; ++I) {
4974 if (I->isMoveConstructor()) {
4975 UserDeclaredMove = *I;
4976 break;
4977 }
4978 }
Richard Smith1c931be2012-04-02 18:40:40 +00004979 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004980 } else if (RD->hasUserDeclaredMoveAssignment() &&
4981 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4982 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004983
4984 // Find any user-declared move assignment operator.
4985 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4986 E = RD->method_end(); I != E; ++I) {
4987 if (I->isMoveAssignmentOperator()) {
4988 UserDeclaredMove = *I;
4989 break;
4990 }
4991 }
Richard Smith1c931be2012-04-02 18:40:40 +00004992 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004993 }
4994
4995 if (UserDeclaredMove) {
4996 Diag(UserDeclaredMove->getLocation(),
4997 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004998 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004999 << UserDeclaredMove->isMoveAssignmentOperator();
5000 return true;
5001 }
5002 }
Sean Hunte16da072011-10-10 06:18:57 +00005003
Richard Smith5bdaac52012-04-02 20:59:25 +00005004 // Do access control from the special member function
5005 ContextRAII MethodContext(*this, MD);
5006
Richard Smith9a561d52012-02-26 09:11:52 +00005007 // C++11 [class.dtor]p5:
5008 // -- for a virtual destructor, lookup of the non-array deallocation function
5009 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005010 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005011 FunctionDecl *OperatorDelete = 0;
5012 DeclarationName Name =
5013 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5014 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005015 OperatorDelete, false)) {
5016 if (Diagnose)
5017 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005018 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005019 }
Richard Smith9a561d52012-02-26 09:11:52 +00005020 }
5021
Richard Smith6c4c36c2012-03-30 20:53:28 +00005022 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005023
Sean Huntcdee3fe2011-05-11 22:34:38 +00005024 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005025 BE = RD->bases_end(); BI != BE; ++BI)
5026 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005027 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005028 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005029
5030 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005031 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00005032 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005033 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005034
5035 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005036 FE = RD->field_end(); FI != FE; ++FI)
5037 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005038 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005039 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005040
Richard Smith7d5088a2012-02-18 02:02:13 +00005041 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005042 return true;
5043
5044 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005045}
5046
Richard Smithac713512012-12-08 02:53:02 +00005047/// Perform lookup for a special member of the specified kind, and determine
5048/// whether it is trivial. If the triviality can be determined without the
5049/// lookup, skip it. This is intended for use when determining whether a
5050/// special member of a containing object is trivial, and thus does not ever
5051/// perform overload resolution for default constructors.
5052///
5053/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5054/// member that was most likely to be intended to be trivial, if any.
5055static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5056 Sema::CXXSpecialMember CSM, unsigned Quals,
5057 CXXMethodDecl **Selected) {
5058 if (Selected)
5059 *Selected = 0;
5060
5061 switch (CSM) {
5062 case Sema::CXXInvalid:
5063 llvm_unreachable("not a special member");
5064
5065 case Sema::CXXDefaultConstructor:
5066 // C++11 [class.ctor]p5:
5067 // A default constructor is trivial if:
5068 // - all the [direct subobjects] have trivial default constructors
5069 //
5070 // Note, no overload resolution is performed in this case.
5071 if (RD->hasTrivialDefaultConstructor())
5072 return true;
5073
5074 if (Selected) {
5075 // If there's a default constructor which could have been trivial, dig it
5076 // out. Otherwise, if there's any user-provided default constructor, point
5077 // to that as an example of why there's not a trivial one.
5078 CXXConstructorDecl *DefCtor = 0;
5079 if (RD->needsImplicitDefaultConstructor())
5080 S.DeclareImplicitDefaultConstructor(RD);
5081 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5082 CE = RD->ctor_end(); CI != CE; ++CI) {
5083 if (!CI->isDefaultConstructor())
5084 continue;
5085 DefCtor = *CI;
5086 if (!DefCtor->isUserProvided())
5087 break;
5088 }
5089
5090 *Selected = DefCtor;
5091 }
5092
5093 return false;
5094
5095 case Sema::CXXDestructor:
5096 // C++11 [class.dtor]p5:
5097 // A destructor is trivial if:
5098 // - all the direct [subobjects] have trivial destructors
5099 if (RD->hasTrivialDestructor())
5100 return true;
5101
5102 if (Selected) {
5103 if (RD->needsImplicitDestructor())
5104 S.DeclareImplicitDestructor(RD);
5105 *Selected = RD->getDestructor();
5106 }
5107
5108 return false;
5109
5110 case Sema::CXXCopyConstructor:
5111 // C++11 [class.copy]p12:
5112 // A copy constructor is trivial if:
5113 // - the constructor selected to copy each direct [subobject] is trivial
5114 if (RD->hasTrivialCopyConstructor()) {
5115 if (Quals == Qualifiers::Const)
5116 // We must either select the trivial copy constructor or reach an
5117 // ambiguity; no need to actually perform overload resolution.
5118 return true;
5119 } else if (!Selected) {
5120 return false;
5121 }
5122 // In C++98, we are not supposed to perform overload resolution here, but we
5123 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5124 // cases like B as having a non-trivial copy constructor:
5125 // struct A { template<typename T> A(T&); };
5126 // struct B { mutable A a; };
5127 goto NeedOverloadResolution;
5128
5129 case Sema::CXXCopyAssignment:
5130 // C++11 [class.copy]p25:
5131 // A copy assignment operator is trivial if:
5132 // - the assignment operator selected to copy each direct [subobject] is
5133 // trivial
5134 if (RD->hasTrivialCopyAssignment()) {
5135 if (Quals == Qualifiers::Const)
5136 return true;
5137 } else if (!Selected) {
5138 return false;
5139 }
5140 // In C++98, we are not supposed to perform overload resolution here, but we
5141 // treat that as a language defect.
5142 goto NeedOverloadResolution;
5143
5144 case Sema::CXXMoveConstructor:
5145 case Sema::CXXMoveAssignment:
5146 NeedOverloadResolution:
5147 Sema::SpecialMemberOverloadResult *SMOR =
5148 S.LookupSpecialMember(RD, CSM,
5149 Quals & Qualifiers::Const,
5150 Quals & Qualifiers::Volatile,
5151 /*RValueThis*/false, /*ConstThis*/false,
5152 /*VolatileThis*/false);
5153
5154 // The standard doesn't describe how to behave if the lookup is ambiguous.
5155 // We treat it as not making the member non-trivial, just like the standard
5156 // mandates for the default constructor. This should rarely matter, because
5157 // the member will also be deleted.
5158 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5159 return true;
5160
5161 if (!SMOR->getMethod()) {
5162 assert(SMOR->getKind() ==
5163 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5164 return false;
5165 }
5166
5167 // We deliberately don't check if we found a deleted special member. We're
5168 // not supposed to!
5169 if (Selected)
5170 *Selected = SMOR->getMethod();
5171 return SMOR->getMethod()->isTrivial();
5172 }
5173
5174 llvm_unreachable("unknown special method kind");
5175}
5176
Benjamin Kramera574c892013-02-15 12:30:38 +00005177static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005178 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5179 CI != CE; ++CI)
5180 if (!CI->isImplicit())
5181 return *CI;
5182
5183 // Look for constructor templates.
5184 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5185 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5186 if (CXXConstructorDecl *CD =
5187 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5188 return CD;
5189 }
5190
5191 return 0;
5192}
5193
5194/// The kind of subobject we are checking for triviality. The values of this
5195/// enumeration are used in diagnostics.
5196enum TrivialSubobjectKind {
5197 /// The subobject is a base class.
5198 TSK_BaseClass,
5199 /// The subobject is a non-static data member.
5200 TSK_Field,
5201 /// The object is actually the complete object.
5202 TSK_CompleteObject
5203};
5204
5205/// Check whether the special member selected for a given type would be trivial.
5206static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5207 QualType SubType,
5208 Sema::CXXSpecialMember CSM,
5209 TrivialSubobjectKind Kind,
5210 bool Diagnose) {
5211 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5212 if (!SubRD)
5213 return true;
5214
5215 CXXMethodDecl *Selected;
5216 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5217 Diagnose ? &Selected : 0))
5218 return true;
5219
5220 if (Diagnose) {
5221 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5222 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5223 << Kind << SubType.getUnqualifiedType();
5224 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5225 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5226 } else if (!Selected)
5227 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5228 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5229 else if (Selected->isUserProvided()) {
5230 if (Kind == TSK_CompleteObject)
5231 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5232 << Kind << SubType.getUnqualifiedType() << CSM;
5233 else {
5234 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5235 << Kind << SubType.getUnqualifiedType() << CSM;
5236 S.Diag(Selected->getLocation(), diag::note_declared_at);
5237 }
5238 } else {
5239 if (Kind != TSK_CompleteObject)
5240 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5241 << Kind << SubType.getUnqualifiedType() << CSM;
5242
5243 // Explain why the defaulted or deleted special member isn't trivial.
5244 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5245 }
5246 }
5247
5248 return false;
5249}
5250
5251/// Check whether the members of a class type allow a special member to be
5252/// trivial.
5253static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5254 Sema::CXXSpecialMember CSM,
5255 bool ConstArg, bool Diagnose) {
5256 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5257 FE = RD->field_end(); FI != FE; ++FI) {
5258 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5259 continue;
5260
5261 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5262
5263 // Pretend anonymous struct or union members are members of this class.
5264 if (FI->isAnonymousStructOrUnion()) {
5265 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5266 CSM, ConstArg, Diagnose))
5267 return false;
5268 continue;
5269 }
5270
5271 // C++11 [class.ctor]p5:
5272 // A default constructor is trivial if [...]
5273 // -- no non-static data member of its class has a
5274 // brace-or-equal-initializer
5275 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5276 if (Diagnose)
5277 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5278 return false;
5279 }
5280
5281 // Objective C ARC 4.3.5:
5282 // [...] nontrivally ownership-qualified types are [...] not trivially
5283 // default constructible, copy constructible, move constructible, copy
5284 // assignable, move assignable, or destructible [...]
5285 if (S.getLangOpts().ObjCAutoRefCount &&
5286 FieldType.hasNonTrivialObjCLifetime()) {
5287 if (Diagnose)
5288 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5289 << RD << FieldType.getObjCLifetime();
5290 return false;
5291 }
5292
5293 if (ConstArg && !FI->isMutable())
5294 FieldType.addConst();
5295 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5296 TSK_Field, Diagnose))
5297 return false;
5298 }
5299
5300 return true;
5301}
5302
5303/// Diagnose why the specified class does not have a trivial special member of
5304/// the given kind.
5305void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5306 QualType Ty = Context.getRecordType(RD);
5307 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5308 Ty.addConst();
5309
5310 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5311 TSK_CompleteObject, /*Diagnose*/true);
5312}
5313
5314/// Determine whether a defaulted or deleted special member function is trivial,
5315/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5316/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5317bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5318 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005319 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5320
5321 CXXRecordDecl *RD = MD->getParent();
5322
5323 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005324
5325 // C++11 [class.copy]p12, p25:
5326 // A [special member] is trivial if its declared parameter type is the same
5327 // as if it had been implicitly declared [...]
5328 switch (CSM) {
5329 case CXXDefaultConstructor:
5330 case CXXDestructor:
5331 // Trivial default constructors and destructors cannot have parameters.
5332 break;
5333
5334 case CXXCopyConstructor:
5335 case CXXCopyAssignment: {
5336 // Trivial copy operations always have const, non-volatile parameter types.
5337 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005338 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005339 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5340 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5341 if (Diagnose)
5342 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5343 << Param0->getSourceRange() << Param0->getType()
5344 << Context.getLValueReferenceType(
5345 Context.getRecordType(RD).withConst());
5346 return false;
5347 }
5348 break;
5349 }
5350
5351 case CXXMoveConstructor:
5352 case CXXMoveAssignment: {
5353 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005354 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005355 const RValueReferenceType *RT =
5356 Param0->getType()->getAs<RValueReferenceType>();
5357 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5358 if (Diagnose)
5359 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5360 << Param0->getSourceRange() << Param0->getType()
5361 << Context.getRValueReferenceType(Context.getRecordType(RD));
5362 return false;
5363 }
5364 break;
5365 }
5366
5367 case CXXInvalid:
5368 llvm_unreachable("not a special member");
5369 }
5370
5371 // FIXME: We require that the parameter-declaration-clause is equivalent to
5372 // that of an implicit declaration, not just that the declared parameter type
5373 // matches, in order to prevent absuridities like a function simultaneously
5374 // being a trivial copy constructor and a non-trivial default constructor.
5375 // This issue has not yet been assigned a core issue number.
5376 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5377 if (Diagnose)
5378 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5379 diag::note_nontrivial_default_arg)
5380 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5381 return false;
5382 }
5383 if (MD->isVariadic()) {
5384 if (Diagnose)
5385 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5386 return false;
5387 }
5388
5389 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5390 // A copy/move [constructor or assignment operator] is trivial if
5391 // -- the [member] selected to copy/move each direct base class subobject
5392 // is trivial
5393 //
5394 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5395 // A [default constructor or destructor] is trivial if
5396 // -- all the direct base classes have trivial [default constructors or
5397 // destructors]
5398 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5399 BE = RD->bases_end(); BI != BE; ++BI)
5400 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5401 ConstArg ? BI->getType().withConst()
5402 : BI->getType(),
5403 CSM, TSK_BaseClass, Diagnose))
5404 return false;
5405
5406 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5407 // A copy/move [constructor or assignment operator] for a class X is
5408 // trivial if
5409 // -- for each non-static data member of X that is of class type (or array
5410 // thereof), the constructor selected to copy/move that member is
5411 // trivial
5412 //
5413 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5414 // A [default constructor or destructor] is trivial if
5415 // -- for all of the non-static data members of its class that are of class
5416 // type (or array thereof), each such class has a trivial [default
5417 // constructor or destructor]
5418 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5419 return false;
5420
5421 // C++11 [class.dtor]p5:
5422 // A destructor is trivial if [...]
5423 // -- the destructor is not virtual
5424 if (CSM == CXXDestructor && MD->isVirtual()) {
5425 if (Diagnose)
5426 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5427 return false;
5428 }
5429
5430 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5431 // A [special member] for class X is trivial if [...]
5432 // -- class X has no virtual functions and no virtual base classes
5433 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5434 if (!Diagnose)
5435 return false;
5436
5437 if (RD->getNumVBases()) {
5438 // Check for virtual bases. We already know that the corresponding
5439 // member in all bases is trivial, so vbases must all be direct.
5440 CXXBaseSpecifier &BS = *RD->vbases_begin();
5441 assert(BS.isVirtual());
5442 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5443 return false;
5444 }
5445
5446 // Must have a virtual method.
5447 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5448 ME = RD->method_end(); MI != ME; ++MI) {
5449 if (MI->isVirtual()) {
5450 SourceLocation MLoc = MI->getLocStart();
5451 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5452 return false;
5453 }
5454 }
5455
5456 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5457 }
5458
5459 // Looks like it's trivial!
5460 return true;
5461}
5462
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005463/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005464namespace {
5465 struct FindHiddenVirtualMethodData {
5466 Sema *S;
5467 CXXMethodDecl *Method;
5468 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005469 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005470 };
5471}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005472
David Blaikie5f750682012-10-19 00:53:08 +00005473/// \brief Check whether any most overriden method from MD in Methods
5474static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5475 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5476 if (MD->size_overridden_methods() == 0)
5477 return Methods.count(MD->getCanonicalDecl());
5478 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5479 E = MD->end_overridden_methods();
5480 I != E; ++I)
5481 if (CheckMostOverridenMethods(*I, Methods))
5482 return true;
5483 return false;
5484}
5485
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005486/// \brief Member lookup function that determines whether a given C++
5487/// method overloads virtual methods in a base class without overriding any,
5488/// to be used with CXXRecordDecl::lookupInBases().
5489static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5490 CXXBasePath &Path,
5491 void *UserData) {
5492 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5493
5494 FindHiddenVirtualMethodData &Data
5495 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5496
5497 DeclarationName Name = Data.Method->getDeclName();
5498 assert(Name.getNameKind() == DeclarationName::Identifier);
5499
5500 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005501 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005502 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005503 !Path.Decls.empty();
5504 Path.Decls = Path.Decls.slice(1)) {
5505 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005506 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005507 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005508 foundSameNameMethod = true;
5509 // Interested only in hidden virtual methods.
5510 if (!MD->isVirtual())
5511 continue;
5512 // If the method we are checking overrides a method from its base
5513 // don't warn about the other overloaded methods.
5514 if (!Data.S->IsOverload(Data.Method, MD, false))
5515 return true;
5516 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005517 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005518 overloadedMethods.push_back(MD);
5519 }
5520 }
5521
5522 if (foundSameNameMethod)
5523 Data.OverloadedMethods.append(overloadedMethods.begin(),
5524 overloadedMethods.end());
5525 return foundSameNameMethod;
5526}
5527
David Blaikie5f750682012-10-19 00:53:08 +00005528/// \brief Add the most overriden methods from MD to Methods
5529static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5530 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5531 if (MD->size_overridden_methods() == 0)
5532 Methods.insert(MD->getCanonicalDecl());
5533 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5534 E = MD->end_overridden_methods();
5535 I != E; ++I)
5536 AddMostOverridenMethods(*I, Methods);
5537}
5538
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005539/// \brief See if a method overloads virtual methods in a base class without
5540/// overriding any.
5541void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5542 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005543 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005544 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005545 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005546 return;
5547
5548 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5549 /*bool RecordPaths=*/false,
5550 /*bool DetectVirtual=*/false);
5551 FindHiddenVirtualMethodData Data;
5552 Data.Method = MD;
5553 Data.S = this;
5554
5555 // Keep the base methods that were overriden or introduced in the subclass
5556 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005557 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5558 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5559 NamedDecl *ND = *I;
5560 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005561 ND = shad->getTargetDecl();
5562 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5563 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005564 }
5565
5566 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5567 !Data.OverloadedMethods.empty()) {
5568 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5569 << MD << (Data.OverloadedMethods.size() > 1);
5570
5571 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5572 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005573 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005574 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005575 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5576 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005577 }
5578 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005579}
5580
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005581void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005582 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005583 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005584 SourceLocation RBrac,
5585 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005586 if (!TagDecl)
5587 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005588
Douglas Gregor42af25f2009-05-11 19:58:34 +00005589 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005590
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005591 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5592 if (l->getKind() != AttributeList::AT_Visibility)
5593 continue;
5594 l->setInvalid();
5595 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5596 l->getName();
5597 }
5598
David Blaikie77b6de02011-09-22 02:58:26 +00005599 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005600 // strict aliasing violation!
5601 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005602 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005603
Douglas Gregor23c94db2010-07-02 17:43:08 +00005604 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005605 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005606}
5607
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005608/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5609/// special functions, such as the default constructor, copy
5610/// constructor, or destructor, to the given C++ class (C++
5611/// [special]p1). This routine can only be executed just before the
5612/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005613void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005614 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005615 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005616
Richard Smithbc2a35d2012-12-08 08:32:28 +00005617 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005618 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005619
Richard Smithbc2a35d2012-12-08 08:32:28 +00005620 // If the properties or semantics of the copy constructor couldn't be
5621 // determined while the class was being declared, force a declaration
5622 // of it now.
5623 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5624 DeclareImplicitCopyConstructor(ClassDecl);
5625 }
5626
Richard Smith80ad52f2013-01-02 11:42:31 +00005627 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005628 ++ASTContext::NumImplicitMoveConstructors;
5629
Richard Smithbc2a35d2012-12-08 08:32:28 +00005630 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5631 DeclareImplicitMoveConstructor(ClassDecl);
5632 }
5633
Douglas Gregora376d102010-07-02 21:50:04 +00005634 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5635 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005636
5637 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005638 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005639 // it shows up in the right place in the vtable and that we diagnose
5640 // problems with the implicit exception specification.
5641 if (ClassDecl->isDynamicClass() ||
5642 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005643 DeclareImplicitCopyAssignment(ClassDecl);
5644 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005645
Richard Smith80ad52f2013-01-02 11:42:31 +00005646 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005647 ++ASTContext::NumImplicitMoveAssignmentOperators;
5648
5649 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005650 if (ClassDecl->isDynamicClass() ||
5651 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005652 DeclareImplicitMoveAssignment(ClassDecl);
5653 }
5654
Douglas Gregor4923aa22010-07-02 20:37:36 +00005655 if (!ClassDecl->hasUserDeclaredDestructor()) {
5656 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005657
5658 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005659 // have to declare the destructor immediately. This ensures that, e.g., it
5660 // shows up in the right place in the vtable and that we diagnose problems
5661 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005662 if (ClassDecl->isDynamicClass() ||
5663 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005664 DeclareImplicitDestructor(ClassDecl);
5665 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005666}
5667
Francois Pichet8387e2a2011-04-22 22:18:13 +00005668void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5669 if (!D)
5670 return;
5671
5672 int NumParamList = D->getNumTemplateParameterLists();
5673 for (int i = 0; i < NumParamList; i++) {
5674 TemplateParameterList* Params = D->getTemplateParameterList(i);
5675 for (TemplateParameterList::iterator Param = Params->begin(),
5676 ParamEnd = Params->end();
5677 Param != ParamEnd; ++Param) {
5678 NamedDecl *Named = cast<NamedDecl>(*Param);
5679 if (Named->getDeclName()) {
5680 S->AddDecl(Named);
5681 IdResolver.AddDecl(Named);
5682 }
5683 }
5684 }
5685}
5686
John McCalld226f652010-08-21 09:40:31 +00005687void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005688 if (!D)
5689 return;
5690
5691 TemplateParameterList *Params = 0;
5692 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5693 Params = Template->getTemplateParameters();
5694 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5695 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5696 Params = PartialSpec->getTemplateParameters();
5697 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005698 return;
5699
Douglas Gregor6569d682009-05-27 23:11:45 +00005700 for (TemplateParameterList::iterator Param = Params->begin(),
5701 ParamEnd = Params->end();
5702 Param != ParamEnd; ++Param) {
5703 NamedDecl *Named = cast<NamedDecl>(*Param);
5704 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005705 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005706 IdResolver.AddDecl(Named);
5707 }
5708 }
5709}
5710
John McCalld226f652010-08-21 09:40:31 +00005711void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005712 if (!RecordD) return;
5713 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005714 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005715 PushDeclContext(S, Record);
5716}
5717
John McCalld226f652010-08-21 09:40:31 +00005718void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005719 if (!RecordD) return;
5720 PopDeclContext();
5721}
5722
Douglas Gregor72b505b2008-12-16 21:30:33 +00005723/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5724/// parsing a top-level (non-nested) C++ class, and we are now
5725/// parsing those parts of the given Method declaration that could
5726/// not be parsed earlier (C++ [class.mem]p2), such as default
5727/// arguments. This action should enter the scope of the given
5728/// Method declaration as if we had just parsed the qualified method
5729/// name. However, it should not bring the parameters into scope;
5730/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005731void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005732}
5733
5734/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5735/// C++ method declaration. We're (re-)introducing the given
5736/// function parameter into scope for use in parsing later parts of
5737/// the method declaration. For example, we could see an
5738/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005739void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005740 if (!ParamD)
5741 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005742
John McCalld226f652010-08-21 09:40:31 +00005743 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005744
5745 // If this parameter has an unparsed default argument, clear it out
5746 // to make way for the parsed default argument.
5747 if (Param->hasUnparsedDefaultArg())
5748 Param->setDefaultArg(0);
5749
John McCalld226f652010-08-21 09:40:31 +00005750 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005751 if (Param->getDeclName())
5752 IdResolver.AddDecl(Param);
5753}
5754
5755/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5756/// processing the delayed method declaration for Method. The method
5757/// declaration is now considered finished. There may be a separate
5758/// ActOnStartOfFunctionDef action later (not necessarily
5759/// immediately!) for this method, if it was also defined inside the
5760/// class body.
John McCalld226f652010-08-21 09:40:31 +00005761void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005762 if (!MethodD)
5763 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005764
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005765 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005766
John McCalld226f652010-08-21 09:40:31 +00005767 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005768
5769 // Now that we have our default arguments, check the constructor
5770 // again. It could produce additional diagnostics or affect whether
5771 // the class has implicitly-declared destructors, among other
5772 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005773 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5774 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005775
5776 // Check the default arguments, which we may have added.
5777 if (!Method->isInvalidDecl())
5778 CheckCXXDefaultArguments(Method);
5779}
5780
Douglas Gregor42a552f2008-11-05 20:51:48 +00005781/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005782/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005783/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005784/// emit diagnostics and set the invalid bit to true. In any case, the type
5785/// will be updated to reflect a well-formed type for the constructor and
5786/// returned.
5787QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005788 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005789 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005790
5791 // C++ [class.ctor]p3:
5792 // A constructor shall not be virtual (10.3) or static (9.4). A
5793 // constructor can be invoked for a const, volatile or const
5794 // volatile object. A constructor shall not be declared const,
5795 // volatile, or const volatile (9.3.2).
5796 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005797 if (!D.isInvalidType())
5798 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5799 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5800 << SourceRange(D.getIdentifierLoc());
5801 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005802 }
John McCalld931b082010-08-26 03:08:43 +00005803 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005804 if (!D.isInvalidType())
5805 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5806 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5807 << SourceRange(D.getIdentifierLoc());
5808 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005809 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005810 }
Mike Stump1eb44332009-09-09 15:08:12 +00005811
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005812 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005813 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005814 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005815 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5816 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005817 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005818 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5819 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005820 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005821 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5822 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005823 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005824 }
Mike Stump1eb44332009-09-09 15:08:12 +00005825
Douglas Gregorc938c162011-01-26 05:01:58 +00005826 // C++0x [class.ctor]p4:
5827 // A constructor shall not be declared with a ref-qualifier.
5828 if (FTI.hasRefQualifier()) {
5829 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5830 << FTI.RefQualifierIsLValueRef
5831 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5832 D.setInvalidType();
5833 }
5834
Douglas Gregor42a552f2008-11-05 20:51:48 +00005835 // Rebuild the function type "R" without any type qualifiers (in
5836 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005837 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005838 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005839 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5840 return R;
5841
5842 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5843 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005844 EPI.RefQualifier = RQ_None;
5845
Richard Smith07b0fdc2013-03-18 21:12:30 +00005846 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005847}
5848
Douglas Gregor72b505b2008-12-16 21:30:33 +00005849/// CheckConstructor - Checks a fully-formed constructor for
5850/// well-formedness, issuing any diagnostics required. Returns true if
5851/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005852void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005853 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005854 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5855 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005856 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005857
5858 // C++ [class.copy]p3:
5859 // A declaration of a constructor for a class X is ill-formed if
5860 // its first parameter is of type (optionally cv-qualified) X and
5861 // either there are no other parameters or else all other
5862 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005863 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005864 ((Constructor->getNumParams() == 1) ||
5865 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005866 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5867 Constructor->getTemplateSpecializationKind()
5868 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005869 QualType ParamType = Constructor->getParamDecl(0)->getType();
5870 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5871 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005872 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005873 const char *ConstRef
5874 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5875 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005876 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005877 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005878
5879 // FIXME: Rather that making the constructor invalid, we should endeavor
5880 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005881 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005882 }
5883 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005884}
5885
John McCall15442822010-08-04 01:04:25 +00005886/// CheckDestructor - Checks a fully-formed destructor definition for
5887/// well-formedness, issuing any diagnostics required. Returns true
5888/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005889bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005890 CXXRecordDecl *RD = Destructor->getParent();
5891
Peter Collingbournef51cfb82013-05-20 14:12:25 +00005892 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005893 SourceLocation Loc;
5894
5895 if (!Destructor->isImplicit())
5896 Loc = Destructor->getLocation();
5897 else
5898 Loc = RD->getLocation();
5899
5900 // If we have a virtual destructor, look up the deallocation function
5901 FunctionDecl *OperatorDelete = 0;
5902 DeclarationName Name =
5903 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005904 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005905 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005906
Eli Friedman5f2987c2012-02-02 03:46:19 +00005907 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005908
5909 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005910 }
Anders Carlsson37909802009-11-30 21:24:50 +00005911
5912 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005913}
5914
Mike Stump1eb44332009-09-09 15:08:12 +00005915static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005916FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5917 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5918 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005919 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005920}
5921
Douglas Gregor42a552f2008-11-05 20:51:48 +00005922/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5923/// the well-formednes of the destructor declarator @p D with type @p
5924/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005925/// emit diagnostics and set the declarator to invalid. Even if this happens,
5926/// will be updated to reflect a well-formed type for the destructor and
5927/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005928QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005929 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005930 // C++ [class.dtor]p1:
5931 // [...] A typedef-name that names a class is a class-name
5932 // (7.1.3); however, a typedef-name that names a class shall not
5933 // be used as the identifier in the declarator for a destructor
5934 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005935 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005936 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005937 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005938 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005939 else if (const TemplateSpecializationType *TST =
5940 DeclaratorType->getAs<TemplateSpecializationType>())
5941 if (TST->isTypeAlias())
5942 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5943 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005944
5945 // C++ [class.dtor]p2:
5946 // A destructor is used to destroy objects of its class type. A
5947 // destructor takes no parameters, and no return type can be
5948 // specified for it (not even void). The address of a destructor
5949 // shall not be taken. A destructor shall not be static. A
5950 // destructor can be invoked for a const, volatile or const
5951 // volatile object. A destructor shall not be declared const,
5952 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005953 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005954 if (!D.isInvalidType())
5955 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5956 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005957 << SourceRange(D.getIdentifierLoc())
5958 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5959
John McCalld931b082010-08-26 03:08:43 +00005960 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005961 }
Chris Lattner65401802009-04-25 08:28:21 +00005962 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005963 // Destructors don't have return types, but the parser will
5964 // happily parse something like:
5965 //
5966 // class X {
5967 // float ~X();
5968 // };
5969 //
5970 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005971 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5972 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5973 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005974 }
Mike Stump1eb44332009-09-09 15:08:12 +00005975
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005976 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005977 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005978 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005979 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5980 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005981 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005982 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5983 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005984 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005985 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5986 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005987 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005988 }
5989
Douglas Gregorc938c162011-01-26 05:01:58 +00005990 // C++0x [class.dtor]p2:
5991 // A destructor shall not be declared with a ref-qualifier.
5992 if (FTI.hasRefQualifier()) {
5993 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5994 << FTI.RefQualifierIsLValueRef
5995 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5996 D.setInvalidType();
5997 }
5998
Douglas Gregor42a552f2008-11-05 20:51:48 +00005999 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006000 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006001 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6002
6003 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006004 FTI.freeArgs();
6005 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006006 }
6007
Mike Stump1eb44332009-09-09 15:08:12 +00006008 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006009 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006010 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006011 D.setInvalidType();
6012 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006013
6014 // Rebuild the function type "R" without any type qualifiers or
6015 // parameters (in case any of the errors above fired) and with
6016 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006017 // types.
John McCalle23cf432010-12-14 08:05:40 +00006018 if (!D.isInvalidType())
6019 return R;
6020
Douglas Gregord92ec472010-07-01 05:10:53 +00006021 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006022 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6023 EPI.Variadic = false;
6024 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006025 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006026 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006027}
6028
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006029/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6030/// well-formednes of the conversion function declarator @p D with
6031/// type @p R. If there are any errors in the declarator, this routine
6032/// will emit diagnostics and return true. Otherwise, it will return
6033/// false. Either way, the type @p R will be updated to reflect a
6034/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006035void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006036 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006037 // C++ [class.conv.fct]p1:
6038 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006039 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006040 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006041 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006042 if (!D.isInvalidType())
6043 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006044 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6045 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006046 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006047 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006048 }
John McCalla3f81372010-04-13 00:04:31 +00006049
6050 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6051
Chris Lattner6e475012009-04-25 08:35:12 +00006052 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006053 // Conversion functions don't have return types, but the parser will
6054 // happily parse something like:
6055 //
6056 // class X {
6057 // float operator bool();
6058 // };
6059 //
6060 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006061 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6062 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6063 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006064 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006065 }
6066
John McCalla3f81372010-04-13 00:04:31 +00006067 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6068
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006069 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006070 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006071 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6072
6073 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006074 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006075 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006076 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006077 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006078 D.setInvalidType();
6079 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006080
John McCalla3f81372010-04-13 00:04:31 +00006081 // Diagnose "&operator bool()" and other such nonsense. This
6082 // is actually a gcc extension which we don't support.
6083 if (Proto->getResultType() != ConvType) {
6084 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6085 << Proto->getResultType();
6086 D.setInvalidType();
6087 ConvType = Proto->getResultType();
6088 }
6089
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006090 // C++ [class.conv.fct]p4:
6091 // The conversion-type-id shall not represent a function type nor
6092 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006093 if (ConvType->isArrayType()) {
6094 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6095 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006096 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006097 } else if (ConvType->isFunctionType()) {
6098 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6099 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006100 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006101 }
6102
6103 // Rebuild the function type "R" without any parameters (in case any
6104 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006105 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006106 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006107 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006108
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006109 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006110 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006111 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006112 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006113 diag::warn_cxx98_compat_explicit_conversion_functions :
6114 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006115 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006116}
6117
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006118/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6119/// the declaration of the given C++ conversion function. This routine
6120/// is responsible for recording the conversion function in the C++
6121/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006122Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006123 assert(Conversion && "Expected to receive a conversion function declaration");
6124
Douglas Gregor9d350972008-12-12 08:25:50 +00006125 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006126
6127 // Make sure we aren't redeclaring the conversion function.
6128 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006129
6130 // C++ [class.conv.fct]p1:
6131 // [...] A conversion function is never used to convert a
6132 // (possibly cv-qualified) object to the (possibly cv-qualified)
6133 // same object type (or a reference to it), to a (possibly
6134 // cv-qualified) base class of that type (or a reference to it),
6135 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006136 // FIXME: Suppress this warning if the conversion function ends up being a
6137 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006138 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006139 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006140 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006141 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006142 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6143 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006144 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006145 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006146 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6147 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006148 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006149 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006150 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006151 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006152 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006153 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006154 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006155 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006156 }
6157
Douglas Gregore80622f2010-09-29 04:25:11 +00006158 if (FunctionTemplateDecl *ConversionTemplate
6159 = Conversion->getDescribedFunctionTemplate())
6160 return ConversionTemplate;
6161
John McCalld226f652010-08-21 09:40:31 +00006162 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006163}
6164
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006165//===----------------------------------------------------------------------===//
6166// Namespace Handling
6167//===----------------------------------------------------------------------===//
6168
Richard Smithd1a55a62012-10-04 22:13:39 +00006169/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6170/// reopened.
6171static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6172 SourceLocation Loc,
6173 IdentifierInfo *II, bool *IsInline,
6174 NamespaceDecl *PrevNS) {
6175 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006176
Richard Smithc969e6a2012-10-05 01:46:25 +00006177 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6178 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6179 // inline namespaces, with the intention of bringing names into namespace std.
6180 //
6181 // We support this just well enough to get that case working; this is not
6182 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006183 if (*IsInline && II && II->getName().startswith("__atomic") &&
6184 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006185 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006186 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6187 NS = NS->getPreviousDecl())
6188 NS->setInline(*IsInline);
6189 // Patch up the lookup table for the containing namespace. This isn't really
6190 // correct, but it's good enough for this particular case.
6191 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6192 E = PrevNS->decls_end(); I != E; ++I)
6193 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6194 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6195 return;
6196 }
6197
6198 if (PrevNS->isInline())
6199 // The user probably just forgot the 'inline', so suggest that it
6200 // be added back.
6201 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6202 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6203 else
6204 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6205 << IsInline;
6206
6207 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6208 *IsInline = PrevNS->isInline();
6209}
John McCallea318642010-08-26 09:15:37 +00006210
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006211/// ActOnStartNamespaceDef - This is called at the start of a namespace
6212/// definition.
John McCalld226f652010-08-21 09:40:31 +00006213Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006214 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006215 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006216 SourceLocation IdentLoc,
6217 IdentifierInfo *II,
6218 SourceLocation LBrace,
6219 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006220 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6221 // For anonymous namespace, take the location of the left brace.
6222 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006223 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006224 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006225 bool IsStd = false;
6226 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006227 Scope *DeclRegionScope = NamespcScope->getParent();
6228
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006229 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006230 if (II) {
6231 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006232 // The identifier in an original-namespace-definition shall not
6233 // have been previously defined in the declarative region in
6234 // which the original-namespace-definition appears. The
6235 // identifier in an original-namespace-definition is the name of
6236 // the namespace. Subsequently in that declarative region, it is
6237 // treated as an original-namespace-name.
6238 //
6239 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006240 // look through using directives, just look for any ordinary names.
6241
6242 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006243 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6244 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006245 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006246 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6247 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6248 ++I) {
6249 if ((*I)->getIdentifierNamespace() & IDNS) {
6250 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006251 break;
6252 }
6253 }
6254
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006255 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6256
6257 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006258 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006259 if (IsInline != PrevNS->isInline())
6260 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6261 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006262 } else if (PrevDecl) {
6263 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006264 Diag(Loc, diag::err_redefinition_different_kind)
6265 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006266 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006267 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006268 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006269 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006270 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006271 // This is the first "real" definition of the namespace "std", so update
6272 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006273 PrevNS = getStdNamespace();
6274 IsStd = true;
6275 AddToKnown = !IsInline;
6276 } else {
6277 // We've seen this namespace for the first time.
6278 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006279 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006280 } else {
John McCall9aeed322009-10-01 00:25:31 +00006281 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006282
6283 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006284 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006285 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006286 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006287 } else {
6288 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006289 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006290 }
6291
Richard Smithd1a55a62012-10-04 22:13:39 +00006292 if (PrevNS && IsInline != PrevNS->isInline())
6293 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6294 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006295 }
6296
6297 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6298 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006299 if (IsInvalid)
6300 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006301
6302 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006303
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006304 // FIXME: Should we be merging attributes?
6305 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006306 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006307
6308 if (IsStd)
6309 StdNamespace = Namespc;
6310 if (AddToKnown)
6311 KnownNamespaces[Namespc] = false;
6312
6313 if (II) {
6314 PushOnScopeChains(Namespc, DeclRegionScope);
6315 } else {
6316 // Link the anonymous namespace into its parent.
6317 DeclContext *Parent = CurContext->getRedeclContext();
6318 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6319 TU->setAnonymousNamespace(Namespc);
6320 } else {
6321 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006322 }
John McCall9aeed322009-10-01 00:25:31 +00006323
Douglas Gregora4181472010-03-24 00:46:35 +00006324 CurContext->addDecl(Namespc);
6325
John McCall9aeed322009-10-01 00:25:31 +00006326 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6327 // behaves as if it were replaced by
6328 // namespace unique { /* empty body */ }
6329 // using namespace unique;
6330 // namespace unique { namespace-body }
6331 // where all occurrences of 'unique' in a translation unit are
6332 // replaced by the same identifier and this identifier differs
6333 // from all other identifiers in the entire program.
6334
6335 // We just create the namespace with an empty name and then add an
6336 // implicit using declaration, just like the standard suggests.
6337 //
6338 // CodeGen enforces the "universally unique" aspect by giving all
6339 // declarations semantically contained within an anonymous
6340 // namespace internal linkage.
6341
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006342 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006343 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006344 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006345 /* 'using' */ LBrace,
6346 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006347 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006348 /* identifier */ SourceLocation(),
6349 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006350 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006351 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006352 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006353 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006354 }
6355
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006356 ActOnDocumentableDecl(Namespc);
6357
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006358 // Although we could have an invalid decl (i.e. the namespace name is a
6359 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006360 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6361 // for the namespace has the declarations that showed up in that particular
6362 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006363 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006364 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006365}
6366
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006367/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6368/// is a namespace alias, returns the namespace it points to.
6369static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6370 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6371 return AD->getNamespace();
6372 return dyn_cast_or_null<NamespaceDecl>(D);
6373}
6374
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006375/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6376/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006377void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006378 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6379 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006380 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006381 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006382 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006383 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006384}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006385
John McCall384aff82010-08-25 07:42:41 +00006386CXXRecordDecl *Sema::getStdBadAlloc() const {
6387 return cast_or_null<CXXRecordDecl>(
6388 StdBadAlloc.get(Context.getExternalSource()));
6389}
6390
6391NamespaceDecl *Sema::getStdNamespace() const {
6392 return cast_or_null<NamespaceDecl>(
6393 StdNamespace.get(Context.getExternalSource()));
6394}
6395
Douglas Gregor66992202010-06-29 17:53:46 +00006396/// \brief Retrieve the special "std" namespace, which may require us to
6397/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006398NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006399 if (!StdNamespace) {
6400 // The "std" namespace has not yet been defined, so build one implicitly.
6401 StdNamespace = NamespaceDecl::Create(Context,
6402 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006403 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006404 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006405 &PP.getIdentifierTable().get("std"),
6406 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006407 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006408 }
6409
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006410 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006411}
6412
Sebastian Redl395e04d2012-01-17 22:49:33 +00006413bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006414 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006415 "Looking for std::initializer_list outside of C++.");
6416
6417 // We're looking for implicit instantiations of
6418 // template <typename E> class std::initializer_list.
6419
6420 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6421 return false;
6422
Sebastian Redl84760e32012-01-17 22:49:58 +00006423 ClassTemplateDecl *Template = 0;
6424 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006425
Sebastian Redl84760e32012-01-17 22:49:58 +00006426 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006427
Sebastian Redl84760e32012-01-17 22:49:58 +00006428 ClassTemplateSpecializationDecl *Specialization =
6429 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6430 if (!Specialization)
6431 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006432
Sebastian Redl84760e32012-01-17 22:49:58 +00006433 Template = Specialization->getSpecializedTemplate();
6434 Arguments = Specialization->getTemplateArgs().data();
6435 } else if (const TemplateSpecializationType *TST =
6436 Ty->getAs<TemplateSpecializationType>()) {
6437 Template = dyn_cast_or_null<ClassTemplateDecl>(
6438 TST->getTemplateName().getAsTemplateDecl());
6439 Arguments = TST->getArgs();
6440 }
6441 if (!Template)
6442 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006443
6444 if (!StdInitializerList) {
6445 // Haven't recognized std::initializer_list yet, maybe this is it.
6446 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6447 if (TemplateClass->getIdentifier() !=
6448 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006449 !getStdNamespace()->InEnclosingNamespaceSetOf(
6450 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006451 return false;
6452 // This is a template called std::initializer_list, but is it the right
6453 // template?
6454 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006455 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006456 return false;
6457 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6458 return false;
6459
6460 // It's the right template.
6461 StdInitializerList = Template;
6462 }
6463
6464 if (Template != StdInitializerList)
6465 return false;
6466
6467 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006468 if (Element)
6469 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006470 return true;
6471}
6472
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006473static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6474 NamespaceDecl *Std = S.getStdNamespace();
6475 if (!Std) {
6476 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6477 return 0;
6478 }
6479
6480 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6481 Loc, Sema::LookupOrdinaryName);
6482 if (!S.LookupQualifiedName(Result, Std)) {
6483 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6484 return 0;
6485 }
6486 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6487 if (!Template) {
6488 Result.suppressDiagnostics();
6489 // We found something weird. Complain about the first thing we found.
6490 NamedDecl *Found = *Result.begin();
6491 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6492 return 0;
6493 }
6494
6495 // We found some template called std::initializer_list. Now verify that it's
6496 // correct.
6497 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006498 if (Params->getMinRequiredArguments() != 1 ||
6499 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006500 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6501 return 0;
6502 }
6503
6504 return Template;
6505}
6506
6507QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6508 if (!StdInitializerList) {
6509 StdInitializerList = LookupStdInitializerList(*this, Loc);
6510 if (!StdInitializerList)
6511 return QualType();
6512 }
6513
6514 TemplateArgumentListInfo Args(Loc, Loc);
6515 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6516 Context.getTrivialTypeSourceInfo(Element,
6517 Loc)));
6518 return Context.getCanonicalType(
6519 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6520}
6521
Sebastian Redl98d36062012-01-17 22:50:14 +00006522bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6523 // C++ [dcl.init.list]p2:
6524 // A constructor is an initializer-list constructor if its first parameter
6525 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6526 // std::initializer_list<E> for some type E, and either there are no other
6527 // parameters or else all other parameters have default arguments.
6528 if (Ctor->getNumParams() < 1 ||
6529 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6530 return false;
6531
6532 QualType ArgType = Ctor->getParamDecl(0)->getType();
6533 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6534 ArgType = RT->getPointeeType().getUnqualifiedType();
6535
6536 return isStdInitializerList(ArgType, 0);
6537}
6538
Douglas Gregor9172aa62011-03-26 22:25:30 +00006539/// \brief Determine whether a using statement is in a context where it will be
6540/// apply in all contexts.
6541static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6542 switch (CurContext->getDeclKind()) {
6543 case Decl::TranslationUnit:
6544 return true;
6545 case Decl::LinkageSpec:
6546 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6547 default:
6548 return false;
6549 }
6550}
6551
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006552namespace {
6553
6554// Callback to only accept typo corrections that are namespaces.
6555class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6556 public:
6557 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6558 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6559 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6560 }
6561 return false;
6562 }
6563};
6564
6565}
6566
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006567static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6568 CXXScopeSpec &SS,
6569 SourceLocation IdentLoc,
6570 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006571 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006572 R.clear();
6573 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006574 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006575 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006576 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6577 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006578 if (DeclContext *DC = S.computeDeclContext(SS, false))
6579 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6580 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006581 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6582 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006583 else
6584 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6585 << Ident << CorrectedQuotedStr
6586 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006587
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006588 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6589 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006590
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006591 R.addDecl(Corrected.getCorrectionDecl());
6592 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006593 }
6594 return false;
6595}
6596
John McCalld226f652010-08-21 09:40:31 +00006597Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006598 SourceLocation UsingLoc,
6599 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006600 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006601 SourceLocation IdentLoc,
6602 IdentifierInfo *NamespcName,
6603 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006604 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6605 assert(NamespcName && "Invalid NamespcName.");
6606 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006607
6608 // This can only happen along a recovery path.
6609 while (S->getFlags() & Scope::TemplateParamScope)
6610 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006611 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006612
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006613 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006614 NestedNameSpecifier *Qualifier = 0;
6615 if (SS.isSet())
6616 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6617
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006618 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006619 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6620 LookupParsedName(R, S, &SS);
6621 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006622 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006623
Douglas Gregor66992202010-06-29 17:53:46 +00006624 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006625 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006626 // Allow "using namespace std;" or "using namespace ::std;" even if
6627 // "std" hasn't been defined yet, for GCC compatibility.
6628 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6629 NamespcName->isStr("std")) {
6630 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006631 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006632 R.resolveKind();
6633 }
6634 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006635 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006636 }
6637
John McCallf36e02d2009-10-09 21:13:30 +00006638 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006639 NamedDecl *Named = R.getFoundDecl();
6640 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6641 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006642 // C++ [namespace.udir]p1:
6643 // A using-directive specifies that the names in the nominated
6644 // namespace can be used in the scope in which the
6645 // using-directive appears after the using-directive. During
6646 // unqualified name lookup (3.4.1), the names appear as if they
6647 // were declared in the nearest enclosing namespace which
6648 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006649 // namespace. [Note: in this context, "contains" means "contains
6650 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006651
6652 // Find enclosing context containing both using-directive and
6653 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006654 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006655 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6656 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6657 CommonAncestor = CommonAncestor->getParent();
6658
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006659 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006660 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006661 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006662
Douglas Gregor9172aa62011-03-26 22:25:30 +00006663 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006664 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006665 Diag(IdentLoc, diag::warn_using_directive_in_header);
6666 }
6667
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006668 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006669 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006670 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006671 }
6672
Richard Smith6b3d3e52013-02-20 19:22:51 +00006673 if (UDir)
6674 ProcessDeclAttributeList(S, UDir, AttrList);
6675
John McCalld226f652010-08-21 09:40:31 +00006676 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006677}
6678
6679void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006680 // If the scope has an associated entity and the using directive is at
6681 // namespace or translation unit scope, add the UsingDirectiveDecl into
6682 // its lookup structure so qualified name lookup can find it.
6683 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6684 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006685 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006686 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006687 // Otherwise, it is at block sope. The using-directives will affect lookup
6688 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006689 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006690}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006691
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006692
John McCalld226f652010-08-21 09:40:31 +00006693Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006694 AccessSpecifier AS,
6695 bool HasUsingKeyword,
6696 SourceLocation UsingLoc,
6697 CXXScopeSpec &SS,
6698 UnqualifiedId &Name,
6699 AttributeList *AttrList,
6700 bool IsTypeName,
6701 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006702 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006703
Douglas Gregor12c118a2009-11-04 16:30:06 +00006704 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006705 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006706 case UnqualifiedId::IK_Identifier:
6707 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006708 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006709 case UnqualifiedId::IK_ConversionFunctionId:
6710 break;
6711
6712 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006713 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006714 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006715 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006716 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006717 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006718 diag::err_using_decl_constructor)
6719 << SS.getRange();
6720
Richard Smith80ad52f2013-01-02 11:42:31 +00006721 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006722
John McCalld226f652010-08-21 09:40:31 +00006723 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006724
6725 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006726 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006727 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006728 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006729
6730 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006731 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006732 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006733 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006734 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006735
6736 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6737 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006738 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006739 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006740
Richard Smith07b0fdc2013-03-18 21:12:30 +00006741 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006742 // TODO: store that the declaration was written without 'using' and
6743 // talk about access decls instead of using decls in the
6744 // diagnostics.
6745 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006746 UsingLoc = Name.getLocStart();
Richard Smith1b2209f2013-06-13 02:12:17 +00006747
6748 Diag(UsingLoc,
6749 getLangOpts().CPlusPlus11 ? diag::err_access_decl
6750 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006751 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006752 }
6753
Douglas Gregor56c04582010-12-16 00:46:58 +00006754 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6755 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6756 return 0;
6757
John McCall9488ea12009-11-17 05:59:44 +00006758 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006759 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006760 /* IsInstantiation */ false,
6761 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006762 if (UD)
6763 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006764
John McCalld226f652010-08-21 09:40:31 +00006765 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006766}
6767
Douglas Gregor09acc982010-07-07 23:08:52 +00006768/// \brief Determine whether a using declaration considers the given
6769/// declarations as "equivalent", e.g., if they are redeclarations of
6770/// the same entity or are both typedefs of the same type.
6771static bool
6772IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6773 bool &SuppressRedeclaration) {
6774 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6775 SuppressRedeclaration = false;
6776 return true;
6777 }
6778
Richard Smith162e1c12011-04-15 14:24:37 +00006779 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6780 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006781 SuppressRedeclaration = true;
6782 return Context.hasSameType(TD1->getUnderlyingType(),
6783 TD2->getUnderlyingType());
6784 }
6785
6786 return false;
6787}
6788
6789
John McCall9f54ad42009-12-10 09:41:52 +00006790/// Determines whether to create a using shadow decl for a particular
6791/// decl, given the set of decls existing prior to this using lookup.
6792bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6793 const LookupResult &Previous) {
6794 // Diagnose finding a decl which is not from a base class of the
6795 // current class. We do this now because there are cases where this
6796 // function will silently decide not to build a shadow decl, which
6797 // will pre-empt further diagnostics.
6798 //
6799 // We don't need to do this in C++0x because we do the check once on
6800 // the qualifier.
6801 //
6802 // FIXME: diagnose the following if we care enough:
6803 // struct A { int foo; };
6804 // struct B : A { using A::foo; };
6805 // template <class T> struct C : A {};
6806 // template <class T> struct D : C<T> { using B::foo; } // <---
6807 // This is invalid (during instantiation) in C++03 because B::foo
6808 // resolves to the using decl in B, which is not a base class of D<T>.
6809 // We can't diagnose it immediately because C<T> is an unknown
6810 // specialization. The UsingShadowDecl in D<T> then points directly
6811 // to A::foo, which will look well-formed when we instantiate.
6812 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006813 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006814 DeclContext *OrigDC = Orig->getDeclContext();
6815
6816 // Handle enums and anonymous structs.
6817 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6818 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6819 while (OrigRec->isAnonymousStructOrUnion())
6820 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6821
6822 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6823 if (OrigDC == CurContext) {
6824 Diag(Using->getLocation(),
6825 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006826 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006827 Diag(Orig->getLocation(), diag::note_using_decl_target);
6828 return true;
6829 }
6830
Douglas Gregordc355712011-02-25 00:36:19 +00006831 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006832 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006833 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006834 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006835 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006836 Diag(Orig->getLocation(), diag::note_using_decl_target);
6837 return true;
6838 }
6839 }
6840
6841 if (Previous.empty()) return false;
6842
6843 NamedDecl *Target = Orig;
6844 if (isa<UsingShadowDecl>(Target))
6845 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6846
John McCalld7533ec2009-12-11 02:33:26 +00006847 // If the target happens to be one of the previous declarations, we
6848 // don't have a conflict.
6849 //
6850 // FIXME: but we might be increasing its access, in which case we
6851 // should redeclare it.
6852 NamedDecl *NonTag = 0, *Tag = 0;
6853 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6854 I != E; ++I) {
6855 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006856 bool Result;
6857 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6858 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006859
6860 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6861 }
6862
John McCall9f54ad42009-12-10 09:41:52 +00006863 if (Target->isFunctionOrFunctionTemplate()) {
6864 FunctionDecl *FD;
6865 if (isa<FunctionTemplateDecl>(Target))
6866 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6867 else
6868 FD = cast<FunctionDecl>(Target);
6869
6870 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006871 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006872 case Ovl_Overload:
6873 return false;
6874
6875 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006876 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006877 break;
6878
6879 // We found a decl with the exact signature.
6880 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006881 // If we're in a record, we want to hide the target, so we
6882 // return true (without a diagnostic) to tell the caller not to
6883 // build a shadow decl.
6884 if (CurContext->isRecord())
6885 return true;
6886
6887 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006888 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006889 break;
6890 }
6891
6892 Diag(Target->getLocation(), diag::note_using_decl_target);
6893 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6894 return true;
6895 }
6896
6897 // Target is not a function.
6898
John McCall9f54ad42009-12-10 09:41:52 +00006899 if (isa<TagDecl>(Target)) {
6900 // No conflict between a tag and a non-tag.
6901 if (!Tag) return false;
6902
John McCall41ce66f2009-12-10 19:51:03 +00006903 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006904 Diag(Target->getLocation(), diag::note_using_decl_target);
6905 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6906 return true;
6907 }
6908
6909 // No conflict between a tag and a non-tag.
6910 if (!NonTag) return false;
6911
John McCall41ce66f2009-12-10 19:51:03 +00006912 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006913 Diag(Target->getLocation(), diag::note_using_decl_target);
6914 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6915 return true;
6916}
6917
John McCall9488ea12009-11-17 05:59:44 +00006918/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006919UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006920 UsingDecl *UD,
6921 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006922
6923 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006924 NamedDecl *Target = Orig;
6925 if (isa<UsingShadowDecl>(Target)) {
6926 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6927 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006928 }
6929
6930 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006931 = UsingShadowDecl::Create(Context, CurContext,
6932 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006933 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006934
6935 Shadow->setAccess(UD->getAccess());
6936 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6937 Shadow->setInvalidDecl();
6938
John McCall9488ea12009-11-17 05:59:44 +00006939 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006940 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006941 else
John McCall604e7f12009-12-08 07:46:18 +00006942 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006943
John McCall604e7f12009-12-08 07:46:18 +00006944
John McCall9f54ad42009-12-10 09:41:52 +00006945 return Shadow;
6946}
John McCall604e7f12009-12-08 07:46:18 +00006947
John McCall9f54ad42009-12-10 09:41:52 +00006948/// Hides a using shadow declaration. This is required by the current
6949/// using-decl implementation when a resolvable using declaration in a
6950/// class is followed by a declaration which would hide or override
6951/// one or more of the using decl's targets; for example:
6952///
6953/// struct Base { void foo(int); };
6954/// struct Derived : Base {
6955/// using Base::foo;
6956/// void foo(int);
6957/// };
6958///
6959/// The governing language is C++03 [namespace.udecl]p12:
6960///
6961/// When a using-declaration brings names from a base class into a
6962/// derived class scope, member functions in the derived class
6963/// override and/or hide member functions with the same name and
6964/// parameter types in a base class (rather than conflicting).
6965///
6966/// There are two ways to implement this:
6967/// (1) optimistically create shadow decls when they're not hidden
6968/// by existing declarations, or
6969/// (2) don't create any shadow decls (or at least don't make them
6970/// visible) until we've fully parsed/instantiated the class.
6971/// The problem with (1) is that we might have to retroactively remove
6972/// a shadow decl, which requires several O(n) operations because the
6973/// decl structures are (very reasonably) not designed for removal.
6974/// (2) avoids this but is very fiddly and phase-dependent.
6975void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006976 if (Shadow->getDeclName().getNameKind() ==
6977 DeclarationName::CXXConversionFunctionName)
6978 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6979
John McCall9f54ad42009-12-10 09:41:52 +00006980 // Remove it from the DeclContext...
6981 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006982
John McCall9f54ad42009-12-10 09:41:52 +00006983 // ...and the scope, if applicable...
6984 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006985 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006986 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006987 }
6988
John McCall9f54ad42009-12-10 09:41:52 +00006989 // ...and the using decl.
6990 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6991
6992 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006993 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006994}
6995
John McCall7ba107a2009-11-18 02:36:19 +00006996/// Builds a using declaration.
6997///
6998/// \param IsInstantiation - Whether this call arises from an
6999/// instantiation of an unresolved using declaration. We treat
7000/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007001NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7002 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007003 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007004 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007005 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007006 bool IsInstantiation,
7007 bool IsTypeName,
7008 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007009 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007010 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007011 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007012
Anders Carlsson550b14b2009-08-28 05:49:21 +00007013 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007014
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007015 if (SS.isEmpty()) {
7016 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007017 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007018 }
Mike Stump1eb44332009-09-09 15:08:12 +00007019
John McCall9f54ad42009-12-10 09:41:52 +00007020 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007021 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007022 ForRedeclaration);
7023 Previous.setHideTags(false);
7024 if (S) {
7025 LookupName(Previous, S);
7026
7027 // It is really dumb that we have to do this.
7028 LookupResult::Filter F = Previous.makeFilter();
7029 while (F.hasNext()) {
7030 NamedDecl *D = F.next();
7031 if (!isDeclInScope(D, CurContext, S))
7032 F.erase();
7033 }
7034 F.done();
7035 } else {
7036 assert(IsInstantiation && "no scope in non-instantiation");
7037 assert(CurContext->isRecord() && "scope not record in instantiation");
7038 LookupQualifiedName(Previous, CurContext);
7039 }
7040
John McCall9f54ad42009-12-10 09:41:52 +00007041 // Check for invalid redeclarations.
7042 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
7043 return 0;
7044
7045 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007046 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7047 return 0;
7048
John McCallaf8e6ed2009-11-12 03:15:40 +00007049 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007050 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007051 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007052 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00007053 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00007054 // FIXME: not all declaration name kinds are legal here
7055 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7056 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007057 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007058 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007059 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007060 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7061 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007062 }
John McCalled976492009-12-04 22:46:56 +00007063 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007064 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7065 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007066 }
John McCalled976492009-12-04 22:46:56 +00007067 D->setAccess(AS);
7068 CurContext->addDecl(D);
7069
7070 if (!LookupContext) return D;
7071 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007072
John McCall77bb1aa2010-05-01 00:40:08 +00007073 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007074 UD->setInvalidDecl();
7075 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007076 }
7077
Richard Smithc5a89a12012-04-02 01:30:27 +00007078 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007079 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007080 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007081 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007082 return UD;
7083 }
7084
7085 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007086
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007087 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007088
John McCall604e7f12009-12-08 07:46:18 +00007089 // Unlike most lookups, we don't always want to hide tag
7090 // declarations: tag names are visible through the using declaration
7091 // even if hidden by ordinary names, *except* in a dependent context
7092 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007093 if (!IsInstantiation)
7094 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007095
John McCallb9abd8722012-04-07 03:04:20 +00007096 // For the purposes of this lookup, we have a base object type
7097 // equal to that of the current context.
7098 if (CurContext->isRecord()) {
7099 R.setBaseObjectType(
7100 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7101 }
7102
John McCalla24dc2e2009-11-17 02:14:36 +00007103 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007104
John McCallf36e02d2009-10-09 21:13:30 +00007105 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00007106 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007107 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007108 UD->setInvalidDecl();
7109 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007110 }
7111
John McCalled976492009-12-04 22:46:56 +00007112 if (R.isAmbiguous()) {
7113 UD->setInvalidDecl();
7114 return UD;
7115 }
Mike Stump1eb44332009-09-09 15:08:12 +00007116
John McCall7ba107a2009-11-18 02:36:19 +00007117 if (IsTypeName) {
7118 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007119 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007120 Diag(IdentLoc, diag::err_using_typename_non_type);
7121 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7122 Diag((*I)->getUnderlyingDecl()->getLocation(),
7123 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007124 UD->setInvalidDecl();
7125 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007126 }
7127 } else {
7128 // If we asked for a non-typename and we got a type, error out,
7129 // but only if this is an instantiation of an unresolved using
7130 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007131 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007132 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7133 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007134 UD->setInvalidDecl();
7135 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007136 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007137 }
7138
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007139 // C++0x N2914 [namespace.udecl]p6:
7140 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007141 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007142 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7143 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007144 UD->setInvalidDecl();
7145 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007146 }
Mike Stump1eb44332009-09-09 15:08:12 +00007147
John McCall9f54ad42009-12-10 09:41:52 +00007148 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7149 if (!CheckUsingShadowDecl(UD, *I, Previous))
7150 BuildUsingShadowDecl(S, UD, *I);
7151 }
John McCall9488ea12009-11-17 05:59:44 +00007152
7153 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007154}
7155
Sebastian Redlf677ea32011-02-05 19:23:19 +00007156/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007157bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7158 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007159
Douglas Gregordc355712011-02-25 00:36:19 +00007160 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007161 assert(SourceType &&
7162 "Using decl naming constructor doesn't have type in scope spec.");
7163 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7164
7165 // Check whether the named type is a direct base class.
7166 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7167 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7168 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7169 BaseIt != BaseE; ++BaseIt) {
7170 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7171 if (CanonicalSourceType == BaseType)
7172 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007173 if (BaseIt->getType()->isDependentType())
7174 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007175 }
7176
7177 if (BaseIt == BaseE) {
7178 // Did not find SourceType in the bases.
7179 Diag(UD->getUsingLocation(),
7180 diag::err_using_decl_constructor_not_in_direct_base)
7181 << UD->getNameInfo().getSourceRange()
7182 << QualType(SourceType, 0) << TargetClass;
7183 return true;
7184 }
7185
Richard Smithc5a89a12012-04-02 01:30:27 +00007186 if (!CurContext->isDependentContext())
7187 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007188
7189 return false;
7190}
7191
John McCall9f54ad42009-12-10 09:41:52 +00007192/// Checks that the given using declaration is not an invalid
7193/// redeclaration. Note that this is checking only for the using decl
7194/// itself, not for any ill-formedness among the UsingShadowDecls.
7195bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7196 bool isTypeName,
7197 const CXXScopeSpec &SS,
7198 SourceLocation NameLoc,
7199 const LookupResult &Prev) {
7200 // C++03 [namespace.udecl]p8:
7201 // C++0x [namespace.udecl]p10:
7202 // A using-declaration is a declaration and can therefore be used
7203 // repeatedly where (and only where) multiple declarations are
7204 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007205 //
John McCall8a726212010-11-29 18:01:58 +00007206 // That's in non-member contexts.
7207 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007208 return false;
7209
7210 NestedNameSpecifier *Qual
7211 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7212
7213 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7214 NamedDecl *D = *I;
7215
7216 bool DTypename;
7217 NestedNameSpecifier *DQual;
7218 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7219 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007220 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007221 } else if (UnresolvedUsingValueDecl *UD
7222 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7223 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007224 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007225 } else if (UnresolvedUsingTypenameDecl *UD
7226 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7227 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007228 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007229 } else continue;
7230
7231 // using decls differ if one says 'typename' and the other doesn't.
7232 // FIXME: non-dependent using decls?
7233 if (isTypeName != DTypename) continue;
7234
7235 // using decls differ if they name different scopes (but note that
7236 // template instantiation can cause this check to trigger when it
7237 // didn't before instantiation).
7238 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7239 Context.getCanonicalNestedNameSpecifier(DQual))
7240 continue;
7241
7242 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007243 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007244 return true;
7245 }
7246
7247 return false;
7248}
7249
John McCall604e7f12009-12-08 07:46:18 +00007250
John McCalled976492009-12-04 22:46:56 +00007251/// Checks that the given nested-name qualifier used in a using decl
7252/// in the current context is appropriately related to the current
7253/// scope. If an error is found, diagnoses it and returns true.
7254bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7255 const CXXScopeSpec &SS,
7256 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007257 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007258
John McCall604e7f12009-12-08 07:46:18 +00007259 if (!CurContext->isRecord()) {
7260 // C++03 [namespace.udecl]p3:
7261 // C++0x [namespace.udecl]p8:
7262 // A using-declaration for a class member shall be a member-declaration.
7263
7264 // If we weren't able to compute a valid scope, it must be a
7265 // dependent class scope.
7266 if (!NamedContext || NamedContext->isRecord()) {
7267 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7268 << SS.getRange();
7269 return true;
7270 }
7271
7272 // Otherwise, everything is known to be fine.
7273 return false;
7274 }
7275
7276 // The current scope is a record.
7277
7278 // If the named context is dependent, we can't decide much.
7279 if (!NamedContext) {
7280 // FIXME: in C++0x, we can diagnose if we can prove that the
7281 // nested-name-specifier does not refer to a base class, which is
7282 // still possible in some cases.
7283
7284 // Otherwise we have to conservatively report that things might be
7285 // okay.
7286 return false;
7287 }
7288
7289 if (!NamedContext->isRecord()) {
7290 // Ideally this would point at the last name in the specifier,
7291 // but we don't have that level of source info.
7292 Diag(SS.getRange().getBegin(),
7293 diag::err_using_decl_nested_name_specifier_is_not_class)
7294 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7295 return true;
7296 }
7297
Douglas Gregor6fb07292010-12-21 07:41:49 +00007298 if (!NamedContext->isDependentContext() &&
7299 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7300 return true;
7301
Richard Smith80ad52f2013-01-02 11:42:31 +00007302 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007303 // C++0x [namespace.udecl]p3:
7304 // In a using-declaration used as a member-declaration, the
7305 // nested-name-specifier shall name a base class of the class
7306 // being defined.
7307
7308 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7309 cast<CXXRecordDecl>(NamedContext))) {
7310 if (CurContext == NamedContext) {
7311 Diag(NameLoc,
7312 diag::err_using_decl_nested_name_specifier_is_current_class)
7313 << SS.getRange();
7314 return true;
7315 }
7316
7317 Diag(SS.getRange().getBegin(),
7318 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7319 << (NestedNameSpecifier*) SS.getScopeRep()
7320 << cast<CXXRecordDecl>(CurContext)
7321 << SS.getRange();
7322 return true;
7323 }
7324
7325 return false;
7326 }
7327
7328 // C++03 [namespace.udecl]p4:
7329 // A using-declaration used as a member-declaration shall refer
7330 // to a member of a base class of the class being defined [etc.].
7331
7332 // Salient point: SS doesn't have to name a base class as long as
7333 // lookup only finds members from base classes. Therefore we can
7334 // diagnose here only if we can prove that that can't happen,
7335 // i.e. if the class hierarchies provably don't intersect.
7336
7337 // TODO: it would be nice if "definitely valid" results were cached
7338 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7339 // need to be repeated.
7340
7341 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007342 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007343
7344 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7345 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7346 Data->Bases.insert(Base);
7347 return true;
7348 }
7349
7350 bool hasDependentBases(const CXXRecordDecl *Class) {
7351 return !Class->forallBases(collect, this);
7352 }
7353
7354 /// Returns true if the base is dependent or is one of the
7355 /// accumulated base classes.
7356 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7357 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7358 return !Data->Bases.count(Base);
7359 }
7360
7361 bool mightShareBases(const CXXRecordDecl *Class) {
7362 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7363 }
7364 };
7365
7366 UserData Data;
7367
7368 // Returns false if we find a dependent base.
7369 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7370 return false;
7371
7372 // Returns false if the class has a dependent base or if it or one
7373 // of its bases is present in the base set of the current context.
7374 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7375 return false;
7376
7377 Diag(SS.getRange().getBegin(),
7378 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7379 << (NestedNameSpecifier*) SS.getScopeRep()
7380 << cast<CXXRecordDecl>(CurContext)
7381 << SS.getRange();
7382
7383 return true;
John McCalled976492009-12-04 22:46:56 +00007384}
7385
Richard Smith162e1c12011-04-15 14:24:37 +00007386Decl *Sema::ActOnAliasDeclaration(Scope *S,
7387 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007388 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007389 SourceLocation UsingLoc,
7390 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007391 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007392 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007393 // Skip up to the relevant declaration scope.
7394 while (S->getFlags() & Scope::TemplateParamScope)
7395 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007396 assert((S->getFlags() & Scope::DeclScope) &&
7397 "got alias-declaration outside of declaration scope");
7398
7399 if (Type.isInvalid())
7400 return 0;
7401
7402 bool Invalid = false;
7403 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7404 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007405 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007406
7407 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7408 return 0;
7409
7410 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007411 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007412 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007413 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7414 TInfo->getTypeLoc().getBeginLoc());
7415 }
Richard Smith162e1c12011-04-15 14:24:37 +00007416
7417 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7418 LookupName(Previous, S);
7419
7420 // Warn about shadowing the name of a template parameter.
7421 if (Previous.isSingleResult() &&
7422 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007423 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007424 Previous.clear();
7425 }
7426
7427 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7428 "name in alias declaration must be an identifier");
7429 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7430 Name.StartLocation,
7431 Name.Identifier, TInfo);
7432
7433 NewTD->setAccess(AS);
7434
7435 if (Invalid)
7436 NewTD->setInvalidDecl();
7437
Richard Smith6b3d3e52013-02-20 19:22:51 +00007438 ProcessDeclAttributeList(S, NewTD, AttrList);
7439
Richard Smith3e4c6c42011-05-05 21:57:07 +00007440 CheckTypedefForVariablyModifiedType(S, NewTD);
7441 Invalid |= NewTD->isInvalidDecl();
7442
Richard Smith162e1c12011-04-15 14:24:37 +00007443 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007444
7445 NamedDecl *NewND;
7446 if (TemplateParamLists.size()) {
7447 TypeAliasTemplateDecl *OldDecl = 0;
7448 TemplateParameterList *OldTemplateParams = 0;
7449
7450 if (TemplateParamLists.size() != 1) {
7451 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007452 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7453 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007454 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007455 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007456
7457 // Only consider previous declarations in the same scope.
7458 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7459 /*ExplicitInstantiationOrSpecialization*/false);
7460 if (!Previous.empty()) {
7461 Redeclaration = true;
7462
7463 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7464 if (!OldDecl && !Invalid) {
7465 Diag(UsingLoc, diag::err_redefinition_different_kind)
7466 << Name.Identifier;
7467
7468 NamedDecl *OldD = Previous.getRepresentativeDecl();
7469 if (OldD->getLocation().isValid())
7470 Diag(OldD->getLocation(), diag::note_previous_definition);
7471
7472 Invalid = true;
7473 }
7474
7475 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7476 if (TemplateParameterListsAreEqual(TemplateParams,
7477 OldDecl->getTemplateParameters(),
7478 /*Complain=*/true,
7479 TPL_TemplateMatch))
7480 OldTemplateParams = OldDecl->getTemplateParameters();
7481 else
7482 Invalid = true;
7483
7484 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7485 if (!Invalid &&
7486 !Context.hasSameType(OldTD->getUnderlyingType(),
7487 NewTD->getUnderlyingType())) {
7488 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7489 // but we can't reasonably accept it.
7490 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7491 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7492 if (OldTD->getLocation().isValid())
7493 Diag(OldTD->getLocation(), diag::note_previous_definition);
7494 Invalid = true;
7495 }
7496 }
7497 }
7498
7499 // Merge any previous default template arguments into our parameters,
7500 // and check the parameter list.
7501 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7502 TPC_TypeAliasTemplate))
7503 return 0;
7504
7505 TypeAliasTemplateDecl *NewDecl =
7506 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7507 Name.Identifier, TemplateParams,
7508 NewTD);
7509
7510 NewDecl->setAccess(AS);
7511
7512 if (Invalid)
7513 NewDecl->setInvalidDecl();
7514 else if (OldDecl)
7515 NewDecl->setPreviousDeclaration(OldDecl);
7516
7517 NewND = NewDecl;
7518 } else {
7519 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7520 NewND = NewTD;
7521 }
Richard Smith162e1c12011-04-15 14:24:37 +00007522
7523 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007524 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007525
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007526 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007527 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007528}
7529
John McCalld226f652010-08-21 09:40:31 +00007530Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007531 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007532 SourceLocation AliasLoc,
7533 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007534 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007535 SourceLocation IdentLoc,
7536 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007537
Anders Carlsson81c85c42009-03-28 23:53:49 +00007538 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007539 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7540 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007541
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007542 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007543 NamedDecl *PrevDecl
7544 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7545 ForRedeclaration);
7546 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7547 PrevDecl = 0;
7548
7549 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007550 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007551 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007552 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007553 // FIXME: At some point, we'll want to create the (redundant)
7554 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007555 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007556 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007557 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007558 }
Mike Stump1eb44332009-09-09 15:08:12 +00007559
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007560 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7561 diag::err_redefinition_different_kind;
7562 Diag(AliasLoc, DiagID) << Alias;
7563 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007564 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007565 }
7566
John McCalla24dc2e2009-11-17 02:14:36 +00007567 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007568 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007569
John McCallf36e02d2009-10-09 21:13:30 +00007570 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007571 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007572 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007573 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007574 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007575 }
Mike Stump1eb44332009-09-09 15:08:12 +00007576
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007577 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007578 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007579 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007580 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007581
John McCall3dbd3d52010-02-16 06:53:13 +00007582 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007583 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007584}
7585
Sean Hunt001cad92011-05-10 00:49:42 +00007586Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007587Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7588 CXXMethodDecl *MD) {
7589 CXXRecordDecl *ClassDecl = MD->getParent();
7590
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007591 // C++ [except.spec]p14:
7592 // An implicitly declared special member function (Clause 12) shall have an
7593 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007594 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007595 if (ClassDecl->isInvalidDecl())
7596 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007597
Sebastian Redl60618fa2011-03-12 11:50:43 +00007598 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007599 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7600 BEnd = ClassDecl->bases_end();
7601 B != BEnd; ++B) {
7602 if (B->isVirtual()) // Handled below.
7603 continue;
7604
Douglas Gregor18274032010-07-03 00:47:00 +00007605 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7606 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007607 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7608 // If this is a deleted function, add it anyway. This might be conformant
7609 // with the standard. This might not. I'm not sure. It might not matter.
7610 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007611 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007612 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007613 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007614
7615 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007616 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7617 BEnd = ClassDecl->vbases_end();
7618 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007619 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7620 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007621 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7622 // If this is a deleted function, add it anyway. This might be conformant
7623 // with the standard. This might not. I'm not sure. It might not matter.
7624 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007625 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007626 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007627 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007628
7629 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007630 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7631 FEnd = ClassDecl->field_end();
7632 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007633 if (F->hasInClassInitializer()) {
7634 if (Expr *E = F->getInClassInitializer())
7635 ExceptSpec.CalledExpr(E);
7636 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007637 // DR1351:
7638 // If the brace-or-equal-initializer of a non-static data member
7639 // invokes a defaulted default constructor of its class or of an
7640 // enclosing class in a potentially evaluated subexpression, the
7641 // program is ill-formed.
7642 //
7643 // This resolution is unworkable: the exception specification of the
7644 // default constructor can be needed in an unevaluated context, in
7645 // particular, in the operand of a noexcept-expression, and we can be
7646 // unable to compute an exception specification for an enclosed class.
7647 //
7648 // We do not allow an in-class initializer to require the evaluation
7649 // of the exception specification for any in-class initializer whose
7650 // definition is not lexically complete.
7651 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007652 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007653 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007654 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7655 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7656 // If this is a deleted function, add it anyway. This might be conformant
7657 // with the standard. This might not. I'm not sure. It might not matter.
7658 // In particular, the problem is that this function never gets called. It
7659 // might just be ill-formed because this function attempts to refer to
7660 // a deleted function here.
7661 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007662 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007663 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007664 }
John McCalle23cf432010-12-14 08:05:40 +00007665
Sean Hunt001cad92011-05-10 00:49:42 +00007666 return ExceptSpec;
7667}
7668
Richard Smith07b0fdc2013-03-18 21:12:30 +00007669Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007670Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7671 CXXRecordDecl *ClassDecl = CD->getParent();
7672
7673 // C++ [except.spec]p14:
7674 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007675 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007676 if (ClassDecl->isInvalidDecl())
7677 return ExceptSpec;
7678
7679 // Inherited constructor.
7680 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7681 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7682 // FIXME: Copying or moving the parameters could add extra exceptions to the
7683 // set, as could the default arguments for the inherited constructor. This
7684 // will be addressed when we implement the resolution of core issue 1351.
7685 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7686
7687 // Direct base-class constructors.
7688 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7689 BEnd = ClassDecl->bases_end();
7690 B != BEnd; ++B) {
7691 if (B->isVirtual()) // Handled below.
7692 continue;
7693
7694 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7695 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7696 if (BaseClassDecl == InheritedDecl)
7697 continue;
7698 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7699 if (Constructor)
7700 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7701 }
7702 }
7703
7704 // Virtual base-class constructors.
7705 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7706 BEnd = ClassDecl->vbases_end();
7707 B != BEnd; ++B) {
7708 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7709 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7710 if (BaseClassDecl == InheritedDecl)
7711 continue;
7712 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7713 if (Constructor)
7714 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7715 }
7716 }
7717
7718 // Field constructors.
7719 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7720 FEnd = ClassDecl->field_end();
7721 F != FEnd; ++F) {
7722 if (F->hasInClassInitializer()) {
7723 if (Expr *E = F->getInClassInitializer())
7724 ExceptSpec.CalledExpr(E);
7725 else if (!F->isInvalidDecl())
7726 Diag(CD->getLocation(),
7727 diag::err_in_class_initializer_references_def_ctor) << CD;
7728 } else if (const RecordType *RecordTy
7729 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7730 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7731 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7732 if (Constructor)
7733 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7734 }
7735 }
7736
Richard Smith07b0fdc2013-03-18 21:12:30 +00007737 return ExceptSpec;
7738}
7739
Richard Smithafb49182012-11-29 01:34:07 +00007740namespace {
7741/// RAII object to register a special member as being currently declared.
7742struct DeclaringSpecialMember {
7743 Sema &S;
7744 Sema::SpecialMemberDecl D;
7745 bool WasAlreadyBeingDeclared;
7746
7747 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7748 : S(S), D(RD, CSM) {
7749 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7750 if (WasAlreadyBeingDeclared)
7751 // This almost never happens, but if it does, ensure that our cache
7752 // doesn't contain a stale result.
7753 S.SpecialMemberCache.clear();
7754
7755 // FIXME: Register a note to be produced if we encounter an error while
7756 // declaring the special member.
7757 }
7758 ~DeclaringSpecialMember() {
7759 if (!WasAlreadyBeingDeclared)
7760 S.SpecialMembersBeingDeclared.erase(D);
7761 }
7762
7763 /// \brief Are we already trying to declare this special member?
7764 bool isAlreadyBeingDeclared() const {
7765 return WasAlreadyBeingDeclared;
7766 }
7767};
7768}
7769
Sean Hunt001cad92011-05-10 00:49:42 +00007770CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7771 CXXRecordDecl *ClassDecl) {
7772 // C++ [class.ctor]p5:
7773 // A default constructor for a class X is a constructor of class X
7774 // that can be called without an argument. If there is no
7775 // user-declared constructor for class X, a default constructor is
7776 // implicitly declared. An implicitly-declared default constructor
7777 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007778 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007779 "Should not build implicit default constructor!");
7780
Richard Smithafb49182012-11-29 01:34:07 +00007781 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7782 if (DSM.isAlreadyBeingDeclared())
7783 return 0;
7784
Richard Smith7756afa2012-06-10 05:43:50 +00007785 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7786 CXXDefaultConstructor,
7787 false);
7788
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007789 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007790 CanQualType ClassType
7791 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007792 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007793 DeclarationName Name
7794 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007795 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007796 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007797 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007798 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007799 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007800 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007801 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007802 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007803
7804 // Build an exception specification pointing back at this constructor.
7805 FunctionProtoType::ExtProtoInfo EPI;
7806 EPI.ExceptionSpecType = EST_Unevaluated;
7807 EPI.ExceptionSpecDecl = DefaultCon;
Dmitri Gribenko55431692013-05-05 00:41:58 +00007808 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007809
Richard Smithbc2a35d2012-12-08 08:32:28 +00007810 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7811 // constructors is easy to compute.
7812 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7813
7814 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007815 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007816
Douglas Gregor18274032010-07-03 00:47:00 +00007817 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007818 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007819
Douglas Gregor23c94db2010-07-02 17:43:08 +00007820 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007821 PushOnScopeChains(DefaultCon, S, false);
7822 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007823
Douglas Gregor32df23e2010-07-01 22:02:46 +00007824 return DefaultCon;
7825}
7826
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007827void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7828 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007829 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007830 !Constructor->doesThisDeclarationHaveABody() &&
7831 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007832 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007833
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007834 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007835 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007836
Eli Friedman9a14db32012-10-18 20:14:08 +00007837 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007838 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007839 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007840 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007841 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007842 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007843 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007844 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007845 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007846
7847 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007848 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007849
7850 Constructor->setUsed();
7851 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007852
7853 if (ASTMutationListener *L = getASTMutationListener()) {
7854 L->CompletedImplicitDefinition(Constructor);
7855 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007856}
7857
Richard Smith7a614d82011-06-11 17:19:42 +00007858void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007859 // Check that any explicitly-defaulted methods have exception specifications
7860 // compatible with their implicit exception specifications.
7861 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007862}
7863
Richard Smith4841ca52013-04-10 05:48:59 +00007864namespace {
7865/// Information on inheriting constructors to declare.
7866class InheritingConstructorInfo {
7867public:
7868 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7869 : SemaRef(SemaRef), Derived(Derived) {
7870 // Mark the constructors that we already have in the derived class.
7871 //
7872 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7873 // unless there is a user-declared constructor with the same signature in
7874 // the class where the using-declaration appears.
7875 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7876 }
7877
7878 void inheritAll(CXXRecordDecl *RD) {
7879 visitAll(RD, &InheritingConstructorInfo::inherit);
7880 }
7881
7882private:
7883 /// Information about an inheriting constructor.
7884 struct InheritingConstructor {
7885 InheritingConstructor()
7886 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7887
7888 /// If \c true, a constructor with this signature is already declared
7889 /// in the derived class.
7890 bool DeclaredInDerived;
7891
7892 /// The constructor which is inherited.
7893 const CXXConstructorDecl *BaseCtor;
7894
7895 /// The derived constructor we declared.
7896 CXXConstructorDecl *DerivedCtor;
7897 };
7898
7899 /// Inheriting constructors with a given canonical type. There can be at
7900 /// most one such non-template constructor, and any number of templated
7901 /// constructors.
7902 struct InheritingConstructorsForType {
7903 InheritingConstructor NonTemplate;
7904 llvm::SmallVector<
7905 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7906
7907 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7908 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7909 TemplateParameterList *ParamList = FTD->getTemplateParameters();
7910 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7911 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7912 false, S.TPL_TemplateMatch))
7913 return Templates[I].second;
7914 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7915 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007916 }
Richard Smith4841ca52013-04-10 05:48:59 +00007917
7918 return NonTemplate;
7919 }
7920 };
7921
7922 /// Get or create the inheriting constructor record for a constructor.
7923 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7924 QualType CtorType) {
7925 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7926 .getEntry(SemaRef, Ctor);
7927 }
7928
7929 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7930
7931 /// Process all constructors for a class.
7932 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7933 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7934 CtorE = RD->ctor_end();
7935 CtorIt != CtorE; ++CtorIt)
7936 (this->*Callback)(*CtorIt);
7937 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7938 I(RD->decls_begin()), E(RD->decls_end());
7939 I != E; ++I) {
7940 const FunctionDecl *FD = (*I)->getTemplatedDecl();
7941 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7942 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007943 }
7944 }
Richard Smith4841ca52013-04-10 05:48:59 +00007945
7946 /// Note that a constructor (or constructor template) was declared in Derived.
7947 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7948 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7949 }
7950
7951 /// Inherit a single constructor.
7952 void inherit(const CXXConstructorDecl *Ctor) {
7953 const FunctionProtoType *CtorType =
7954 Ctor->getType()->castAs<FunctionProtoType>();
7955 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7956 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7957
7958 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7959
7960 // Core issue (no number yet): the ellipsis is always discarded.
7961 if (EPI.Variadic) {
7962 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7963 SemaRef.Diag(Ctor->getLocation(),
7964 diag::note_using_decl_constructor_ellipsis);
7965 EPI.Variadic = false;
7966 }
7967
7968 // Declare a constructor for each number of parameters.
7969 //
7970 // C++11 [class.inhctor]p1:
7971 // The candidate set of inherited constructors from the class X named in
7972 // the using-declaration consists of [... modulo defects ...] for each
7973 // constructor or constructor template of X, the set of constructors or
7974 // constructor templates that results from omitting any ellipsis parameter
7975 // specification and successively omitting parameters with a default
7976 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00007977 unsigned MinParams = minParamsToInherit(Ctor);
7978 unsigned Params = Ctor->getNumParams();
7979 if (Params >= MinParams) {
7980 do
7981 declareCtor(UsingLoc, Ctor,
7982 SemaRef.Context.getFunctionType(
7983 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7984 while (Params > MinParams &&
7985 Ctor->getParamDecl(--Params)->hasDefaultArg());
7986 }
Richard Smith4841ca52013-04-10 05:48:59 +00007987 }
7988
7989 /// Find the using-declaration which specified that we should inherit the
7990 /// constructors of \p Base.
7991 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
7992 // No fancy lookup required; just look for the base constructor name
7993 // directly within the derived class.
7994 ASTContext &Context = SemaRef.Context;
7995 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
7996 Context.getCanonicalType(Context.getRecordType(Base)));
7997 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
7998 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
7999 }
8000
8001 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8002 // C++11 [class.inhctor]p3:
8003 // [F]or each constructor template in the candidate set of inherited
8004 // constructors, a constructor template is implicitly declared
8005 if (Ctor->getDescribedFunctionTemplate())
8006 return 0;
8007
8008 // For each non-template constructor in the candidate set of inherited
8009 // constructors other than a constructor having no parameters or a
8010 // copy/move constructor having a single parameter, a constructor is
8011 // implicitly declared [...]
8012 if (Ctor->getNumParams() == 0)
8013 return 1;
8014 if (Ctor->isCopyOrMoveConstructor())
8015 return 2;
8016
8017 // Per discussion on core reflector, never inherit a constructor which
8018 // would become a default, copy, or move constructor of Derived either.
8019 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8020 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8021 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8022 }
8023
8024 /// Declare a single inheriting constructor, inheriting the specified
8025 /// constructor, with the given type.
8026 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8027 QualType DerivedType) {
8028 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8029
8030 // C++11 [class.inhctor]p3:
8031 // ... a constructor is implicitly declared with the same constructor
8032 // characteristics unless there is a user-declared constructor with
8033 // the same signature in the class where the using-declaration appears
8034 if (Entry.DeclaredInDerived)
8035 return;
8036
8037 // C++11 [class.inhctor]p7:
8038 // If two using-declarations declare inheriting constructors with the
8039 // same signature, the program is ill-formed
8040 if (Entry.DerivedCtor) {
8041 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8042 // Only diagnose this once per constructor.
8043 if (Entry.DerivedCtor->isInvalidDecl())
8044 return;
8045 Entry.DerivedCtor->setInvalidDecl();
8046
8047 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8048 SemaRef.Diag(BaseCtor->getLocation(),
8049 diag::note_using_decl_constructor_conflict_current_ctor);
8050 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8051 diag::note_using_decl_constructor_conflict_previous_ctor);
8052 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8053 diag::note_using_decl_constructor_conflict_previous_using);
8054 } else {
8055 // Core issue (no number): if the same inheriting constructor is
8056 // produced by multiple base class constructors from the same base
8057 // class, the inheriting constructor is defined as deleted.
8058 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8059 }
8060
8061 return;
8062 }
8063
8064 ASTContext &Context = SemaRef.Context;
8065 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8066 Context.getCanonicalType(Context.getRecordType(Derived)));
8067 DeclarationNameInfo NameInfo(Name, UsingLoc);
8068
8069 TemplateParameterList *TemplateParams = 0;
8070 if (const FunctionTemplateDecl *FTD =
8071 BaseCtor->getDescribedFunctionTemplate()) {
8072 TemplateParams = FTD->getTemplateParameters();
8073 // We're reusing template parameters from a different DeclContext. This
8074 // is questionable at best, but works out because the template depth in
8075 // both places is guaranteed to be 0.
8076 // FIXME: Rebuild the template parameters in the new context, and
8077 // transform the function type to refer to them.
8078 }
8079
8080 // Build type source info pointing at the using-declaration. This is
8081 // required by template instantiation.
8082 TypeSourceInfo *TInfo =
8083 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8084 FunctionProtoTypeLoc ProtoLoc =
8085 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8086
8087 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8088 Context, Derived, UsingLoc, NameInfo, DerivedType,
8089 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8090 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8091
8092 // Build an unevaluated exception specification for this constructor.
8093 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8094 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8095 EPI.ExceptionSpecType = EST_Unevaluated;
8096 EPI.ExceptionSpecDecl = DerivedCtor;
8097 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8098 FPT->getArgTypes(), EPI));
8099
8100 // Build the parameter declarations.
8101 SmallVector<ParmVarDecl *, 16> ParamDecls;
8102 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8103 TypeSourceInfo *TInfo =
8104 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8105 ParmVarDecl *PD = ParmVarDecl::Create(
8106 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8107 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8108 PD->setScopeInfo(0, I);
8109 PD->setImplicit();
8110 ParamDecls.push_back(PD);
8111 ProtoLoc.setArg(I, PD);
8112 }
8113
8114 // Set up the new constructor.
8115 DerivedCtor->setAccess(BaseCtor->getAccess());
8116 DerivedCtor->setParams(ParamDecls);
8117 DerivedCtor->setInheritedConstructor(BaseCtor);
8118 if (BaseCtor->isDeleted())
8119 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8120
8121 // If this is a constructor template, build the template declaration.
8122 if (TemplateParams) {
8123 FunctionTemplateDecl *DerivedTemplate =
8124 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8125 TemplateParams, DerivedCtor);
8126 DerivedTemplate->setAccess(BaseCtor->getAccess());
8127 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8128 Derived->addDecl(DerivedTemplate);
8129 } else {
8130 Derived->addDecl(DerivedCtor);
8131 }
8132
8133 Entry.BaseCtor = BaseCtor;
8134 Entry.DerivedCtor = DerivedCtor;
8135 }
8136
8137 Sema &SemaRef;
8138 CXXRecordDecl *Derived;
8139 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8140 MapType Map;
8141};
8142}
8143
8144void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8145 // Defer declaring the inheriting constructors until the class is
8146 // instantiated.
8147 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008148 return;
8149
Richard Smith4841ca52013-04-10 05:48:59 +00008150 // Find base classes from which we might inherit constructors.
8151 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8152 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8153 BaseE = ClassDecl->bases_end();
8154 BaseIt != BaseE; ++BaseIt)
8155 if (BaseIt->getInheritConstructors())
8156 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008157
Richard Smith4841ca52013-04-10 05:48:59 +00008158 // Go no further if we're not inheriting any constructors.
8159 if (InheritedBases.empty())
8160 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008161
Richard Smith4841ca52013-04-10 05:48:59 +00008162 // Declare the inherited constructors.
8163 InheritingConstructorInfo ICI(*this, ClassDecl);
8164 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8165 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008166}
8167
Richard Smith07b0fdc2013-03-18 21:12:30 +00008168void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8169 CXXConstructorDecl *Constructor) {
8170 CXXRecordDecl *ClassDecl = Constructor->getParent();
8171 assert(Constructor->getInheritedConstructor() &&
8172 !Constructor->doesThisDeclarationHaveABody() &&
8173 !Constructor->isDeleted());
8174
8175 SynthesizedFunctionScope Scope(*this, Constructor);
8176 DiagnosticErrorTrap Trap(Diags);
8177 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8178 Trap.hasErrorOccurred()) {
8179 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8180 << Context.getTagDeclType(ClassDecl);
8181 Constructor->setInvalidDecl();
8182 return;
8183 }
8184
8185 SourceLocation Loc = Constructor->getLocation();
8186 Constructor->setBody(new (Context) CompoundStmt(Loc));
8187
8188 Constructor->setUsed();
8189 MarkVTableUsed(CurrentLocation, ClassDecl);
8190
8191 if (ASTMutationListener *L = getASTMutationListener()) {
8192 L->CompletedImplicitDefinition(Constructor);
8193 }
8194}
8195
8196
Sean Huntcb45a0f2011-05-12 22:46:25 +00008197Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008198Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8199 CXXRecordDecl *ClassDecl = MD->getParent();
8200
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008201 // C++ [except.spec]p14:
8202 // An implicitly declared special member function (Clause 12) shall have
8203 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008204 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008205 if (ClassDecl->isInvalidDecl())
8206 return ExceptSpec;
8207
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008208 // Direct base-class destructors.
8209 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8210 BEnd = ClassDecl->bases_end();
8211 B != BEnd; ++B) {
8212 if (B->isVirtual()) // Handled below.
8213 continue;
8214
8215 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008216 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008217 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008218 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008219
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008220 // Virtual base-class destructors.
8221 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8222 BEnd = ClassDecl->vbases_end();
8223 B != BEnd; ++B) {
8224 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008225 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008226 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008227 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008228
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008229 // Field destructors.
8230 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8231 FEnd = ClassDecl->field_end();
8232 F != FEnd; ++F) {
8233 if (const RecordType *RecordTy
8234 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008235 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008236 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008237 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008238
Sean Huntcb45a0f2011-05-12 22:46:25 +00008239 return ExceptSpec;
8240}
8241
8242CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8243 // C++ [class.dtor]p2:
8244 // If a class has no user-declared destructor, a destructor is
8245 // declared implicitly. An implicitly-declared destructor is an
8246 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008247 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008248
Richard Smithafb49182012-11-29 01:34:07 +00008249 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8250 if (DSM.isAlreadyBeingDeclared())
8251 return 0;
8252
Douglas Gregor4923aa22010-07-02 20:37:36 +00008253 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008254 CanQualType ClassType
8255 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008256 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008257 DeclarationName Name
8258 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008259 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008260 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008261 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8262 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008263 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008264 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008265 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008266 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008267
8268 // Build an exception specification pointing back at this destructor.
8269 FunctionProtoType::ExtProtoInfo EPI;
8270 EPI.ExceptionSpecType = EST_Unevaluated;
8271 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008272 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008273
Richard Smithbc2a35d2012-12-08 08:32:28 +00008274 AddOverriddenMethods(ClassDecl, Destructor);
8275
8276 // We don't need to use SpecialMemberIsTrivial here; triviality for
8277 // destructors is easy to compute.
8278 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8279
8280 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008281 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008282
Douglas Gregor4923aa22010-07-02 20:37:36 +00008283 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008284 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008285
Douglas Gregor4923aa22010-07-02 20:37:36 +00008286 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008287 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008288 PushOnScopeChains(Destructor, S, false);
8289 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008290
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008291 return Destructor;
8292}
8293
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008294void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008295 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008296 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008297 !Destructor->doesThisDeclarationHaveABody() &&
8298 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008299 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008300 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008301 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008302
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008303 if (Destructor->isInvalidDecl())
8304 return;
8305
Eli Friedman9a14db32012-10-18 20:14:08 +00008306 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008307
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008308 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008309 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8310 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008311
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008312 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008313 Diag(CurrentLocation, diag::note_member_synthesized_at)
8314 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8315
8316 Destructor->setInvalidDecl();
8317 return;
8318 }
8319
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008320 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008321 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008322 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008323 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008324 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008325
8326 if (ASTMutationListener *L = getASTMutationListener()) {
8327 L->CompletedImplicitDefinition(Destructor);
8328 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008329}
8330
Richard Smitha4156b82012-04-21 18:42:51 +00008331/// \brief Perform any semantic analysis which needs to be delayed until all
8332/// pending class member declarations have been parsed.
8333void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008334 // If the context is an invalid C++ class, just suppress these checks.
8335 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8336 if (Record->isInvalidDecl()) {
8337 DelayedDestructorExceptionSpecChecks.clear();
8338 return;
8339 }
8340 }
8341
Richard Smitha4156b82012-04-21 18:42:51 +00008342 // Perform any deferred checking of exception specifications for virtual
8343 // destructors.
8344 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8345 i != e; ++i) {
8346 const CXXDestructorDecl *Dtor =
8347 DelayedDestructorExceptionSpecChecks[i].first;
8348 assert(!Dtor->getParent()->isDependentType() &&
8349 "Should not ever add destructors of templates into the list.");
8350 CheckOverridingFunctionExceptionSpec(Dtor,
8351 DelayedDestructorExceptionSpecChecks[i].second);
8352 }
8353 DelayedDestructorExceptionSpecChecks.clear();
8354}
8355
Richard Smithb9d0b762012-07-27 04:22:15 +00008356void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8357 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008358 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008359 "adjusting dtor exception specs was introduced in c++11");
8360
Sebastian Redl0ee33912011-05-19 05:13:44 +00008361 // C++11 [class.dtor]p3:
8362 // A declaration of a destructor that does not have an exception-
8363 // specification is implicitly considered to have the same exception-
8364 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008365 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008366 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008367 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008368 return;
8369
Chandler Carruth3f224b22011-09-20 04:55:26 +00008370 // Replace the destructor's type, building off the existing one. Fortunately,
8371 // the only thing of interest in the destructor type is its extended info.
8372 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008373 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8374 EPI.ExceptionSpecType = EST_Unevaluated;
8375 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008376 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008377
Sebastian Redl0ee33912011-05-19 05:13:44 +00008378 // FIXME: If the destructor has a body that could throw, and the newly created
8379 // spec doesn't allow exceptions, we should emit a warning, because this
8380 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008381 // However, we don't have a body or an exception specification yet, so it
8382 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008383}
8384
Richard Smith8c889532012-11-14 00:50:40 +00008385/// When generating a defaulted copy or move assignment operator, if a field
8386/// should be copied with __builtin_memcpy rather than via explicit assignments,
8387/// do so. This optimization only applies for arrays of scalars, and for arrays
8388/// of class type where the selected copy/move-assignment operator is trivial.
8389static StmtResult
8390buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8391 Expr *To, Expr *From) {
8392 // Compute the size of the memory buffer to be copied.
8393 QualType SizeType = S.Context.getSizeType();
8394 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8395 S.Context.getTypeSizeInChars(T).getQuantity());
8396
8397 // Take the address of the field references for "from" and "to". We
8398 // directly construct UnaryOperators here because semantic analysis
8399 // does not permit us to take the address of an xvalue.
8400 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8401 S.Context.getPointerType(From->getType()),
8402 VK_RValue, OK_Ordinary, Loc);
8403 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8404 S.Context.getPointerType(To->getType()),
8405 VK_RValue, OK_Ordinary, Loc);
8406
8407 const Type *E = T->getBaseElementTypeUnsafe();
8408 bool NeedsCollectableMemCpy =
8409 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8410
8411 // Create a reference to the __builtin_objc_memmove_collectable function
8412 StringRef MemCpyName = NeedsCollectableMemCpy ?
8413 "__builtin_objc_memmove_collectable" :
8414 "__builtin_memcpy";
8415 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8416 Sema::LookupOrdinaryName);
8417 S.LookupName(R, S.TUScope, true);
8418
8419 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8420 if (!MemCpy)
8421 // Something went horribly wrong earlier, and we will have complained
8422 // about it.
8423 return StmtError();
8424
8425 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8426 VK_RValue, Loc, 0);
8427 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8428
8429 Expr *CallArgs[] = {
8430 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8431 };
8432 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8433 Loc, CallArgs, Loc);
8434
8435 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8436 return S.Owned(Call.takeAs<Stmt>());
8437}
8438
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008439/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008440/// \c To.
8441///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008442/// This routine is used to copy/move the members of a class with an
8443/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008444/// copied are arrays, this routine builds for loops to copy them.
8445///
8446/// \param S The Sema object used for type-checking.
8447///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008448/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008449///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008450/// \param T The type of the expressions being copied/moved. Both expressions
8451/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008452///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008453/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008454///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008455/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008456///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008457/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008458/// Otherwise, it's a non-static member subobject.
8459///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008460/// \param Copying Whether we're copying or moving.
8461///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008462/// \param Depth Internal parameter recording the depth of the recursion.
8463///
Richard Smith8c889532012-11-14 00:50:40 +00008464/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8465/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008466static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008467buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8468 Expr *To, Expr *From,
8469 bool CopyingBaseSubobject, bool Copying,
8470 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008471 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008472 // Each subobject is assigned in the manner appropriate to its type:
8473 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008474 // - if the subobject is of class type, as if by a call to operator= with
8475 // the subobject as the object expression and the corresponding
8476 // subobject of x as a single function argument (as if by explicit
8477 // qualification; that is, ignoring any possible virtual overriding
8478 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008479 //
8480 // C++03 [class.copy]p13:
8481 // - if the subobject is of class type, the copy assignment operator for
8482 // the class is used (as if by explicit qualification; that is,
8483 // ignoring any possible virtual overriding functions in more derived
8484 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008485 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8486 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008487
Douglas Gregor06a9f362010-05-01 20:49:11 +00008488 // Look for operator=.
8489 DeclarationName Name
8490 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8491 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8492 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008493
Richard Smith044c8aa2012-11-13 00:54:12 +00008494 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8495 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008496 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008497 LookupResult::Filter F = OpLookup.makeFilter();
8498 while (F.hasNext()) {
8499 NamedDecl *D = F.next();
8500 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8501 if (Method->isCopyAssignmentOperator() ||
8502 (!Copying && Method->isMoveAssignmentOperator()))
8503 continue;
8504
8505 F.erase();
8506 }
8507 F.done();
John McCallb0207482010-03-16 06:11:48 +00008508 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008509
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008510 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008511 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008512 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008513 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008514 // ambiguities), we need to cast "this" to that subobject type; to
8515 // ensure that we don't go through the virtual call mechanism, we need
8516 // to qualify the operator= name with the base class (see below). However,
8517 // this means that if the base class has a protected copy assignment
8518 // operator, the protected member access check will fail. So, we
8519 // rewrite "protected" access to "public" access in this case, since we
8520 // know by construction that we're calling from a derived class.
8521 if (CopyingBaseSubobject) {
8522 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8523 L != LEnd; ++L) {
8524 if (L.getAccess() == AS_protected)
8525 L.setAccess(AS_public);
8526 }
8527 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008528
Douglas Gregor06a9f362010-05-01 20:49:11 +00008529 // Create the nested-name-specifier that will be used to qualify the
8530 // reference to operator=; this is required to suppress the virtual
8531 // call mechanism.
8532 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008533 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008534 SS.MakeTrivial(S.Context,
8535 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008536 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008537 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008538
Douglas Gregor06a9f362010-05-01 20:49:11 +00008539 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008540 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008541 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008542 /*TemplateKWLoc=*/SourceLocation(),
8543 /*FirstQualifierInScope=*/0,
8544 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008545 /*TemplateArgs=*/0,
8546 /*SuppressQualifierCheck=*/true);
8547 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008548 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008549
Douglas Gregor06a9f362010-05-01 20:49:11 +00008550 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008551
Richard Smith044c8aa2012-11-13 00:54:12 +00008552 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008553 OpEqualRef.takeAs<Expr>(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00008554 Loc, From, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008555 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008556 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008557
Richard Smith8c889532012-11-14 00:50:40 +00008558 // If we built a call to a trivial 'operator=' while copying an array,
8559 // bail out. We'll replace the whole shebang with a memcpy.
8560 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8561 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8562 return StmtResult((Stmt*)0);
8563
Richard Smith044c8aa2012-11-13 00:54:12 +00008564 // Convert to an expression-statement, and clean up any produced
8565 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008566 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008567 }
John McCallb0207482010-03-16 06:11:48 +00008568
Richard Smith044c8aa2012-11-13 00:54:12 +00008569 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008570 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008571 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008572 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008573 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008574 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008575 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008576 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008577 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008578
8579 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008580 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008581
Douglas Gregor06a9f362010-05-01 20:49:11 +00008582 // Construct a loop over the array bounds, e.g.,
8583 //
8584 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8585 //
8586 // that will copy each of the array elements.
8587 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008588
Douglas Gregor06a9f362010-05-01 20:49:11 +00008589 // Create the iteration variable.
8590 IdentifierInfo *IterationVarName = 0;
8591 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008592 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008593 llvm::raw_svector_ostream OS(Str);
8594 OS << "__i" << Depth;
8595 IterationVarName = &S.Context.Idents.get(OS.str());
8596 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008597 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008598 IterationVarName, SizeType,
8599 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008600 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008601
Douglas Gregor06a9f362010-05-01 20:49:11 +00008602 // Initialize the iteration variable to zero.
8603 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008604 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008605
8606 // Create a reference to the iteration variable; we'll use this several
8607 // times throughout.
8608 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008609 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008610 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008611 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8612 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8613
Douglas Gregor06a9f362010-05-01 20:49:11 +00008614 // Create the DeclStmt that holds the iteration variable.
8615 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008616
Douglas Gregor06a9f362010-05-01 20:49:11 +00008617 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008618 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008619 IterationVarRefRVal,
8620 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008621 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008622 IterationVarRefRVal,
8623 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008624 if (!Copying) // Cast to rvalue
8625 From = CastForMoving(S, From);
8626
8627 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008628 StmtResult Copy =
8629 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8630 To, From, CopyingBaseSubobject,
8631 Copying, Depth + 1);
8632 // Bail out if copying fails or if we determined that we should use memcpy.
8633 if (Copy.isInvalid() || !Copy.get())
8634 return Copy;
8635
8636 // Create the comparison against the array bound.
8637 llvm::APInt Upper
8638 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8639 Expr *Comparison
8640 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8641 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8642 BO_NE, S.Context.BoolTy,
8643 VK_RValue, OK_Ordinary, Loc, false);
8644
8645 // Create the pre-increment of the iteration variable.
8646 Expr *Increment
8647 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8648 VK_LValue, OK_Ordinary, Loc);
8649
Douglas Gregor06a9f362010-05-01 20:49:11 +00008650 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008651 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008652 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008653 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008654 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008655}
8656
Richard Smith8c889532012-11-14 00:50:40 +00008657static StmtResult
8658buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8659 Expr *To, Expr *From,
8660 bool CopyingBaseSubobject, bool Copying) {
8661 // Maybe we should use a memcpy?
8662 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8663 T.isTriviallyCopyableType(S.Context))
8664 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8665
8666 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8667 CopyingBaseSubobject,
8668 Copying, 0));
8669
8670 // If we ended up picking a trivial assignment operator for an array of a
8671 // non-trivially-copyable class type, just emit a memcpy.
8672 if (!Result.isInvalid() && !Result.get())
8673 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8674
8675 return Result;
8676}
8677
Richard Smithb9d0b762012-07-27 04:22:15 +00008678Sema::ImplicitExceptionSpecification
8679Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8680 CXXRecordDecl *ClassDecl = MD->getParent();
8681
8682 ImplicitExceptionSpecification ExceptSpec(*this);
8683 if (ClassDecl->isInvalidDecl())
8684 return ExceptSpec;
8685
8686 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8687 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8688 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8689
Douglas Gregorb87786f2010-07-01 17:48:08 +00008690 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008691 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008692 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008693
8694 // It is unspecified whether or not an implicit copy assignment operator
8695 // attempts to deduplicate calls to assignment operators of virtual bases are
8696 // made. As such, this exception specification is effectively unspecified.
8697 // Based on a similar decision made for constness in C++0x, we're erring on
8698 // the side of assuming such calls to be made regardless of whether they
8699 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008700 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8701 BaseEnd = ClassDecl->bases_end();
8702 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008703 if (Base->isVirtual())
8704 continue;
8705
Douglas Gregora376d102010-07-02 21:50:04 +00008706 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008707 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008708 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8709 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008710 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008711 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008712
8713 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8714 BaseEnd = ClassDecl->vbases_end();
8715 Base != BaseEnd; ++Base) {
8716 CXXRecordDecl *BaseClassDecl
8717 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8718 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8719 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008720 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008721 }
8722
Douglas Gregorb87786f2010-07-01 17:48:08 +00008723 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8724 FieldEnd = ClassDecl->field_end();
8725 Field != FieldEnd;
8726 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008727 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008728 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8729 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008730 LookupCopyingAssignment(FieldClassDecl,
8731 ArgQuals | FieldType.getCVRQualifiers(),
8732 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008733 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008734 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008735 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008736
Richard Smithb9d0b762012-07-27 04:22:15 +00008737 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008738}
8739
8740CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8741 // Note: The following rules are largely analoguous to the copy
8742 // constructor rules. Note that virtual bases are not taken into account
8743 // for determining the argument type of the operator. Note also that
8744 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008745 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008746
Richard Smithafb49182012-11-29 01:34:07 +00008747 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8748 if (DSM.isAlreadyBeingDeclared())
8749 return 0;
8750
Sean Hunt30de05c2011-05-14 05:23:20 +00008751 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8752 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00008753 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
8754 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00008755 ArgType = ArgType.withConst();
8756 ArgType = Context.getLValueReferenceType(ArgType);
8757
Richard Smitha8942d72013-05-07 03:19:20 +00008758 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8759 CXXCopyAssignment,
8760 Const);
8761
Douglas Gregord3c35902010-07-01 16:36:15 +00008762 // An implicitly-declared copy assignment operator is an inline public
8763 // member of its class.
8764 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008765 SourceLocation ClassLoc = ClassDecl->getLocation();
8766 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00008767 CXXMethodDecl *CopyAssignment =
8768 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8769 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
8770 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008771 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008772 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008773 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008774
8775 // Build an exception specification pointing back at this member.
8776 FunctionProtoType::ExtProtoInfo EPI;
8777 EPI.ExceptionSpecType = EST_Unevaluated;
8778 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008779 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008780
Douglas Gregord3c35902010-07-01 16:36:15 +00008781 // Add the parameter to the operator.
8782 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008783 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008784 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008785 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008786 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008787
Richard Smithbc2a35d2012-12-08 08:32:28 +00008788 AddOverriddenMethods(ClassDecl, CopyAssignment);
8789
8790 CopyAssignment->setTrivial(
8791 ClassDecl->needsOverloadResolutionForCopyAssignment()
8792 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8793 : ClassDecl->hasTrivialCopyAssignment());
8794
Richard Smitha8942d72013-05-07 03:19:20 +00008795 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00008796 // .... If the class definition does not explicitly declare a copy
8797 // assignment operator, there is no user-declared move constructor, and
8798 // there is no user-declared move assignment operator, a copy assignment
8799 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008800 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008801 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008802
Richard Smithbc2a35d2012-12-08 08:32:28 +00008803 // Note that we have added this copy-assignment operator.
8804 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8805
8806 if (Scope *S = getScopeForContext(ClassDecl))
8807 PushOnScopeChains(CopyAssignment, S, false);
8808 ClassDecl->addDecl(CopyAssignment);
8809
Douglas Gregord3c35902010-07-01 16:36:15 +00008810 return CopyAssignment;
8811}
8812
Richard Smith36155c12013-06-13 03:23:42 +00008813/// Diagnose an implicit copy operation for a class which is odr-used, but
8814/// which is deprecated because the class has a user-declared copy constructor,
8815/// copy assignment operator, or destructor.
8816static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
8817 SourceLocation UseLoc) {
8818 assert(CopyOp->isImplicit());
8819
8820 CXXRecordDecl *RD = CopyOp->getParent();
8821 CXXMethodDecl *UserDeclaredOperation = 0;
8822
8823 // In Microsoft mode, assignment operations don't affect constructors and
8824 // vice versa.
8825 if (RD->hasUserDeclaredDestructor()) {
8826 UserDeclaredOperation = RD->getDestructor();
8827 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
8828 RD->hasUserDeclaredCopyConstructor() &&
8829 !S.getLangOpts().MicrosoftMode) {
8830 // Find any user-declared copy constructor.
8831 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
8832 E = RD->ctor_end(); I != E; ++I) {
8833 if (I->isCopyConstructor()) {
8834 UserDeclaredOperation = *I;
8835 break;
8836 }
8837 }
8838 assert(UserDeclaredOperation);
8839 } else if (isa<CXXConstructorDecl>(CopyOp) &&
8840 RD->hasUserDeclaredCopyAssignment() &&
8841 !S.getLangOpts().MicrosoftMode) {
8842 // Find any user-declared move assignment operator.
8843 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
8844 E = RD->method_end(); I != E; ++I) {
8845 if (I->isCopyAssignmentOperator()) {
8846 UserDeclaredOperation = *I;
8847 break;
8848 }
8849 }
8850 assert(UserDeclaredOperation);
8851 }
8852
8853 if (UserDeclaredOperation) {
8854 S.Diag(UserDeclaredOperation->getLocation(),
8855 diag::warn_deprecated_copy_operation)
8856 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
8857 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
8858 S.Diag(UseLoc, diag::note_member_synthesized_at)
8859 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
8860 : Sema::CXXCopyAssignment)
8861 << RD;
8862 }
8863}
8864
Douglas Gregor06a9f362010-05-01 20:49:11 +00008865void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8866 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008867 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008868 CopyAssignOperator->isOverloadedOperator() &&
8869 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008870 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8871 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008872 "DefineImplicitCopyAssignment called for wrong function");
8873
8874 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8875
8876 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8877 CopyAssignOperator->setInvalidDecl();
8878 return;
8879 }
Richard Smith36155c12013-06-13 03:23:42 +00008880
8881 // C++11 [class.copy]p18:
8882 // The [definition of an implicitly declared copy assignment operator] is
8883 // deprecated if the class has a user-declared copy constructor or a
8884 // user-declared destructor.
8885 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
8886 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
8887
Douglas Gregor06a9f362010-05-01 20:49:11 +00008888 CopyAssignOperator->setUsed();
8889
Eli Friedman9a14db32012-10-18 20:14:08 +00008890 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008891 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008892
8893 // C++0x [class.copy]p30:
8894 // The implicitly-defined or explicitly-defaulted copy assignment operator
8895 // for a non-union class X performs memberwise copy assignment of its
8896 // subobjects. The direct base classes of X are assigned first, in the
8897 // order of their declaration in the base-specifier-list, and then the
8898 // immediate non-static data members of X are assigned, in the order in
8899 // which they were declared in the class definition.
8900
8901 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008902 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008903
8904 // The parameter for the "other" object, which we are copying from.
8905 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8906 Qualifiers OtherQuals = Other->getType().getQualifiers();
8907 QualType OtherRefType = Other->getType();
8908 if (const LValueReferenceType *OtherRef
8909 = OtherRefType->getAs<LValueReferenceType>()) {
8910 OtherRefType = OtherRef->getPointeeType();
8911 OtherQuals = OtherRefType.getQualifiers();
8912 }
8913
8914 // Our location for everything implicitly-generated.
8915 SourceLocation Loc = CopyAssignOperator->getLocation();
8916
8917 // Construct a reference to the "other" object. We'll be using this
8918 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008919 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008920 assert(OtherRef && "Reference to parameter cannot fail!");
8921
8922 // Construct the "this" pointer. We'll be using this throughout the generated
8923 // ASTs.
8924 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8925 assert(This && "Reference to this cannot fail!");
8926
8927 // Assign base classes.
8928 bool Invalid = false;
8929 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8930 E = ClassDecl->bases_end(); Base != E; ++Base) {
8931 // Form the assignment:
8932 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8933 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008934 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008935 Invalid = true;
8936 continue;
8937 }
8938
John McCallf871d0c2010-08-07 06:22:56 +00008939 CXXCastPath BasePath;
8940 BasePath.push_back(Base);
8941
Douglas Gregor06a9f362010-05-01 20:49:11 +00008942 // Construct the "from" expression, which is an implicit cast to the
8943 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008944 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008945 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8946 CK_UncheckedDerivedToBase,
8947 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008948
8949 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008950 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008951
8952 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008953 To = ImpCastExprToType(To.take(),
8954 Context.getCVRQualifiedType(BaseType,
8955 CopyAssignOperator->getTypeQualifiers()),
8956 CK_UncheckedDerivedToBase,
8957 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008958
8959 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008960 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008961 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008962 /*CopyingBaseSubobject=*/true,
8963 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008964 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008965 Diag(CurrentLocation, diag::note_member_synthesized_at)
8966 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8967 CopyAssignOperator->setInvalidDecl();
8968 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008969 }
8970
8971 // Success! Record the copy.
8972 Statements.push_back(Copy.takeAs<Expr>());
8973 }
8974
Douglas Gregor06a9f362010-05-01 20:49:11 +00008975 // Assign non-static members.
8976 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8977 FieldEnd = ClassDecl->field_end();
8978 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008979 if (Field->isUnnamedBitfield())
8980 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00008981
8982 if (Field->isInvalidDecl()) {
8983 Invalid = true;
8984 continue;
8985 }
8986
Douglas Gregor06a9f362010-05-01 20:49:11 +00008987 // Check for members of reference type; we can't copy those.
8988 if (Field->getType()->isReferenceType()) {
8989 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8990 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8991 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008992 Diag(CurrentLocation, diag::note_member_synthesized_at)
8993 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008994 Invalid = true;
8995 continue;
8996 }
8997
8998 // Check for members of const-qualified, non-class type.
8999 QualType BaseType = Context.getBaseElementType(Field->getType());
9000 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9001 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9002 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9003 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009004 Diag(CurrentLocation, diag::note_member_synthesized_at)
9005 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009006 Invalid = true;
9007 continue;
9008 }
John McCallb77115d2011-06-17 00:18:42 +00009009
9010 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009011 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9012 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009013
9014 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009015 if (FieldType->isIncompleteArrayType()) {
9016 assert(ClassDecl->hasFlexibleArrayMember() &&
9017 "Incomplete array type is not valid");
9018 continue;
9019 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009020
9021 // Build references to the field in the object we're copying from and to.
9022 CXXScopeSpec SS; // Intentionally empty
9023 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9024 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009025 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009026 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00009027 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00009028 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009029 SS, SourceLocation(), 0,
9030 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00009031 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00009032 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009033 SS, SourceLocation(), 0,
9034 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009035 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9036 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00009037
Douglas Gregor06a9f362010-05-01 20:49:11 +00009038 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009039 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009040 To.get(), From.get(),
9041 /*CopyingBaseSubobject=*/false,
9042 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009043 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009044 Diag(CurrentLocation, diag::note_member_synthesized_at)
9045 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9046 CopyAssignOperator->setInvalidDecl();
9047 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009048 }
9049
9050 // Success! Record the copy.
9051 Statements.push_back(Copy.takeAs<Stmt>());
9052 }
9053
9054 if (!Invalid) {
9055 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00009056 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009057
John McCall60d7b3a2010-08-24 06:29:42 +00009058 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009059 if (Return.isInvalid())
9060 Invalid = true;
9061 else {
9062 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009063
9064 if (Trap.hasErrorOccurred()) {
9065 Diag(CurrentLocation, diag::note_member_synthesized_at)
9066 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9067 Invalid = true;
9068 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009069 }
9070 }
9071
9072 if (Invalid) {
9073 CopyAssignOperator->setInvalidDecl();
9074 return;
9075 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009076
9077 StmtResult Body;
9078 {
9079 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009080 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009081 /*isStmtExpr=*/false);
9082 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9083 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009084 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009085
9086 if (ASTMutationListener *L = getASTMutationListener()) {
9087 L->CompletedImplicitDefinition(CopyAssignOperator);
9088 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009089}
9090
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009091Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009092Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9093 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009094
Richard Smithb9d0b762012-07-27 04:22:15 +00009095 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009096 if (ClassDecl->isInvalidDecl())
9097 return ExceptSpec;
9098
9099 // C++0x [except.spec]p14:
9100 // An implicitly declared special member function (Clause 12) shall have an
9101 // exception-specification. [...]
9102
9103 // It is unspecified whether or not an implicit move assignment operator
9104 // attempts to deduplicate calls to assignment operators of virtual bases are
9105 // made. As such, this exception specification is effectively unspecified.
9106 // Based on a similar decision made for constness in C++0x, we're erring on
9107 // the side of assuming such calls to be made regardless of whether they
9108 // actually happen.
9109 // Note that a move constructor is not implicitly declared when there are
9110 // virtual bases, but it can still be user-declared and explicitly defaulted.
9111 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9112 BaseEnd = ClassDecl->bases_end();
9113 Base != BaseEnd; ++Base) {
9114 if (Base->isVirtual())
9115 continue;
9116
9117 CXXRecordDecl *BaseClassDecl
9118 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9119 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009120 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009121 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009122 }
9123
9124 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9125 BaseEnd = ClassDecl->vbases_end();
9126 Base != BaseEnd; ++Base) {
9127 CXXRecordDecl *BaseClassDecl
9128 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9129 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009130 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009131 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009132 }
9133
9134 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9135 FieldEnd = ClassDecl->field_end();
9136 Field != FieldEnd;
9137 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009138 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009139 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009140 if (CXXMethodDecl *MoveAssign =
9141 LookupMovingAssignment(FieldClassDecl,
9142 FieldType.getCVRQualifiers(),
9143 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009144 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009145 }
9146 }
9147
9148 return ExceptSpec;
9149}
9150
Richard Smith1c931be2012-04-02 18:40:40 +00009151/// Determine whether the class type has any direct or indirect virtual base
9152/// classes which have a non-trivial move assignment operator.
9153static bool
9154hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9155 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9156 BaseEnd = ClassDecl->vbases_end();
9157 Base != BaseEnd; ++Base) {
9158 CXXRecordDecl *BaseClass =
9159 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9160
9161 // Try to declare the move assignment. If it would be deleted, then the
9162 // class does not have a non-trivial move assignment.
9163 if (BaseClass->needsImplicitMoveAssignment())
9164 S.DeclareImplicitMoveAssignment(BaseClass);
9165
Richard Smith426391c2012-11-16 00:53:38 +00009166 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009167 return true;
9168 }
9169
9170 return false;
9171}
9172
9173/// Determine whether the given type either has a move constructor or is
9174/// trivially copyable.
9175static bool
9176hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9177 Type = S.Context.getBaseElementType(Type);
9178
9179 // FIXME: Technically, non-trivially-copyable non-class types, such as
9180 // reference types, are supposed to return false here, but that appears
9181 // to be a standard defect.
9182 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009183 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009184 return true;
9185
9186 if (Type.isTriviallyCopyableType(S.Context))
9187 return true;
9188
9189 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009190 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9191 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009192 if (ClassDecl->needsImplicitMoveConstructor())
9193 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009194 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009195 }
9196
Richard Smithe5411b72012-12-01 02:35:44 +00009197 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9198 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009199 if (ClassDecl->needsImplicitMoveAssignment())
9200 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009201 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009202}
9203
9204/// Determine whether all non-static data members and direct or virtual bases
9205/// of class \p ClassDecl have either a move operation, or are trivially
9206/// copyable.
9207static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9208 bool IsConstructor) {
9209 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9210 BaseEnd = ClassDecl->bases_end();
9211 Base != BaseEnd; ++Base) {
9212 if (Base->isVirtual())
9213 continue;
9214
9215 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9216 return false;
9217 }
9218
9219 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9220 BaseEnd = ClassDecl->vbases_end();
9221 Base != BaseEnd; ++Base) {
9222 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9223 return false;
9224 }
9225
9226 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9227 FieldEnd = ClassDecl->field_end();
9228 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009229 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009230 return false;
9231 }
9232
9233 return true;
9234}
9235
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009236CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009237 // C++11 [class.copy]p20:
9238 // If the definition of a class X does not explicitly declare a move
9239 // assignment operator, one will be implicitly declared as defaulted
9240 // if and only if:
9241 //
9242 // - [first 4 bullets]
9243 assert(ClassDecl->needsImplicitMoveAssignment());
9244
Richard Smithafb49182012-11-29 01:34:07 +00009245 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9246 if (DSM.isAlreadyBeingDeclared())
9247 return 0;
9248
Richard Smith1c931be2012-04-02 18:40:40 +00009249 // [Checked after we build the declaration]
9250 // - the move assignment operator would not be implicitly defined as
9251 // deleted,
9252
9253 // [DR1402]:
9254 // - X has no direct or indirect virtual base class with a non-trivial
9255 // move assignment operator, and
9256 // - each of X's non-static data members and direct or virtual base classes
9257 // has a type that either has a move assignment operator or is trivially
9258 // copyable.
9259 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9260 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9261 ClassDecl->setFailedImplicitMoveAssignment();
9262 return 0;
9263 }
9264
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009265 // Note: The following rules are largely analoguous to the move
9266 // constructor rules.
9267
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009268 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9269 QualType RetType = Context.getLValueReferenceType(ArgType);
9270 ArgType = Context.getRValueReferenceType(ArgType);
9271
Richard Smitha8942d72013-05-07 03:19:20 +00009272 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9273 CXXMoveAssignment,
9274 false);
9275
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009276 // An implicitly-declared move assignment operator is an inline public
9277 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009278 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9279 SourceLocation ClassLoc = ClassDecl->getLocation();
9280 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009281 CXXMethodDecl *MoveAssignment =
9282 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9283 /*TInfo=*/0, /*StorageClass=*/SC_None,
9284 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009285 MoveAssignment->setAccess(AS_public);
9286 MoveAssignment->setDefaulted();
9287 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009288
Richard Smithb9d0b762012-07-27 04:22:15 +00009289 // Build an exception specification pointing back at this member.
9290 FunctionProtoType::ExtProtoInfo EPI;
9291 EPI.ExceptionSpecType = EST_Unevaluated;
9292 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009293 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009294
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009295 // Add the parameter to the operator.
9296 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9297 ClassLoc, ClassLoc, /*Id=*/0,
9298 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009299 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009300 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009301
Richard Smithbc2a35d2012-12-08 08:32:28 +00009302 AddOverriddenMethods(ClassDecl, MoveAssignment);
9303
9304 MoveAssignment->setTrivial(
9305 ClassDecl->needsOverloadResolutionForMoveAssignment()
9306 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9307 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009308
9309 // C++0x [class.copy]p9:
9310 // If the definition of a class X does not explicitly declare a move
9311 // assignment operator, one will be implicitly declared as defaulted if and
9312 // only if:
9313 // [...]
9314 // - the move assignment operator would not be implicitly defined as
9315 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009316 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009317 // Cache this result so that we don't try to generate this over and over
9318 // on every lookup, leaking memory and wasting time.
9319 ClassDecl->setFailedImplicitMoveAssignment();
9320 return 0;
9321 }
9322
Richard Smithbc2a35d2012-12-08 08:32:28 +00009323 // Note that we have added this copy-assignment operator.
9324 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9325
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009326 if (Scope *S = getScopeForContext(ClassDecl))
9327 PushOnScopeChains(MoveAssignment, S, false);
9328 ClassDecl->addDecl(MoveAssignment);
9329
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009330 return MoveAssignment;
9331}
9332
9333void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9334 CXXMethodDecl *MoveAssignOperator) {
9335 assert((MoveAssignOperator->isDefaulted() &&
9336 MoveAssignOperator->isOverloadedOperator() &&
9337 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009338 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9339 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009340 "DefineImplicitMoveAssignment called for wrong function");
9341
9342 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9343
9344 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9345 MoveAssignOperator->setInvalidDecl();
9346 return;
9347 }
9348
9349 MoveAssignOperator->setUsed();
9350
Eli Friedman9a14db32012-10-18 20:14:08 +00009351 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009352 DiagnosticErrorTrap Trap(Diags);
9353
9354 // C++0x [class.copy]p28:
9355 // The implicitly-defined or move assignment operator for a non-union class
9356 // X performs memberwise move assignment of its subobjects. The direct base
9357 // classes of X are assigned first, in the order of their declaration in the
9358 // base-specifier-list, and then the immediate non-static data members of X
9359 // are assigned, in the order in which they were declared in the class
9360 // definition.
9361
9362 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009363 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009364
9365 // The parameter for the "other" object, which we are move from.
9366 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9367 QualType OtherRefType = Other->getType()->
9368 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009369 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009370 "Bad argument type of defaulted move assignment");
9371
9372 // Our location for everything implicitly-generated.
9373 SourceLocation Loc = MoveAssignOperator->getLocation();
9374
9375 // Construct a reference to the "other" object. We'll be using this
9376 // throughout the generated ASTs.
9377 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9378 assert(OtherRef && "Reference to parameter cannot fail!");
9379 // Cast to rvalue.
9380 OtherRef = CastForMoving(*this, OtherRef);
9381
9382 // Construct the "this" pointer. We'll be using this throughout the generated
9383 // ASTs.
9384 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9385 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009386
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009387 // Assign base classes.
9388 bool Invalid = false;
9389 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9390 E = ClassDecl->bases_end(); Base != E; ++Base) {
9391 // Form the assignment:
9392 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9393 QualType BaseType = Base->getType().getUnqualifiedType();
9394 if (!BaseType->isRecordType()) {
9395 Invalid = true;
9396 continue;
9397 }
9398
9399 CXXCastPath BasePath;
9400 BasePath.push_back(Base);
9401
9402 // Construct the "from" expression, which is an implicit cast to the
9403 // appropriately-qualified base type.
9404 Expr *From = OtherRef;
9405 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009406 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009407
9408 // Dereference "this".
9409 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9410
9411 // Implicitly cast "this" to the appropriately-qualified base type.
9412 To = ImpCastExprToType(To.take(),
9413 Context.getCVRQualifiedType(BaseType,
9414 MoveAssignOperator->getTypeQualifiers()),
9415 CK_UncheckedDerivedToBase,
9416 VK_LValue, &BasePath);
9417
9418 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009419 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009420 To.get(), From,
9421 /*CopyingBaseSubobject=*/true,
9422 /*Copying=*/false);
9423 if (Move.isInvalid()) {
9424 Diag(CurrentLocation, diag::note_member_synthesized_at)
9425 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9426 MoveAssignOperator->setInvalidDecl();
9427 return;
9428 }
9429
9430 // Success! Record the move.
9431 Statements.push_back(Move.takeAs<Expr>());
9432 }
9433
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009434 // Assign non-static members.
9435 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9436 FieldEnd = ClassDecl->field_end();
9437 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009438 if (Field->isUnnamedBitfield())
9439 continue;
9440
Eli Friedman8150da32013-06-07 01:48:56 +00009441 if (Field->isInvalidDecl()) {
9442 Invalid = true;
9443 continue;
9444 }
9445
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009446 // Check for members of reference type; we can't move those.
9447 if (Field->getType()->isReferenceType()) {
9448 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9449 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9450 Diag(Field->getLocation(), diag::note_declared_at);
9451 Diag(CurrentLocation, diag::note_member_synthesized_at)
9452 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9453 Invalid = true;
9454 continue;
9455 }
9456
9457 // Check for members of const-qualified, non-class type.
9458 QualType BaseType = Context.getBaseElementType(Field->getType());
9459 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9460 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9461 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9462 Diag(Field->getLocation(), diag::note_declared_at);
9463 Diag(CurrentLocation, diag::note_member_synthesized_at)
9464 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9465 Invalid = true;
9466 continue;
9467 }
9468
9469 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009470 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9471 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009472
9473 QualType FieldType = Field->getType().getNonReferenceType();
9474 if (FieldType->isIncompleteArrayType()) {
9475 assert(ClassDecl->hasFlexibleArrayMember() &&
9476 "Incomplete array type is not valid");
9477 continue;
9478 }
9479
9480 // Build references to the field in the object we're copying from and to.
9481 CXXScopeSpec SS; // Intentionally empty
9482 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9483 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009484 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009485 MemberLookup.resolveKind();
9486 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9487 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009488 SS, SourceLocation(), 0,
9489 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009490 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9491 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009492 SS, SourceLocation(), 0,
9493 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009494 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9495 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9496
9497 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9498 "Member reference with rvalue base must be rvalue except for reference "
9499 "members, which aren't allowed for move assignment.");
9500
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009501 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009502 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009503 To.get(), From.get(),
9504 /*CopyingBaseSubobject=*/false,
9505 /*Copying=*/false);
9506 if (Move.isInvalid()) {
9507 Diag(CurrentLocation, diag::note_member_synthesized_at)
9508 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9509 MoveAssignOperator->setInvalidDecl();
9510 return;
9511 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009512
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009513 // Success! Record the copy.
9514 Statements.push_back(Move.takeAs<Stmt>());
9515 }
9516
9517 if (!Invalid) {
9518 // Add a "return *this;"
9519 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9520
9521 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9522 if (Return.isInvalid())
9523 Invalid = true;
9524 else {
9525 Statements.push_back(Return.takeAs<Stmt>());
9526
9527 if (Trap.hasErrorOccurred()) {
9528 Diag(CurrentLocation, diag::note_member_synthesized_at)
9529 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9530 Invalid = true;
9531 }
9532 }
9533 }
9534
9535 if (Invalid) {
9536 MoveAssignOperator->setInvalidDecl();
9537 return;
9538 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009539
9540 StmtResult Body;
9541 {
9542 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009543 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009544 /*isStmtExpr=*/false);
9545 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9546 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009547 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9548
9549 if (ASTMutationListener *L = getASTMutationListener()) {
9550 L->CompletedImplicitDefinition(MoveAssignOperator);
9551 }
9552}
9553
Richard Smithb9d0b762012-07-27 04:22:15 +00009554Sema::ImplicitExceptionSpecification
9555Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9556 CXXRecordDecl *ClassDecl = MD->getParent();
9557
9558 ImplicitExceptionSpecification ExceptSpec(*this);
9559 if (ClassDecl->isInvalidDecl())
9560 return ExceptSpec;
9561
9562 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9563 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9564 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9565
Douglas Gregor0d405db2010-07-01 20:59:04 +00009566 // C++ [except.spec]p14:
9567 // An implicitly declared special member function (Clause 12) shall have an
9568 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009569 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9570 BaseEnd = ClassDecl->bases_end();
9571 Base != BaseEnd;
9572 ++Base) {
9573 // Virtual bases are handled below.
9574 if (Base->isVirtual())
9575 continue;
9576
Douglas Gregor22584312010-07-02 23:41:54 +00009577 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009578 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009579 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009580 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009581 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009582 }
9583 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9584 BaseEnd = ClassDecl->vbases_end();
9585 Base != BaseEnd;
9586 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009587 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009588 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009589 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009590 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009591 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009592 }
9593 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9594 FieldEnd = ClassDecl->field_end();
9595 Field != FieldEnd;
9596 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009597 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009598 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9599 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009600 LookupCopyingConstructor(FieldClassDecl,
9601 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009602 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009603 }
9604 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009605
Richard Smithb9d0b762012-07-27 04:22:15 +00009606 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009607}
9608
9609CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9610 CXXRecordDecl *ClassDecl) {
9611 // C++ [class.copy]p4:
9612 // If the class definition does not explicitly declare a copy
9613 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009614 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009615
Richard Smithafb49182012-11-29 01:34:07 +00009616 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9617 if (DSM.isAlreadyBeingDeclared())
9618 return 0;
9619
Sean Hunt49634cf2011-05-13 06:10:58 +00009620 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9621 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009622 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009623 if (Const)
9624 ArgType = ArgType.withConst();
9625 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009626
Richard Smith7756afa2012-06-10 05:43:50 +00009627 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9628 CXXCopyConstructor,
9629 Const);
9630
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009631 DeclarationName Name
9632 = Context.DeclarationNames.getCXXConstructorName(
9633 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009634 SourceLocation ClassLoc = ClassDecl->getLocation();
9635 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009636
9637 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009638 // member of its class.
9639 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009640 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009641 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009642 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009643 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009644 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009645
Richard Smithb9d0b762012-07-27 04:22:15 +00009646 // Build an exception specification pointing back at this member.
9647 FunctionProtoType::ExtProtoInfo EPI;
9648 EPI.ExceptionSpecType = EST_Unevaluated;
9649 EPI.ExceptionSpecDecl = CopyConstructor;
9650 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009651 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009652
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009653 // Add the parameter to the constructor.
9654 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009655 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009656 /*IdentifierInfo=*/0,
9657 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009658 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009659 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009660
Richard Smithbc2a35d2012-12-08 08:32:28 +00009661 CopyConstructor->setTrivial(
9662 ClassDecl->needsOverloadResolutionForCopyConstructor()
9663 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9664 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009665
Nico Weberafcc96a2012-01-23 03:19:29 +00009666 // C++11 [class.copy]p8:
9667 // ... If the class definition does not explicitly declare a copy
9668 // constructor, there is no user-declared move constructor, and there is no
9669 // user-declared move assignment operator, a copy constructor is implicitly
9670 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009671 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009672 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009673
Richard Smithbc2a35d2012-12-08 08:32:28 +00009674 // Note that we have declared this constructor.
9675 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9676
9677 if (Scope *S = getScopeForContext(ClassDecl))
9678 PushOnScopeChains(CopyConstructor, S, false);
9679 ClassDecl->addDecl(CopyConstructor);
9680
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009681 return CopyConstructor;
9682}
9683
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009684void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009685 CXXConstructorDecl *CopyConstructor) {
9686 assert((CopyConstructor->isDefaulted() &&
9687 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009688 !CopyConstructor->doesThisDeclarationHaveABody() &&
9689 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009690 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009691
Anders Carlsson63010a72010-04-23 16:24:12 +00009692 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009693 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009694
Richard Smith36155c12013-06-13 03:23:42 +00009695 // C++11 [class.copy]p7:
9696 // The [definition of an implicitly declared copy constructro] is
9697 // deprecated if the class has a user-declared copy assignment operator
9698 // or a user-declared destructor.
9699 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
9700 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
9701
Eli Friedman9a14db32012-10-18 20:14:08 +00009702 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009703 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009704
David Blaikie93c86172013-01-17 05:26:25 +00009705 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009706 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009707 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009708 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009709 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009710 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009711 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009712 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9713 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009714 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009715 /*isStmtExpr=*/false)
9716 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009717 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009718 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009719
9720 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009721 if (ASTMutationListener *L = getASTMutationListener()) {
9722 L->CompletedImplicitDefinition(CopyConstructor);
9723 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009724}
9725
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009726Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009727Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9728 CXXRecordDecl *ClassDecl = MD->getParent();
9729
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009730 // C++ [except.spec]p14:
9731 // An implicitly declared special member function (Clause 12) shall have an
9732 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009733 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009734 if (ClassDecl->isInvalidDecl())
9735 return ExceptSpec;
9736
9737 // Direct base-class constructors.
9738 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9739 BEnd = ClassDecl->bases_end();
9740 B != BEnd; ++B) {
9741 if (B->isVirtual()) // Handled below.
9742 continue;
9743
9744 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9745 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009746 CXXConstructorDecl *Constructor =
9747 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009748 // If this is a deleted function, add it anyway. This might be conformant
9749 // with the standard. This might not. I'm not sure. It might not matter.
9750 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009751 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009752 }
9753 }
9754
9755 // Virtual base-class constructors.
9756 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9757 BEnd = ClassDecl->vbases_end();
9758 B != BEnd; ++B) {
9759 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9760 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009761 CXXConstructorDecl *Constructor =
9762 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009763 // If this is a deleted function, add it anyway. This might be conformant
9764 // with the standard. This might not. I'm not sure. It might not matter.
9765 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009766 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009767 }
9768 }
9769
9770 // Field constructors.
9771 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9772 FEnd = ClassDecl->field_end();
9773 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009774 QualType FieldType = Context.getBaseElementType(F->getType());
9775 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9776 CXXConstructorDecl *Constructor =
9777 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009778 // If this is a deleted function, add it anyway. This might be conformant
9779 // with the standard. This might not. I'm not sure. It might not matter.
9780 // In particular, the problem is that this function never gets called. It
9781 // might just be ill-formed because this function attempts to refer to
9782 // a deleted function here.
9783 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009784 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009785 }
9786 }
9787
9788 return ExceptSpec;
9789}
9790
9791CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9792 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009793 // C++11 [class.copy]p9:
9794 // If the definition of a class X does not explicitly declare a move
9795 // constructor, one will be implicitly declared as defaulted if and only if:
9796 //
9797 // - [first 4 bullets]
9798 assert(ClassDecl->needsImplicitMoveConstructor());
9799
Richard Smithafb49182012-11-29 01:34:07 +00009800 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9801 if (DSM.isAlreadyBeingDeclared())
9802 return 0;
9803
Richard Smith1c931be2012-04-02 18:40:40 +00009804 // [Checked after we build the declaration]
9805 // - the move assignment operator would not be implicitly defined as
9806 // deleted,
9807
9808 // [DR1402]:
9809 // - each of X's non-static data members and direct or virtual base classes
9810 // has a type that either has a move constructor or is trivially copyable.
9811 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9812 ClassDecl->setFailedImplicitMoveConstructor();
9813 return 0;
9814 }
9815
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009816 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9817 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009818
Richard Smith7756afa2012-06-10 05:43:50 +00009819 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9820 CXXMoveConstructor,
9821 false);
9822
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009823 DeclarationName Name
9824 = Context.DeclarationNames.getCXXConstructorName(
9825 Context.getCanonicalType(ClassType));
9826 SourceLocation ClassLoc = ClassDecl->getLocation();
9827 DeclarationNameInfo NameInfo(Name, ClassLoc);
9828
Richard Smitha8942d72013-05-07 03:19:20 +00009829 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009830 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009831 // member of its class.
9832 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009833 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009834 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009835 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009836 MoveConstructor->setAccess(AS_public);
9837 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009838
Richard Smithb9d0b762012-07-27 04:22:15 +00009839 // Build an exception specification pointing back at this member.
9840 FunctionProtoType::ExtProtoInfo EPI;
9841 EPI.ExceptionSpecType = EST_Unevaluated;
9842 EPI.ExceptionSpecDecl = MoveConstructor;
9843 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009844 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009845
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009846 // Add the parameter to the constructor.
9847 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9848 ClassLoc, ClassLoc,
9849 /*IdentifierInfo=*/0,
9850 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009851 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009852 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009853
Richard Smithbc2a35d2012-12-08 08:32:28 +00009854 MoveConstructor->setTrivial(
9855 ClassDecl->needsOverloadResolutionForMoveConstructor()
9856 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9857 : ClassDecl->hasTrivialMoveConstructor());
9858
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009859 // C++0x [class.copy]p9:
9860 // If the definition of a class X does not explicitly declare a move
9861 // constructor, one will be implicitly declared as defaulted if and only if:
9862 // [...]
9863 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009864 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009865 // Cache this result so that we don't try to generate this over and over
9866 // on every lookup, leaking memory and wasting time.
9867 ClassDecl->setFailedImplicitMoveConstructor();
9868 return 0;
9869 }
9870
9871 // Note that we have declared this constructor.
9872 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9873
9874 if (Scope *S = getScopeForContext(ClassDecl))
9875 PushOnScopeChains(MoveConstructor, S, false);
9876 ClassDecl->addDecl(MoveConstructor);
9877
9878 return MoveConstructor;
9879}
9880
9881void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9882 CXXConstructorDecl *MoveConstructor) {
9883 assert((MoveConstructor->isDefaulted() &&
9884 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009885 !MoveConstructor->doesThisDeclarationHaveABody() &&
9886 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009887 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9888
9889 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9890 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9891
Eli Friedman9a14db32012-10-18 20:14:08 +00009892 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009893 DiagnosticErrorTrap Trap(Diags);
9894
David Blaikie93c86172013-01-17 05:26:25 +00009895 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009896 Trap.hasErrorOccurred()) {
9897 Diag(CurrentLocation, diag::note_member_synthesized_at)
9898 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9899 MoveConstructor->setInvalidDecl();
9900 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009901 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009902 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9903 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009904 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009905 /*isStmtExpr=*/false)
9906 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009907 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009908 }
9909
9910 MoveConstructor->setUsed();
9911
9912 if (ASTMutationListener *L = getASTMutationListener()) {
9913 L->CompletedImplicitDefinition(MoveConstructor);
9914 }
9915}
9916
Douglas Gregore4e68d42012-02-15 19:33:52 +00009917bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9918 return FD->isDeleted() &&
9919 (FD->isDefaulted() || FD->isImplicit()) &&
9920 isa<CXXMethodDecl>(FD);
9921}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009922
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009923/// \brief Mark the call operator of the given lambda closure type as "used".
9924static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9925 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009926 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009927 Lambda->lookup(
9928 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009929 CallOperator->setReferenced();
9930 CallOperator->setUsed();
9931}
9932
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009933void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9934 SourceLocation CurrentLocation,
9935 CXXConversionDecl *Conv)
9936{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009937 CXXRecordDecl *Lambda = Conv->getParent();
9938
9939 // Make sure that the lambda call operator is marked used.
9940 markLambdaCallOperatorUsed(*this, Lambda);
9941
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009942 Conv->setUsed();
9943
Eli Friedman9a14db32012-10-18 20:14:08 +00009944 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009945 DiagnosticErrorTrap Trap(Diags);
9946
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009947 // Return the address of the __invoke function.
9948 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9949 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009950 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009951 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9952 VK_LValue, Conv->getLocation()).take();
9953 assert(FunctionRef && "Can't refer to __invoke function?");
9954 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009955 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009956 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009957 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009958
9959 // Fill in the __invoke function with a dummy implementation. IR generation
9960 // will fill in the actual details.
9961 Invoke->setUsed();
9962 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009963 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009964
9965 if (ASTMutationListener *L = getASTMutationListener()) {
9966 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009967 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009968 }
9969}
9970
9971void Sema::DefineImplicitLambdaToBlockPointerConversion(
9972 SourceLocation CurrentLocation,
9973 CXXConversionDecl *Conv)
9974{
9975 Conv->setUsed();
9976
Eli Friedman9a14db32012-10-18 20:14:08 +00009977 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009978 DiagnosticErrorTrap Trap(Diags);
9979
Douglas Gregorac1303e2012-02-22 05:02:47 +00009980 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009981 Expr *This = ActOnCXXThis(CurrentLocation).take();
9982 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009983
Eli Friedman23f02672012-03-01 04:01:32 +00009984 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9985 Conv->getLocation(),
9986 Conv, DerefThis);
9987
9988 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9989 // behavior. Note that only the general conversion function does this
9990 // (since it's unusable otherwise); in the case where we inline the
9991 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009992 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009993 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9994 CK_CopyAndAutoreleaseBlockObject,
9995 BuildBlock.get(), 0, VK_RValue);
9996
9997 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009998 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009999 Conv->setInvalidDecl();
10000 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010001 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010002
Douglas Gregorac1303e2012-02-22 05:02:47 +000010003 // Create the return statement that returns the block from the conversion
10004 // function.
Eli Friedman23f02672012-03-01 04:01:32 +000010005 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010006 if (Return.isInvalid()) {
10007 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10008 Conv->setInvalidDecl();
10009 return;
10010 }
10011
10012 // Set the body of the conversion function.
10013 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010014 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010015 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010016 Conv->getLocation()));
10017
Douglas Gregorac1303e2012-02-22 05:02:47 +000010018 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010019 if (ASTMutationListener *L = getASTMutationListener()) {
10020 L->CompletedImplicitDefinition(Conv);
10021 }
10022}
10023
Douglas Gregorf52757d2012-03-10 06:53:13 +000010024/// \brief Determine whether the given list arguments contains exactly one
10025/// "real" (non-default) argument.
10026static bool hasOneRealArgument(MultiExprArg Args) {
10027 switch (Args.size()) {
10028 case 0:
10029 return false;
10030
10031 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010032 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010033 return false;
10034
10035 // fall through
10036 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010037 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010038 }
10039
10040 return false;
10041}
10042
John McCall60d7b3a2010-08-24 06:29:42 +000010043ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010044Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010045 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010046 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010047 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010048 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010049 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010050 unsigned ConstructKind,
10051 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010052 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010053
Douglas Gregor2f599792010-04-02 18:24:57 +000010054 // C++0x [class.copy]p34:
10055 // When certain criteria are met, an implementation is allowed to
10056 // omit the copy/move construction of a class object, even if the
10057 // copy/move constructor and/or destructor for the object have
10058 // side effects. [...]
10059 // - when a temporary class object that has not been bound to a
10060 // reference (12.2) would be copied/moved to a class object
10061 // with the same cv-unqualified type, the copy/move operation
10062 // can be omitted by constructing the temporary object
10063 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010064 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010065 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010066 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010067 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010068 }
Mike Stump1eb44332009-09-09 15:08:12 +000010069
10070 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010071 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010072 IsListInitialization, RequiresZeroInit,
10073 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010074}
10075
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010076/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10077/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010078ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010079Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10080 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010081 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010082 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010083 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010084 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010085 unsigned ConstructKind,
10086 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010087 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010088 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010089 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010090 HadMultipleCandidates,
10091 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010092 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10093 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010094}
10095
John McCall68c6c9a2010-02-02 09:10:11 +000010096void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010097 if (VD->isInvalidDecl()) return;
10098
John McCall68c6c9a2010-02-02 09:10:11 +000010099 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010100 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010101 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010102 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010103
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010104 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010105 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010106 CheckDestructorAccess(VD->getLocation(), Destructor,
10107 PDiag(diag::err_access_dtor_var)
10108 << VD->getDeclName()
10109 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010110 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010111
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010112 if (!VD->hasGlobalStorage()) return;
10113
10114 // Emit warning for non-trivial dtor in global scope (a real global,
10115 // class-static, function-static).
10116 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10117
10118 // TODO: this should be re-enabled for static locals by !CXAAtExit
10119 if (!VD->isStaticLocal())
10120 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010121}
10122
Douglas Gregor39da0b82009-09-09 23:08:42 +000010123/// \brief Given a constructor and the set of arguments provided for the
10124/// constructor, convert the arguments and add any required default arguments
10125/// to form a proper call to this constructor.
10126///
10127/// \returns true if an error occurred, false otherwise.
10128bool
10129Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10130 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010131 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010132 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010133 bool AllowExplicit,
10134 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010135 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10136 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010137 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010138
10139 const FunctionProtoType *Proto
10140 = Constructor->getType()->getAs<FunctionProtoType>();
10141 assert(Proto && "Constructor without a prototype?");
10142 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010143
10144 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010145 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010146 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010147 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010148 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010149
10150 VariadicCallType CallType =
10151 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010152 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010153 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010154 Proto, 0,
10155 llvm::makeArrayRef(Args, NumArgs),
10156 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010157 CallType, AllowExplicit,
10158 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010159 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010160
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010161 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010162
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010163 CheckConstructorCall(Constructor,
10164 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10165 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010166 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010167
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010168 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010169}
10170
Anders Carlsson20d45d22009-12-12 00:32:00 +000010171static inline bool
10172CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10173 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010174 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010175 if (isa<NamespaceDecl>(DC)) {
10176 return SemaRef.Diag(FnDecl->getLocation(),
10177 diag::err_operator_new_delete_declared_in_namespace)
10178 << FnDecl->getDeclName();
10179 }
10180
10181 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010182 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010183 return SemaRef.Diag(FnDecl->getLocation(),
10184 diag::err_operator_new_delete_declared_static)
10185 << FnDecl->getDeclName();
10186 }
10187
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010188 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010189}
10190
Anders Carlsson156c78e2009-12-13 17:53:43 +000010191static inline bool
10192CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10193 CanQualType ExpectedResultType,
10194 CanQualType ExpectedFirstParamType,
10195 unsigned DependentParamTypeDiag,
10196 unsigned InvalidParamTypeDiag) {
10197 QualType ResultType =
10198 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10199
10200 // Check that the result type is not dependent.
10201 if (ResultType->isDependentType())
10202 return SemaRef.Diag(FnDecl->getLocation(),
10203 diag::err_operator_new_delete_dependent_result_type)
10204 << FnDecl->getDeclName() << ExpectedResultType;
10205
10206 // Check that the result type is what we expect.
10207 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10208 return SemaRef.Diag(FnDecl->getLocation(),
10209 diag::err_operator_new_delete_invalid_result_type)
10210 << FnDecl->getDeclName() << ExpectedResultType;
10211
10212 // A function template must have at least 2 parameters.
10213 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10214 return SemaRef.Diag(FnDecl->getLocation(),
10215 diag::err_operator_new_delete_template_too_few_parameters)
10216 << FnDecl->getDeclName();
10217
10218 // The function decl must have at least 1 parameter.
10219 if (FnDecl->getNumParams() == 0)
10220 return SemaRef.Diag(FnDecl->getLocation(),
10221 diag::err_operator_new_delete_too_few_parameters)
10222 << FnDecl->getDeclName();
10223
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010224 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010225 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10226 if (FirstParamType->isDependentType())
10227 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10228 << FnDecl->getDeclName() << ExpectedFirstParamType;
10229
10230 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010231 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010232 ExpectedFirstParamType)
10233 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10234 << FnDecl->getDeclName() << ExpectedFirstParamType;
10235
10236 return false;
10237}
10238
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010239static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010240CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010241 // C++ [basic.stc.dynamic.allocation]p1:
10242 // A program is ill-formed if an allocation function is declared in a
10243 // namespace scope other than global scope or declared static in global
10244 // scope.
10245 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10246 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010247
10248 CanQualType SizeTy =
10249 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10250
10251 // C++ [basic.stc.dynamic.allocation]p1:
10252 // The return type shall be void*. The first parameter shall have type
10253 // std::size_t.
10254 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10255 SizeTy,
10256 diag::err_operator_new_dependent_param_type,
10257 diag::err_operator_new_param_type))
10258 return true;
10259
10260 // C++ [basic.stc.dynamic.allocation]p1:
10261 // The first parameter shall not have an associated default argument.
10262 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010263 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010264 diag::err_operator_new_default_arg)
10265 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10266
10267 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010268}
10269
10270static bool
Richard Smith444d3842012-10-20 08:26:51 +000010271CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010272 // C++ [basic.stc.dynamic.deallocation]p1:
10273 // A program is ill-formed if deallocation functions are declared in a
10274 // namespace scope other than global scope or declared static in global
10275 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010276 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10277 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010278
10279 // C++ [basic.stc.dynamic.deallocation]p2:
10280 // Each deallocation function shall return void and its first parameter
10281 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010282 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10283 SemaRef.Context.VoidPtrTy,
10284 diag::err_operator_delete_dependent_param_type,
10285 diag::err_operator_delete_param_type))
10286 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010287
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010288 return false;
10289}
10290
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010291/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10292/// of this overloaded operator is well-formed. If so, returns false;
10293/// otherwise, emits appropriate diagnostics and returns true.
10294bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010295 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010296 "Expected an overloaded operator declaration");
10297
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010298 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10299
Mike Stump1eb44332009-09-09 15:08:12 +000010300 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010301 // The allocation and deallocation functions, operator new,
10302 // operator new[], operator delete and operator delete[], are
10303 // described completely in 3.7.3. The attributes and restrictions
10304 // found in the rest of this subclause do not apply to them unless
10305 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010306 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010307 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010308
Anders Carlssona3ccda52009-12-12 00:26:23 +000010309 if (Op == OO_New || Op == OO_Array_New)
10310 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010311
10312 // C++ [over.oper]p6:
10313 // An operator function shall either be a non-static member
10314 // function or be a non-member function and have at least one
10315 // parameter whose type is a class, a reference to a class, an
10316 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010317 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10318 if (MethodDecl->isStatic())
10319 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010320 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010321 } else {
10322 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010323 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10324 ParamEnd = FnDecl->param_end();
10325 Param != ParamEnd; ++Param) {
10326 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010327 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10328 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010329 ClassOrEnumParam = true;
10330 break;
10331 }
10332 }
10333
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010334 if (!ClassOrEnumParam)
10335 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010336 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010337 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010338 }
10339
10340 // C++ [over.oper]p8:
10341 // An operator function cannot have default arguments (8.3.6),
10342 // except where explicitly stated below.
10343 //
Mike Stump1eb44332009-09-09 15:08:12 +000010344 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010345 // (C++ [over.call]p1).
10346 if (Op != OO_Call) {
10347 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10348 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010349 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010350 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010351 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010352 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010353 }
10354 }
10355
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010356 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10357 { false, false, false }
10358#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10359 , { Unary, Binary, MemberOnly }
10360#include "clang/Basic/OperatorKinds.def"
10361 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010362
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010363 bool CanBeUnaryOperator = OperatorUses[Op][0];
10364 bool CanBeBinaryOperator = OperatorUses[Op][1];
10365 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010366
10367 // C++ [over.oper]p8:
10368 // [...] Operator functions cannot have more or fewer parameters
10369 // than the number required for the corresponding operator, as
10370 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010371 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010372 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010373 if (Op != OO_Call &&
10374 ((NumParams == 1 && !CanBeUnaryOperator) ||
10375 (NumParams == 2 && !CanBeBinaryOperator) ||
10376 (NumParams < 1) || (NumParams > 2))) {
10377 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010378 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010379 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010380 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010381 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010382 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010383 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010384 assert(CanBeBinaryOperator &&
10385 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010386 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010387 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010388
Chris Lattner416e46f2008-11-21 07:57:12 +000010389 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010390 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010391 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010392
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010393 // Overloaded operators other than operator() cannot be variadic.
10394 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010395 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010396 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010397 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010398 }
10399
10400 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010401 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10402 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010403 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010404 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010405 }
10406
10407 // C++ [over.inc]p1:
10408 // The user-defined function called operator++ implements the
10409 // prefix and postfix ++ operator. If this function is a member
10410 // function with no parameters, or a non-member function with one
10411 // parameter of class or enumeration type, it defines the prefix
10412 // increment operator ++ for objects of that type. If the function
10413 // is a member function with one parameter (which shall be of type
10414 // int) or a non-member function with two parameters (the second
10415 // of which shall be of type int), it defines the postfix
10416 // increment operator ++ for objects of that type.
10417 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10418 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10419 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010420 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010421 ParamIsInt = BT->getKind() == BuiltinType::Int;
10422
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010423 if (!ParamIsInt)
10424 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010425 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010426 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010427 }
10428
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010429 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010430}
Chris Lattner5a003a42008-12-17 07:09:26 +000010431
Sean Hunta6c058d2010-01-13 09:01:02 +000010432/// CheckLiteralOperatorDeclaration - Check whether the declaration
10433/// of this literal operator function is well-formed. If so, returns
10434/// false; otherwise, emits appropriate diagnostics and returns true.
10435bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010436 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010437 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10438 << FnDecl->getDeclName();
10439 return true;
10440 }
10441
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010442 if (FnDecl->isExternC()) {
10443 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10444 return true;
10445 }
10446
Sean Hunta6c058d2010-01-13 09:01:02 +000010447 bool Valid = false;
10448
Richard Smith36f5cfe2012-03-09 08:00:36 +000010449 // This might be the definition of a literal operator template.
10450 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10451 // This might be a specialization of a literal operator template.
10452 if (!TpDecl)
10453 TpDecl = FnDecl->getPrimaryTemplate();
10454
Sean Hunt216c2782010-04-07 23:11:06 +000010455 // template <char...> type operator "" name() is the only valid template
10456 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010457 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010458 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010459 // Must have only one template parameter
10460 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10461 if (Params->size() == 1) {
10462 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010463 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010464
Sean Hunt216c2782010-04-07 23:11:06 +000010465 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010466 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10467 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10468 Valid = true;
10469 }
10470 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010471 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010472 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010473 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10474
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010475 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010476
Sean Hunt30019c02010-04-07 22:57:35 +000010477 // unsigned long long int, long double, and any character type are allowed
10478 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010479 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10480 Context.hasSameType(T, Context.LongDoubleTy) ||
10481 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010482 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010483 Context.hasSameType(T, Context.Char16Ty) ||
10484 Context.hasSameType(T, Context.Char32Ty)) {
10485 if (++Param == FnDecl->param_end())
10486 Valid = true;
10487 goto FinishedParams;
10488 }
10489
Sean Hunt30019c02010-04-07 22:57:35 +000010490 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010491 const PointerType *PT = T->getAs<PointerType>();
10492 if (!PT)
10493 goto FinishedParams;
10494 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010495 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010496 goto FinishedParams;
10497 T = T.getUnqualifiedType();
10498
10499 // Move on to the second parameter;
10500 ++Param;
10501
10502 // If there is no second parameter, the first must be a const char *
10503 if (Param == FnDecl->param_end()) {
10504 if (Context.hasSameType(T, Context.CharTy))
10505 Valid = true;
10506 goto FinishedParams;
10507 }
10508
10509 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10510 // are allowed as the first parameter to a two-parameter function
10511 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010512 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010513 Context.hasSameType(T, Context.Char16Ty) ||
10514 Context.hasSameType(T, Context.Char32Ty)))
10515 goto FinishedParams;
10516
10517 // The second and final parameter must be an std::size_t
10518 T = (*Param)->getType().getUnqualifiedType();
10519 if (Context.hasSameType(T, Context.getSizeType()) &&
10520 ++Param == FnDecl->param_end())
10521 Valid = true;
10522 }
10523
10524 // FIXME: This diagnostic is absolutely terrible.
10525FinishedParams:
10526 if (!Valid) {
10527 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10528 << FnDecl->getDeclName();
10529 return true;
10530 }
10531
Richard Smitha9e88b22012-03-09 08:16:22 +000010532 // A parameter-declaration-clause containing a default argument is not
10533 // equivalent to any of the permitted forms.
10534 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10535 ParamEnd = FnDecl->param_end();
10536 Param != ParamEnd; ++Param) {
10537 if ((*Param)->hasDefaultArg()) {
10538 Diag((*Param)->getDefaultArgRange().getBegin(),
10539 diag::err_literal_operator_default_argument)
10540 << (*Param)->getDefaultArgRange();
10541 break;
10542 }
10543 }
10544
Richard Smith2fb4ae32012-03-08 02:39:21 +000010545 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010546 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10547 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010548 // C++11 [usrlit.suffix]p1:
10549 // Literal suffix identifiers that do not start with an underscore
10550 // are reserved for future standardization.
10551 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010552 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010553
Sean Hunta6c058d2010-01-13 09:01:02 +000010554 return false;
10555}
10556
Douglas Gregor074149e2009-01-05 19:45:36 +000010557/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10558/// linkage specification, including the language and (if present)
10559/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10560/// the location of the language string literal, which is provided
10561/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10562/// the '{' brace. Otherwise, this linkage specification does not
10563/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010564Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10565 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010566 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010567 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010568 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010569 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010570 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010571 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010572 Language = LinkageSpecDecl::lang_cxx;
10573 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010574 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010575 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010576 }
Mike Stump1eb44332009-09-09 15:08:12 +000010577
Chris Lattnercc98eac2008-12-17 07:13:27 +000010578 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010579
Douglas Gregor074149e2009-01-05 19:45:36 +000010580 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010581 ExternLoc, LangLoc, Language,
10582 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010583 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010584 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010585 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010586}
10587
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010588/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010589/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10590/// valid, it's the position of the closing '}' brace in a linkage
10591/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010592Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010593 Decl *LinkageSpec,
10594 SourceLocation RBraceLoc) {
10595 if (LinkageSpec) {
10596 if (RBraceLoc.isValid()) {
10597 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10598 LSDecl->setRBraceLoc(RBraceLoc);
10599 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010600 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010601 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010602 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010603}
10604
Michael Han684aa732013-02-22 17:15:32 +000010605Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10606 AttributeList *AttrList,
10607 SourceLocation SemiLoc) {
10608 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10609 // Attribute declarations appertain to empty declaration so we handle
10610 // them here.
10611 if (AttrList)
10612 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010613
Michael Han684aa732013-02-22 17:15:32 +000010614 CurContext->addDecl(ED);
10615 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010616}
10617
Douglas Gregord308e622009-05-18 20:51:54 +000010618/// \brief Perform semantic analysis for the variable declaration that
10619/// occurs within a C++ catch clause, returning the newly-created
10620/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010621VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010622 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010623 SourceLocation StartLoc,
10624 SourceLocation Loc,
10625 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010626 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010627 QualType ExDeclType = TInfo->getType();
10628
Sebastian Redl4b07b292008-12-22 19:15:10 +000010629 // Arrays and functions decay.
10630 if (ExDeclType->isArrayType())
10631 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10632 else if (ExDeclType->isFunctionType())
10633 ExDeclType = Context.getPointerType(ExDeclType);
10634
10635 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10636 // The exception-declaration shall not denote a pointer or reference to an
10637 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010638 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010639 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010640 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010641 Invalid = true;
10642 }
Douglas Gregord308e622009-05-18 20:51:54 +000010643
Sebastian Redl4b07b292008-12-22 19:15:10 +000010644 QualType BaseType = ExDeclType;
10645 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010646 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010647 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010648 BaseType = Ptr->getPointeeType();
10649 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010650 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010651 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010652 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010653 BaseType = Ref->getPointeeType();
10654 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010655 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010656 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010657 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010658 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010659 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010660
Mike Stump1eb44332009-09-09 15:08:12 +000010661 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010662 RequireNonAbstractType(Loc, ExDeclType,
10663 diag::err_abstract_type_in_decl,
10664 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010665 Invalid = true;
10666
John McCall5a180392010-07-24 00:37:23 +000010667 // Only the non-fragile NeXT runtime currently supports C++ catches
10668 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010669 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010670 QualType T = ExDeclType;
10671 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10672 T = RT->getPointeeType();
10673
10674 if (T->isObjCObjectType()) {
10675 Diag(Loc, diag::err_objc_object_catch);
10676 Invalid = true;
10677 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010678 // FIXME: should this be a test for macosx-fragile specifically?
10679 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010680 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010681 }
10682 }
10683
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010684 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010685 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010686 ExDecl->setExceptionVariable(true);
10687
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010688 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010689 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010690 Invalid = true;
10691
Douglas Gregorc41b8782011-07-06 18:14:43 +000010692 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010693 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010694 // Insulate this from anything else we might currently be parsing.
10695 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10696
Douglas Gregor6d182892010-03-05 23:38:39 +000010697 // C++ [except.handle]p16:
10698 // The object declared in an exception-declaration or, if the
10699 // exception-declaration does not specify a name, a temporary (12.2) is
10700 // copy-initialized (8.5) from the exception object. [...]
10701 // The object is destroyed when the handler exits, after the destruction
10702 // of any automatic objects initialized within the handler.
10703 //
10704 // We just pretend to initialize the object with itself, then make sure
10705 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010706 QualType initType = ExDeclType;
10707
10708 InitializedEntity entity =
10709 InitializedEntity::InitializeVariable(ExDecl);
10710 InitializationKind initKind =
10711 InitializationKind::CreateCopy(Loc, SourceLocation());
10712
10713 Expr *opaqueValue =
10714 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000010715 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10716 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000010717 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010718 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010719 else {
10720 // If the constructor used was non-trivial, set this as the
10721 // "initializer".
10722 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10723 if (!construct->getConstructor()->isTrivial()) {
10724 Expr *init = MaybeCreateExprWithCleanups(construct);
10725 ExDecl->setInit(init);
10726 }
10727
10728 // And make sure it's destructable.
10729 FinalizeVarWithDestructor(ExDecl, recordType);
10730 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010731 }
10732 }
10733
Douglas Gregord308e622009-05-18 20:51:54 +000010734 if (Invalid)
10735 ExDecl->setInvalidDecl();
10736
10737 return ExDecl;
10738}
10739
10740/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10741/// handler.
John McCalld226f652010-08-21 09:40:31 +000010742Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010743 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010744 bool Invalid = D.isInvalidType();
10745
10746 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010747 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10748 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010749 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10750 D.getIdentifierLoc());
10751 Invalid = true;
10752 }
10753
Sebastian Redl4b07b292008-12-22 19:15:10 +000010754 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010755 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010756 LookupOrdinaryName,
10757 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010758 // The scope should be freshly made just for us. There is just no way
10759 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010760 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010761 if (PrevDecl->isTemplateParameter()) {
10762 // Maybe we will complain about the shadowed template parameter.
10763 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010764 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010765 }
10766 }
10767
Chris Lattnereaaebc72009-04-25 08:06:05 +000010768 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010769 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10770 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010771 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010772 }
10773
Douglas Gregor83cb9422010-09-09 17:09:21 +000010774 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010775 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010776 D.getIdentifierLoc(),
10777 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010778 if (Invalid)
10779 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010780
Sebastian Redl4b07b292008-12-22 19:15:10 +000010781 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010782 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010783 PushOnScopeChains(ExDecl, S);
10784 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010785 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010786
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010787 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010788 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010789}
Anders Carlssonfb311762009-03-14 00:25:26 +000010790
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010791Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010792 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010793 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010794 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010795 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010796
Richard Smithe3f470a2012-07-11 22:37:56 +000010797 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10798 return 0;
10799
10800 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10801 AssertMessage, RParenLoc, false);
10802}
10803
10804Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10805 Expr *AssertExpr,
10806 StringLiteral *AssertMessage,
10807 SourceLocation RParenLoc,
10808 bool Failed) {
10809 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10810 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010811 // In a static_assert-declaration, the constant-expression shall be a
10812 // constant expression that can be contextually converted to bool.
10813 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10814 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010815 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010816
Richard Smithdaaefc52011-12-14 23:32:26 +000010817 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010818 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010819 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010820 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010821 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010822
Richard Smithe3f470a2012-07-11 22:37:56 +000010823 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010824 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010825 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010826 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010827 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010828 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010829 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010830 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010831 }
Mike Stump1eb44332009-09-09 15:08:12 +000010832
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010833 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010834 AssertExpr, AssertMessage, RParenLoc,
10835 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010836
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010837 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010838 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010839}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010840
Douglas Gregor1d869352010-04-07 16:53:43 +000010841/// \brief Perform semantic analysis of the given friend type declaration.
10842///
10843/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010844FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010845 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010846 TypeSourceInfo *TSInfo) {
10847 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10848
10849 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010850 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010851
Richard Smith6b130222011-10-18 21:39:00 +000010852 // C++03 [class.friend]p2:
10853 // An elaborated-type-specifier shall be used in a friend declaration
10854 // for a class.*
10855 //
10856 // * The class-key of the elaborated-type-specifier is required.
10857 if (!ActiveTemplateInstantiations.empty()) {
10858 // Do not complain about the form of friend template types during
10859 // template instantiation; we will already have complained when the
10860 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010861 } else {
10862 if (!T->isElaboratedTypeSpecifier()) {
10863 // If we evaluated the type to a record type, suggest putting
10864 // a tag in front.
10865 if (const RecordType *RT = T->getAs<RecordType>()) {
10866 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010867
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010868 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010869
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010870 Diag(TypeRange.getBegin(),
10871 getLangOpts().CPlusPlus11 ?
10872 diag::warn_cxx98_compat_unelaborated_friend_type :
10873 diag::ext_unelaborated_friend_type)
10874 << (unsigned) RD->getTagKind()
10875 << T
10876 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10877 InsertionText);
10878 } else {
10879 Diag(FriendLoc,
10880 getLangOpts().CPlusPlus11 ?
10881 diag::warn_cxx98_compat_nonclass_type_friend :
10882 diag::ext_nonclass_type_friend)
10883 << T
10884 << TypeRange;
10885 }
10886 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010887 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010888 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010889 diag::warn_cxx98_compat_enum_friend :
10890 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010891 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010892 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010893 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010894
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010895 // C++11 [class.friend]p3:
10896 // A friend declaration that does not declare a function shall have one
10897 // of the following forms:
10898 // friend elaborated-type-specifier ;
10899 // friend simple-type-specifier ;
10900 // friend typename-specifier ;
10901 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10902 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10903 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010904
Douglas Gregor06245bf2010-04-07 17:57:12 +000010905 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010906 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010907 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010908 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010909}
10910
John McCall9a34edb2010-10-19 01:40:49 +000010911/// Handle a friend tag declaration where the scope specifier was
10912/// templated.
10913Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10914 unsigned TagSpec, SourceLocation TagLoc,
10915 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010916 IdentifierInfo *Name,
10917 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010918 AttributeList *Attr,
10919 MultiTemplateParamsArg TempParamLists) {
10920 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10921
10922 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010923 bool Invalid = false;
10924
10925 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010926 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010927 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010928 TempParamLists.size(),
10929 /*friend*/ true,
10930 isExplicitSpecialization,
10931 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010932 if (TemplateParams->size() > 0) {
10933 // This is a declaration of a class template.
10934 if (Invalid)
10935 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010936
Eric Christopher4110e132011-07-21 05:34:24 +000010937 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10938 SS, Name, NameLoc, Attr,
10939 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010940 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010941 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010942 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010943 } else {
10944 // The "template<>" header is extraneous.
10945 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10946 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10947 isExplicitSpecialization = true;
10948 }
10949 }
10950
10951 if (Invalid) return 0;
10952
John McCall9a34edb2010-10-19 01:40:49 +000010953 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010954 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010955 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010956 isAllExplicitSpecializations = false;
10957 break;
10958 }
10959 }
10960
10961 // FIXME: don't ignore attributes.
10962
10963 // If it's explicit specializations all the way down, just forget
10964 // about the template header and build an appropriate non-templated
10965 // friend. TODO: for source fidelity, remember the headers.
10966 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010967 if (SS.isEmpty()) {
10968 bool Owned = false;
10969 bool IsDependent = false;
10970 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10971 Attr, AS_public,
10972 /*ModulePrivateLoc=*/SourceLocation(),
10973 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010974 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010975 /*ScopedEnumUsesClassTag=*/false,
10976 /*UnderlyingType=*/TypeResult());
10977 }
10978
Douglas Gregor2494dd02011-03-01 01:34:45 +000010979 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010980 ElaboratedTypeKeyword Keyword
10981 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010982 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010983 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010984 if (T.isNull())
10985 return 0;
10986
10987 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10988 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010989 DependentNameTypeLoc TL =
10990 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010991 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010992 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010993 TL.setNameLoc(NameLoc);
10994 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010995 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010996 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010997 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010998 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010999 }
11000
11001 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011002 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011003 Friend->setAccess(AS_public);
11004 CurContext->addDecl(Friend);
11005 return Friend;
11006 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011007
11008 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11009
11010
John McCall9a34edb2010-10-19 01:40:49 +000011011
11012 // Handle the case of a templated-scope friend class. e.g.
11013 // template <class T> class A<T>::B;
11014 // FIXME: we don't support these right now.
11015 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11016 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11017 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011018 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011019 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011020 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011021 TL.setNameLoc(NameLoc);
11022
11023 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011024 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011025 Friend->setAccess(AS_public);
11026 Friend->setUnsupportedFriend(true);
11027 CurContext->addDecl(Friend);
11028 return Friend;
11029}
11030
11031
John McCalldd4a3b02009-09-16 22:47:08 +000011032/// Handle a friend type declaration. This works in tandem with
11033/// ActOnTag.
11034///
11035/// Notes on friend class templates:
11036///
11037/// We generally treat friend class declarations as if they were
11038/// declaring a class. So, for example, the elaborated type specifier
11039/// in a friend declaration is required to obey the restrictions of a
11040/// class-head (i.e. no typedefs in the scope chain), template
11041/// parameters are required to match up with simple template-ids, &c.
11042/// However, unlike when declaring a template specialization, it's
11043/// okay to refer to a template specialization without an empty
11044/// template parameter declaration, e.g.
11045/// friend class A<T>::B<unsigned>;
11046/// We permit this as a special case; if there are any template
11047/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011048/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011049Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011050 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011051 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011052
11053 assert(DS.isFriendSpecified());
11054 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11055
John McCalldd4a3b02009-09-16 22:47:08 +000011056 // Try to convert the decl specifier to a type. This works for
11057 // friend templates because ActOnTag never produces a ClassTemplateDecl
11058 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011059 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011060 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11061 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011062 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011063 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011064
Douglas Gregor6ccab972010-12-16 01:14:37 +000011065 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11066 return 0;
11067
John McCalldd4a3b02009-09-16 22:47:08 +000011068 // This is definitely an error in C++98. It's probably meant to
11069 // be forbidden in C++0x, too, but the specification is just
11070 // poorly written.
11071 //
11072 // The problem is with declarations like the following:
11073 // template <T> friend A<T>::foo;
11074 // where deciding whether a class C is a friend or not now hinges
11075 // on whether there exists an instantiation of A that causes
11076 // 'foo' to equal C. There are restrictions on class-heads
11077 // (which we declare (by fiat) elaborated friend declarations to
11078 // be) that makes this tractable.
11079 //
11080 // FIXME: handle "template <> friend class A<T>;", which
11081 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011082 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011083 Diag(Loc, diag::err_tagless_friend_type_template)
11084 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011085 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011086 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011087
John McCall02cace72009-08-28 07:59:38 +000011088 // C++98 [class.friend]p1: A friend of a class is a function
11089 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011090 // This is fixed in DR77, which just barely didn't make the C++03
11091 // deadline. It's also a very silly restriction that seriously
11092 // affects inner classes and which nobody else seems to implement;
11093 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011094 //
11095 // But note that we could warn about it: it's always useless to
11096 // friend one of your own members (it's not, however, worthless to
11097 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011098
John McCalldd4a3b02009-09-16 22:47:08 +000011099 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011100 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011101 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011102 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011103 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011104 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011105 DS.getFriendSpecLoc());
11106 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011107 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011108
11109 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011110 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011111
John McCalldd4a3b02009-09-16 22:47:08 +000011112 D->setAccess(AS_public);
11113 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011114
John McCalld226f652010-08-21 09:40:31 +000011115 return D;
John McCall02cace72009-08-28 07:59:38 +000011116}
11117
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011118NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11119 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011120 const DeclSpec &DS = D.getDeclSpec();
11121
11122 assert(DS.isFriendSpecified());
11123 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11124
11125 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011126 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011127
11128 // C++ [class.friend]p1
11129 // A friend of a class is a function or class....
11130 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011131 // It *doesn't* see through dependent types, which is correct
11132 // according to [temp.arg.type]p3:
11133 // If a declaration acquires a function type through a
11134 // type dependent on a template-parameter and this causes
11135 // a declaration that does not use the syntactic form of a
11136 // function declarator to have a function type, the program
11137 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011138 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011139 Diag(Loc, diag::err_unexpected_friend);
11140
11141 // It might be worthwhile to try to recover by creating an
11142 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011143 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011144 }
11145
11146 // C++ [namespace.memdef]p3
11147 // - If a friend declaration in a non-local class first declares a
11148 // class or function, the friend class or function is a member
11149 // of the innermost enclosing namespace.
11150 // - The name of the friend is not found by simple name lookup
11151 // until a matching declaration is provided in that namespace
11152 // scope (either before or after the class declaration granting
11153 // friendship).
11154 // - If a friend function is called, its name may be found by the
11155 // name lookup that considers functions from namespaces and
11156 // classes associated with the types of the function arguments.
11157 // - When looking for a prior declaration of a class or a function
11158 // declared as a friend, scopes outside the innermost enclosing
11159 // namespace scope are not considered.
11160
John McCall337ec3d2010-10-12 23:13:28 +000011161 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011162 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11163 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011164 assert(Name);
11165
Douglas Gregor6ccab972010-12-16 01:14:37 +000011166 // Check for unexpanded parameter packs.
11167 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11168 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11169 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11170 return 0;
11171
John McCall67d1a672009-08-06 02:15:43 +000011172 // The context we found the declaration in, or in which we should
11173 // create the declaration.
11174 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011175 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011176 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011177 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011178
John McCall337ec3d2010-10-12 23:13:28 +000011179 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000011180
John McCall337ec3d2010-10-12 23:13:28 +000011181 // There are four cases here.
11182 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000011183 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000011184 // there as appropriate.
11185 // Recover from invalid scope qualifiers as if they just weren't there.
11186 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000011187 // C++0x [namespace.memdef]p3:
11188 // If the name in a friend declaration is neither qualified nor
11189 // a template-id and the declaration is a function or an
11190 // elaborated-type-specifier, the lookup to determine whether
11191 // the entity has been previously declared shall not consider
11192 // any scopes outside the innermost enclosing namespace.
11193 // C++0x [class.friend]p11:
11194 // If a friend declaration appears in a local class and the name
11195 // specified is an unqualified name, a prior declaration is
11196 // looked up without considering scopes that are outside the
11197 // innermost enclosing non-class scope. For a friend function
11198 // declaration, if there is no prior declaration, the program is
11199 // ill-formed.
11200 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000011201 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011202
John McCall29ae6e52010-10-13 05:45:15 +000011203 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011204 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011205
Rafael Espindola11dc6342013-04-25 20:12:36 +000011206 // Skip class contexts. If someone can cite chapter and verse
11207 // for this behavior, that would be nice --- it's what GCC and
11208 // EDG do, and it seems like a reasonable intent, but the spec
11209 // really only says that checks for unqualified existing
11210 // declarations should stop at the nearest enclosing namespace,
11211 // not that they should only consider the nearest enclosing
11212 // namespace.
11213 while (DC->isRecord())
11214 DC = DC->getParent();
11215
11216 DeclContext *LookupDC = DC;
11217 while (LookupDC->isTransparentContext())
11218 LookupDC = LookupDC->getParent();
11219
11220 while (true) {
11221 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011222
11223 // TODO: decide what we think about using declarations.
Rafael Espindola11dc6342013-04-25 20:12:36 +000011224 if (isLocal)
John McCall67d1a672009-08-06 02:15:43 +000011225 break;
John McCall29ae6e52010-10-13 05:45:15 +000011226
Rafael Espindola11dc6342013-04-25 20:12:36 +000011227 if (!Previous.empty()) {
11228 DC = LookupDC;
11229 break;
John McCall8a407372010-10-14 22:22:28 +000011230 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011231
11232 if (isTemplateId) {
11233 if (isa<TranslationUnitDecl>(LookupDC)) break;
11234 } else {
11235 if (LookupDC->isFileContext()) break;
11236 }
11237 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011238 }
11239
John McCall380aaa42010-10-13 06:22:15 +000011240 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011241
Douglas Gregor883af832011-10-10 01:11:59 +000011242 // C++ [class.friend]p6:
11243 // A function can be defined in a friend declaration of a class if and
11244 // only if the class is a non-local class (9.8), the function name is
11245 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011246 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011247 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11248 }
11249
John McCall337ec3d2010-10-12 23:13:28 +000011250 // - There's a non-dependent scope specifier, in which case we
11251 // compute it and do a previous lookup there for a function
11252 // or function template.
11253 } else if (!SS.getScopeRep()->isDependent()) {
11254 DC = computeDeclContext(SS);
11255 if (!DC) return 0;
11256
11257 if (RequireCompleteDeclContext(SS, DC)) return 0;
11258
11259 LookupQualifiedName(Previous, DC);
11260
11261 // Ignore things found implicitly in the wrong scope.
11262 // TODO: better diagnostics for this case. Suggesting the right
11263 // qualified scope would be nice...
11264 LookupResult::Filter F = Previous.makeFilter();
11265 while (F.hasNext()) {
11266 NamedDecl *D = F.next();
11267 if (!DC->InEnclosingNamespaceSetOf(
11268 D->getDeclContext()->getRedeclContext()))
11269 F.erase();
11270 }
11271 F.done();
11272
11273 if (Previous.empty()) {
11274 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011275 Diag(Loc, diag::err_qualified_friend_not_found)
11276 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011277 return 0;
11278 }
11279
11280 // C++ [class.friend]p1: A friend of a class is a function or
11281 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011282 if (DC->Equals(CurContext))
11283 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011284 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011285 diag::warn_cxx98_compat_friend_is_member :
11286 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011287
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011288 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011289 // C++ [class.friend]p6:
11290 // A function can be defined in a friend declaration of a class if and
11291 // only if the class is a non-local class (9.8), the function name is
11292 // unqualified, and the function has namespace scope.
11293 SemaDiagnosticBuilder DB
11294 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11295
11296 DB << SS.getScopeRep();
11297 if (DC->isFileContext())
11298 DB << FixItHint::CreateRemoval(SS.getRange());
11299 SS.clear();
11300 }
John McCall337ec3d2010-10-12 23:13:28 +000011301
11302 // - There's a scope specifier that does not match any template
11303 // parameter lists, in which case we use some arbitrary context,
11304 // create a method or method template, and wait for instantiation.
11305 // - There's a scope specifier that does match some template
11306 // parameter lists, which we don't handle right now.
11307 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011308 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011309 // C++ [class.friend]p6:
11310 // A function can be defined in a friend declaration of a class if and
11311 // only if the class is a non-local class (9.8), the function name is
11312 // unqualified, and the function has namespace scope.
11313 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11314 << SS.getScopeRep();
11315 }
11316
John McCall337ec3d2010-10-12 23:13:28 +000011317 DC = CurContext;
11318 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011319 }
Douglas Gregor883af832011-10-10 01:11:59 +000011320
John McCall29ae6e52010-10-13 05:45:15 +000011321 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011322 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011323 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11324 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11325 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011326 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011327 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11328 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011329 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011330 }
John McCall67d1a672009-08-06 02:15:43 +000011331 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011332
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011333 // FIXME: This is an egregious hack to cope with cases where the scope stack
11334 // does not contain the declaration context, i.e., in an out-of-line
11335 // definition of a class.
11336 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11337 if (!DCScope) {
11338 FakeDCScope.setEntity(DC);
11339 DCScope = &FakeDCScope;
11340 }
11341
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011342 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011343 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011344 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011345 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011346
Douglas Gregor182ddf02009-09-28 00:08:27 +000011347 assert(ND->getDeclContext() == DC);
11348 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011349
John McCallab88d972009-08-31 22:39:49 +000011350 // Add the function declaration to the appropriate lookup tables,
11351 // adjusting the redeclarations list as necessary. We don't
11352 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011353 //
John McCallab88d972009-08-31 22:39:49 +000011354 // Also update the scope-based lookup if the target context's
11355 // lookup context is in lexical scope.
11356 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011357 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011358 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011359 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011360 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011361 }
John McCall02cace72009-08-28 07:59:38 +000011362
11363 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011364 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011365 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011366 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011367 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011368
John McCall1f2e1a92012-08-10 03:15:35 +000011369 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011370 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011371 } else {
11372 if (DC->isRecord()) CheckFriendAccess(ND);
11373
John McCall6102ca12010-10-16 06:59:13 +000011374 FunctionDecl *FD;
11375 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11376 FD = FTD->getTemplatedDecl();
11377 else
11378 FD = cast<FunctionDecl>(ND);
11379
11380 // Mark templated-scope function declarations as unsupported.
11381 if (FD->getNumTemplateParameterLists())
11382 FrD->setUnsupportedFriend(true);
11383 }
John McCall337ec3d2010-10-12 23:13:28 +000011384
John McCalld226f652010-08-21 09:40:31 +000011385 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011386}
11387
John McCalld226f652010-08-21 09:40:31 +000011388void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11389 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011390
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011391 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011392 if (!Fn) {
11393 Diag(DelLoc, diag::err_deleted_non_function);
11394 return;
11395 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011396
Douglas Gregoref96ee02012-01-14 16:38:05 +000011397 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011398 // Don't consider the implicit declaration we generate for explicit
11399 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011400 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11401 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011402 Diag(DelLoc, diag::err_deleted_decl_not_first);
11403 Diag(Prev->getLocation(), diag::note_previous_declaration);
11404 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011405 // If the declaration wasn't the first, we delete the function anyway for
11406 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011407 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011408 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011409
11410 if (Fn->isDeleted())
11411 return;
11412
11413 // See if we're deleting a function which is already known to override a
11414 // non-deleted virtual function.
11415 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11416 bool IssuedDiagnostic = false;
11417 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11418 E = MD->end_overridden_methods();
11419 I != E; ++I) {
11420 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11421 if (!IssuedDiagnostic) {
11422 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11423 IssuedDiagnostic = true;
11424 }
11425 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11426 }
11427 }
11428 }
11429
Sean Hunt10620eb2011-05-06 20:44:56 +000011430 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011431}
Sebastian Redl13e88542009-04-27 21:33:24 +000011432
Sean Hunte4246a62011-05-12 06:15:49 +000011433void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011434 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011435
11436 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011437 if (MD->getParent()->isDependentType()) {
11438 MD->setDefaulted();
11439 MD->setExplicitlyDefaulted();
11440 return;
11441 }
11442
Sean Hunte4246a62011-05-12 06:15:49 +000011443 CXXSpecialMember Member = getSpecialMember(MD);
11444 if (Member == CXXInvalid) {
11445 Diag(DefaultLoc, diag::err_default_special_members);
11446 return;
11447 }
11448
11449 MD->setDefaulted();
11450 MD->setExplicitlyDefaulted();
11451
Sean Huntcd10dec2011-05-23 23:14:04 +000011452 // If this definition appears within the record, do the checking when
11453 // the record is complete.
11454 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011455 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011456 // Find the uninstantiated declaration that actually had the '= default'
11457 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011458 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011459
Richard Smith12fef492013-03-27 00:22:47 +000011460 // If the method was defaulted on its first declaration, we will have
11461 // already performed the checking in CheckCompletedCXXClass. Such a
11462 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011463 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011464 return;
11465
Richard Smithb9d0b762012-07-27 04:22:15 +000011466 CheckExplicitlyDefaultedSpecialMember(MD);
11467
Richard Smith1d28caf2012-12-11 01:14:52 +000011468 // The exception specification is needed because we are defining the
11469 // function.
11470 ResolveExceptionSpec(DefaultLoc,
11471 MD->getType()->castAs<FunctionProtoType>());
11472
Sean Hunte4246a62011-05-12 06:15:49 +000011473 switch (Member) {
11474 case CXXDefaultConstructor: {
11475 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011476 if (!CD->isInvalidDecl())
11477 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11478 break;
11479 }
11480
11481 case CXXCopyConstructor: {
11482 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011483 if (!CD->isInvalidDecl())
11484 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011485 break;
11486 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011487
Sean Hunt2b188082011-05-14 05:23:28 +000011488 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011489 if (!MD->isInvalidDecl())
11490 DefineImplicitCopyAssignment(DefaultLoc, MD);
11491 break;
11492 }
11493
Sean Huntcb45a0f2011-05-12 22:46:25 +000011494 case CXXDestructor: {
11495 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011496 if (!DD->isInvalidDecl())
11497 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011498 break;
11499 }
11500
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011501 case CXXMoveConstructor: {
11502 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011503 if (!CD->isInvalidDecl())
11504 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011505 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011506 }
Sean Hunt82713172011-05-25 23:16:36 +000011507
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011508 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011509 if (!MD->isInvalidDecl())
11510 DefineImplicitMoveAssignment(DefaultLoc, MD);
11511 break;
11512 }
11513
11514 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011515 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011516 }
11517 } else {
11518 Diag(DefaultLoc, diag::err_default_special_members);
11519 }
11520}
11521
Sebastian Redl13e88542009-04-27 21:33:24 +000011522static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011523 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011524 Stmt *SubStmt = *CI;
11525 if (!SubStmt)
11526 continue;
11527 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011528 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011529 diag::err_return_in_constructor_handler);
11530 if (!isa<Expr>(SubStmt))
11531 SearchForReturnInStmt(Self, SubStmt);
11532 }
11533}
11534
11535void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11536 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11537 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11538 SearchForReturnInStmt(*this, Handler);
11539 }
11540}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011541
David Blaikie299adab2013-01-18 23:03:15 +000011542bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011543 const CXXMethodDecl *Old) {
11544 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11545 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11546
11547 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11548
11549 // If the calling conventions match, everything is fine
11550 if (NewCC == OldCC)
11551 return false;
11552
11553 // If either of the calling conventions are set to "default", we need to pick
11554 // something more sensible based on the target. This supports code where the
11555 // one method explicitly sets thiscall, and another has no explicit calling
11556 // convention.
11557 CallingConv Default =
11558 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11559 if (NewCC == CC_Default)
11560 NewCC = Default;
11561 if (OldCC == CC_Default)
11562 OldCC = Default;
11563
11564 // If the calling conventions still don't match, then report the error
11565 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011566 Diag(New->getLocation(),
11567 diag::err_conflicting_overriding_cc_attributes)
11568 << New->getDeclName() << New->getType() << Old->getType();
11569 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11570 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011571 }
11572
11573 return false;
11574}
11575
Mike Stump1eb44332009-09-09 15:08:12 +000011576bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011577 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011578 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11579 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011580
Chandler Carruth73857792010-02-15 11:53:20 +000011581 if (Context.hasSameType(NewTy, OldTy) ||
11582 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011583 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011584
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011585 // Check if the return types are covariant
11586 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011587
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011588 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011589 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11590 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011591 NewClassTy = NewPT->getPointeeType();
11592 OldClassTy = OldPT->getPointeeType();
11593 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011594 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11595 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11596 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11597 NewClassTy = NewRT->getPointeeType();
11598 OldClassTy = OldRT->getPointeeType();
11599 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011600 }
11601 }
Mike Stump1eb44332009-09-09 15:08:12 +000011602
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011603 // The return types aren't either both pointers or references to a class type.
11604 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011605 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011606 diag::err_different_return_type_for_overriding_virtual_function)
11607 << New->getDeclName() << NewTy << OldTy;
11608 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011609
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011610 return true;
11611 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011612
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011613 // C++ [class.virtual]p6:
11614 // If the return type of D::f differs from the return type of B::f, the
11615 // class type in the return type of D::f shall be complete at the point of
11616 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011617 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11618 if (!RT->isBeingDefined() &&
11619 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011620 diag::err_covariant_return_incomplete,
11621 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011622 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011623 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011624
Douglas Gregora4923eb2009-11-16 21:35:15 +000011625 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011626 // Check if the new class derives from the old class.
11627 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11628 Diag(New->getLocation(),
11629 diag::err_covariant_return_not_derived)
11630 << New->getDeclName() << NewTy << OldTy;
11631 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11632 return true;
11633 }
Mike Stump1eb44332009-09-09 15:08:12 +000011634
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011635 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011636 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011637 diag::err_covariant_return_inaccessible_base,
11638 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11639 // FIXME: Should this point to the return type?
11640 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011641 // FIXME: this note won't trigger for delayed access control
11642 // diagnostics, and it's impossible to get an undelayed error
11643 // here from access control during the original parse because
11644 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011645 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11646 return true;
11647 }
11648 }
Mike Stump1eb44332009-09-09 15:08:12 +000011649
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011650 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011651 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011652 Diag(New->getLocation(),
11653 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011654 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011655 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11656 return true;
11657 };
Mike Stump1eb44332009-09-09 15:08:12 +000011658
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011659
11660 // The new class type must have the same or less qualifiers as the old type.
11661 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11662 Diag(New->getLocation(),
11663 diag::err_covariant_return_type_class_type_more_qualified)
11664 << New->getDeclName() << NewTy << OldTy;
11665 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11666 return true;
11667 };
Mike Stump1eb44332009-09-09 15:08:12 +000011668
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011669 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011670}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011671
Douglas Gregor4ba31362009-12-01 17:24:26 +000011672/// \brief Mark the given method pure.
11673///
11674/// \param Method the method to be marked pure.
11675///
11676/// \param InitRange the source range that covers the "0" initializer.
11677bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011678 SourceLocation EndLoc = InitRange.getEnd();
11679 if (EndLoc.isValid())
11680 Method->setRangeEnd(EndLoc);
11681
Douglas Gregor4ba31362009-12-01 17:24:26 +000011682 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11683 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011684 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011685 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011686
11687 if (!Method->isInvalidDecl())
11688 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11689 << Method->getDeclName() << InitRange;
11690 return true;
11691}
11692
Douglas Gregor552e2992012-02-21 02:22:07 +000011693/// \brief Determine whether the given declaration is a static data member.
11694static bool isStaticDataMember(Decl *D) {
11695 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11696 if (!Var)
11697 return false;
11698
11699 return Var->isStaticDataMember();
11700}
John McCall731ad842009-12-19 09:28:58 +000011701/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11702/// an initializer for the out-of-line declaration 'Dcl'. The scope
11703/// is a fresh scope pushed for just this purpose.
11704///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011705/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11706/// static data member of class X, names should be looked up in the scope of
11707/// class X.
John McCalld226f652010-08-21 09:40:31 +000011708void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011709 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011710 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011711
John McCall731ad842009-12-19 09:28:58 +000011712 // We should only get called for declarations with scope specifiers, like:
11713 // int foo::bar;
11714 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011715 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011716
11717 // If we are parsing the initializer for a static data member, push a
11718 // new expression evaluation context that is associated with this static
11719 // data member.
11720 if (isStaticDataMember(D))
11721 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011722}
11723
11724/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011725/// initializer for the out-of-line declaration 'D'.
11726void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011727 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011728 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011729
Douglas Gregor552e2992012-02-21 02:22:07 +000011730 if (isStaticDataMember(D))
11731 PopExpressionEvaluationContext();
11732
John McCall731ad842009-12-19 09:28:58 +000011733 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011734 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011735}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011736
11737/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11738/// C++ if/switch/while/for statement.
11739/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011740DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011741 // C++ 6.4p2:
11742 // The declarator shall not specify a function or an array.
11743 // The type-specifier-seq shall not contain typedef and shall not declare a
11744 // new class or enumeration.
11745 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11746 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011747
11748 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011749 if (!Dcl)
11750 return true;
11751
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011752 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11753 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011754 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011755 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011756 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011757
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011758 return Dcl;
11759}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011760
Douglas Gregordfe65432011-07-28 19:11:31 +000011761void Sema::LoadExternalVTableUses() {
11762 if (!ExternalSource)
11763 return;
11764
11765 SmallVector<ExternalVTableUse, 4> VTables;
11766 ExternalSource->ReadUsedVTables(VTables);
11767 SmallVector<VTableUse, 4> NewUses;
11768 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11769 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11770 = VTablesUsed.find(VTables[I].Record);
11771 // Even if a definition wasn't required before, it may be required now.
11772 if (Pos != VTablesUsed.end()) {
11773 if (!Pos->second && VTables[I].DefinitionRequired)
11774 Pos->second = true;
11775 continue;
11776 }
11777
11778 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11779 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11780 }
11781
11782 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11783}
11784
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011785void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11786 bool DefinitionRequired) {
11787 // Ignore any vtable uses in unevaluated operands or for classes that do
11788 // not have a vtable.
11789 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000011790 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011791 return;
11792
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011793 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011794 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011795 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11796 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11797 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11798 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011799 // If we already had an entry, check to see if we are promoting this vtable
11800 // to required a definition. If so, we need to reappend to the VTableUses
11801 // list, since we may have already processed the first entry.
11802 if (DefinitionRequired && !Pos.first->second) {
11803 Pos.first->second = true;
11804 } else {
11805 // Otherwise, we can early exit.
11806 return;
11807 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011808 }
11809
11810 // Local classes need to have their virtual members marked
11811 // immediately. For all other classes, we mark their virtual members
11812 // at the end of the translation unit.
11813 if (Class->isLocalClass())
11814 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011815 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011816 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011817}
11818
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011819bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011820 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011821 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011822 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011823
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011824 // Note: The VTableUses vector could grow as a result of marking
11825 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011826 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011827 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011828 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011829 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011830 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011831 if (!Class)
11832 continue;
11833
11834 SourceLocation Loc = VTableUses[I].second;
11835
Richard Smithb9d0b762012-07-27 04:22:15 +000011836 bool DefineVTable = true;
11837
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011838 // If this class has a key function, but that key function is
11839 // defined in another translation unit, we don't need to emit the
11840 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011841 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011842 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011843 switch (KeyFunction->getTemplateSpecializationKind()) {
11844 case TSK_Undeclared:
11845 case TSK_ExplicitSpecialization:
11846 case TSK_ExplicitInstantiationDeclaration:
11847 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011848 DefineVTable = false;
11849 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011850
11851 case TSK_ExplicitInstantiationDefinition:
11852 case TSK_ImplicitInstantiation:
11853 // We will be instantiating the key function.
11854 break;
11855 }
11856 } else if (!KeyFunction) {
11857 // If we have a class with no key function that is the subject
11858 // of an explicit instantiation declaration, suppress the
11859 // vtable; it will live with the explicit instantiation
11860 // definition.
11861 bool IsExplicitInstantiationDeclaration
11862 = Class->getTemplateSpecializationKind()
11863 == TSK_ExplicitInstantiationDeclaration;
11864 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11865 REnd = Class->redecls_end();
11866 R != REnd; ++R) {
11867 TemplateSpecializationKind TSK
11868 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11869 if (TSK == TSK_ExplicitInstantiationDeclaration)
11870 IsExplicitInstantiationDeclaration = true;
11871 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11872 IsExplicitInstantiationDeclaration = false;
11873 break;
11874 }
11875 }
11876
11877 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011878 DefineVTable = false;
11879 }
11880
11881 // The exception specifications for all virtual members may be needed even
11882 // if we are not providing an authoritative form of the vtable in this TU.
11883 // We may choose to emit it available_externally anyway.
11884 if (!DefineVTable) {
11885 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11886 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011887 }
11888
11889 // Mark all of the virtual members of this class as referenced, so
11890 // that we can build a vtable. Then, tell the AST consumer that a
11891 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011892 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011893 MarkVirtualMembersReferenced(Loc, Class);
11894 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11895 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11896
11897 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000011898 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011899 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011900 const FunctionDecl *KeyFunctionDef = 0;
11901 if (!KeyFunction ||
11902 (KeyFunction->hasBody(KeyFunctionDef) &&
11903 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011904 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11905 TSK_ExplicitInstantiationDefinition
11906 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11907 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011908 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011909 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011910 VTableUses.clear();
11911
Douglas Gregor78844032011-04-22 22:25:37 +000011912 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011913}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011914
Richard Smithb9d0b762012-07-27 04:22:15 +000011915void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11916 const CXXRecordDecl *RD) {
11917 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11918 E = RD->method_end(); I != E; ++I)
11919 if ((*I)->isVirtual() && !(*I)->isPure())
11920 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11921}
11922
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011923void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11924 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011925 // Mark all functions which will appear in RD's vtable as used.
11926 CXXFinalOverriderMap FinalOverriders;
11927 RD->getFinalOverriders(FinalOverriders);
11928 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11929 E = FinalOverriders.end();
11930 I != E; ++I) {
11931 for (OverridingMethods::const_iterator OI = I->second.begin(),
11932 OE = I->second.end();
11933 OI != OE; ++OI) {
11934 assert(OI->second.size() > 0 && "no final overrider");
11935 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011936
Richard Smithff817f72012-07-07 06:59:51 +000011937 // C++ [basic.def.odr]p2:
11938 // [...] A virtual member function is used if it is not pure. [...]
11939 if (!Overrider->isPure())
11940 MarkFunctionReferenced(Loc, Overrider);
11941 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011942 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011943
11944 // Only classes that have virtual bases need a VTT.
11945 if (RD->getNumVBases() == 0)
11946 return;
11947
11948 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11949 e = RD->bases_end(); i != e; ++i) {
11950 const CXXRecordDecl *Base =
11951 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011952 if (Base->getNumVBases() == 0)
11953 continue;
11954 MarkVirtualMembersReferenced(Loc, Base);
11955 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011956}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011957
11958/// SetIvarInitializers - This routine builds initialization ASTs for the
11959/// Objective-C implementation whose ivars need be initialized.
11960void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011961 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011962 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011963 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011964 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011965 CollectIvarsToConstructOrDestruct(OID, ivars);
11966 if (ivars.empty())
11967 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011968 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011969 for (unsigned i = 0; i < ivars.size(); i++) {
11970 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011971 if (Field->isInvalidDecl())
11972 continue;
11973
Sean Huntcbb67482011-01-08 20:30:50 +000011974 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011975 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11976 InitializationKind InitKind =
11977 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000011978
11979 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
11980 ExprResult MemberInit =
11981 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000011982 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011983 // Note, MemberInit could actually come back empty if no initialization
11984 // is required (e.g., because it would call a trivial default constructor)
11985 if (!MemberInit.get() || MemberInit.isInvalid())
11986 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011987
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011988 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011989 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11990 SourceLocation(),
11991 MemberInit.takeAs<Expr>(),
11992 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011993 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011994
11995 // Be sure that the destructor is accessible and is marked as referenced.
11996 if (const RecordType *RecordTy
11997 = Context.getBaseElementType(Field->getType())
11998 ->getAs<RecordType>()) {
11999 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000012000 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012001 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012002 CheckDestructorAccess(Field->getLocation(), Destructor,
12003 PDiag(diag::err_access_dtor_ivar)
12004 << Context.getBaseElementType(Field->getType()));
12005 }
12006 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012007 }
12008 ObjCImplementation->setIvarInitializers(Context,
12009 AllToInit.data(), AllToInit.size());
12010 }
12011}
Sean Huntfe57eef2011-05-04 05:57:24 +000012012
Sean Huntebcbe1d2011-05-04 23:29:54 +000012013static
12014void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12015 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12016 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12017 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12018 Sema &S) {
12019 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12020 CE = Current.end();
12021 if (Ctor->isInvalidDecl())
12022 return;
12023
Richard Smitha8eaf002012-08-23 06:16:52 +000012024 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12025
12026 // Target may not be determinable yet, for instance if this is a dependent
12027 // call in an uninstantiated template.
12028 if (Target) {
12029 const FunctionDecl *FNTarget = 0;
12030 (void)Target->hasBody(FNTarget);
12031 Target = const_cast<CXXConstructorDecl*>(
12032 cast_or_null<CXXConstructorDecl>(FNTarget));
12033 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012034
12035 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12036 // Avoid dereferencing a null pointer here.
12037 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12038
12039 if (!Current.insert(Canonical))
12040 return;
12041
12042 // We know that beyond here, we aren't chaining into a cycle.
12043 if (!Target || !Target->isDelegatingConstructor() ||
12044 Target->isInvalidDecl() || Valid.count(TCanonical)) {
12045 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12046 Valid.insert(*CI);
12047 Current.clear();
12048 // We've hit a cycle.
12049 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12050 Current.count(TCanonical)) {
12051 // If we haven't diagnosed this cycle yet, do so now.
12052 if (!Invalid.count(TCanonical)) {
12053 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012054 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012055 << Ctor;
12056
Richard Smitha8eaf002012-08-23 06:16:52 +000012057 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012058 if (TCanonical != Canonical)
12059 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12060
12061 CXXConstructorDecl *C = Target;
12062 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012063 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012064 (void)C->getTargetConstructor()->hasBody(FNTarget);
12065 assert(FNTarget && "Ctor cycle through bodiless function");
12066
Richard Smitha8eaf002012-08-23 06:16:52 +000012067 C = const_cast<CXXConstructorDecl*>(
12068 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012069 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12070 }
12071 }
12072
12073 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12074 Invalid.insert(*CI);
12075 Current.clear();
12076 } else {
12077 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12078 }
12079}
12080
12081
Sean Huntfe57eef2011-05-04 05:57:24 +000012082void Sema::CheckDelegatingCtorCycles() {
12083 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12084
Sean Huntebcbe1d2011-05-04 23:29:54 +000012085 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12086 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000012087
Douglas Gregor0129b562011-07-27 21:57:17 +000012088 for (DelegatingCtorDeclsType::iterator
12089 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012090 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012091 I != E; ++I)
12092 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012093
12094 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
12095 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012096}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012097
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012098namespace {
12099 /// \brief AST visitor that finds references to the 'this' expression.
12100 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12101 Sema &S;
12102
12103 public:
12104 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12105
12106 bool VisitCXXThisExpr(CXXThisExpr *E) {
12107 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12108 << E->isImplicit();
12109 return false;
12110 }
12111 };
12112}
12113
12114bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12115 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12116 if (!TSInfo)
12117 return false;
12118
12119 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012120 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012121 if (!ProtoTL)
12122 return false;
12123
12124 // C++11 [expr.prim.general]p3:
12125 // [The expression this] shall not appear before the optional
12126 // cv-qualifier-seq and it shall not appear within the declaration of a
12127 // static member function (although its type and value category are defined
12128 // within a static member function as they are within a non-static member
12129 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012130 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012131 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012132 FindCXXThisExpr Finder(*this);
12133
12134 // If the return type came after the cv-qualifier-seq, check it now.
12135 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012136 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012137 return true;
12138
12139 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012140 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12141 return true;
12142
12143 return checkThisInStaticMemberFunctionAttributes(Method);
12144}
12145
12146bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12147 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12148 if (!TSInfo)
12149 return false;
12150
12151 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012152 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012153 if (!ProtoTL)
12154 return false;
12155
David Blaikie39e6ab42013-02-18 22:06:02 +000012156 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012157 FindCXXThisExpr Finder(*this);
12158
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012159 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012160 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012161 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012162 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012163 case EST_DynamicNone:
12164 case EST_MSAny:
12165 case EST_None:
12166 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012167
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012168 case EST_ComputedNoexcept:
12169 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12170 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012171
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012172 case EST_Dynamic:
12173 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012174 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012175 E != EEnd; ++E) {
12176 if (!Finder.TraverseType(*E))
12177 return true;
12178 }
12179 break;
12180 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012181
12182 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012183}
12184
12185bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12186 FindCXXThisExpr Finder(*this);
12187
12188 // Check attributes.
12189 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12190 A != AEnd; ++A) {
12191 // FIXME: This should be emitted by tblgen.
12192 Expr *Arg = 0;
12193 ArrayRef<Expr *> Args;
12194 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12195 Arg = G->getArg();
12196 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12197 Arg = G->getArg();
12198 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12199 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12200 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12201 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12202 else if (ExclusiveLockFunctionAttr *ELF
12203 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12204 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12205 else if (SharedLockFunctionAttr *SLF
12206 = dyn_cast<SharedLockFunctionAttr>(*A))
12207 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12208 else if (ExclusiveTrylockFunctionAttr *ETLF
12209 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12210 Arg = ETLF->getSuccessValue();
12211 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12212 } else if (SharedTrylockFunctionAttr *STLF
12213 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12214 Arg = STLF->getSuccessValue();
12215 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12216 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12217 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12218 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12219 Arg = LR->getArg();
12220 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12221 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12222 else if (ExclusiveLocksRequiredAttr *ELR
12223 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12224 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12225 else if (SharedLocksRequiredAttr *SLR
12226 = dyn_cast<SharedLocksRequiredAttr>(*A))
12227 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12228
12229 if (Arg && !Finder.TraverseStmt(Arg))
12230 return true;
12231
12232 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12233 if (!Finder.TraverseStmt(Args[I]))
12234 return true;
12235 }
12236 }
12237
12238 return false;
12239}
12240
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012241void
12242Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12243 ArrayRef<ParsedType> DynamicExceptions,
12244 ArrayRef<SourceRange> DynamicExceptionRanges,
12245 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012246 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012247 FunctionProtoType::ExtProtoInfo &EPI) {
12248 Exceptions.clear();
12249 EPI.ExceptionSpecType = EST;
12250 if (EST == EST_Dynamic) {
12251 Exceptions.reserve(DynamicExceptions.size());
12252 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12253 // FIXME: Preserve type source info.
12254 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12255
12256 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12257 collectUnexpandedParameterPacks(ET, Unexpanded);
12258 if (!Unexpanded.empty()) {
12259 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12260 UPPC_ExceptionType,
12261 Unexpanded);
12262 continue;
12263 }
12264
12265 // Check that the type is valid for an exception spec, and
12266 // drop it if not.
12267 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12268 Exceptions.push_back(ET);
12269 }
12270 EPI.NumExceptions = Exceptions.size();
12271 EPI.Exceptions = Exceptions.data();
12272 return;
12273 }
12274
12275 if (EST == EST_ComputedNoexcept) {
12276 // If an error occurred, there's no expression here.
12277 if (NoexceptExpr) {
12278 assert((NoexceptExpr->isTypeDependent() ||
12279 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12280 Context.BoolTy) &&
12281 "Parser should have made sure that the expression is boolean");
12282 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12283 EPI.ExceptionSpecType = EST_BasicNoexcept;
12284 return;
12285 }
12286
12287 if (!NoexceptExpr->isValueDependent())
12288 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012289 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012290 /*AllowFold*/ false).take();
12291 EPI.NoexceptExpr = NoexceptExpr;
12292 }
12293 return;
12294 }
12295}
12296
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012297/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12298Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12299 // Implicitly declared functions (e.g. copy constructors) are
12300 // __host__ __device__
12301 if (D->isImplicit())
12302 return CFT_HostDevice;
12303
12304 if (D->hasAttr<CUDAGlobalAttr>())
12305 return CFT_Global;
12306
12307 if (D->hasAttr<CUDADeviceAttr>()) {
12308 if (D->hasAttr<CUDAHostAttr>())
12309 return CFT_HostDevice;
12310 else
12311 return CFT_Device;
12312 }
12313
12314 return CFT_Host;
12315}
12316
12317bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12318 CUDAFunctionTarget CalleeTarget) {
12319 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12320 // Callable from the device only."
12321 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12322 return true;
12323
12324 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12325 // Callable from the host only."
12326 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12327 // Callable from the host only."
12328 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12329 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12330 return true;
12331
12332 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12333 return true;
12334
12335 return false;
12336}
John McCall76da55d2013-04-16 07:28:30 +000012337
12338/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12339///
12340MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12341 SourceLocation DeclStart,
12342 Declarator &D, Expr *BitWidth,
12343 InClassInitStyle InitStyle,
12344 AccessSpecifier AS,
12345 AttributeList *MSPropertyAttr) {
12346 IdentifierInfo *II = D.getIdentifier();
12347 if (!II) {
12348 Diag(DeclStart, diag::err_anonymous_property);
12349 return NULL;
12350 }
12351 SourceLocation Loc = D.getIdentifierLoc();
12352
12353 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12354 QualType T = TInfo->getType();
12355 if (getLangOpts().CPlusPlus) {
12356 CheckExtraCXXDefaultArguments(D);
12357
12358 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12359 UPPC_DataMemberType)) {
12360 D.setInvalidType();
12361 T = Context.IntTy;
12362 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12363 }
12364 }
12365
12366 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12367
12368 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12369 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12370 diag::err_invalid_thread)
12371 << DeclSpec::getSpecifierName(TSCS);
12372
12373 // Check to see if this name was declared as a member previously
12374 NamedDecl *PrevDecl = 0;
12375 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12376 LookupName(Previous, S);
12377 switch (Previous.getResultKind()) {
12378 case LookupResult::Found:
12379 case LookupResult::FoundUnresolvedValue:
12380 PrevDecl = Previous.getAsSingle<NamedDecl>();
12381 break;
12382
12383 case LookupResult::FoundOverloaded:
12384 PrevDecl = Previous.getRepresentativeDecl();
12385 break;
12386
12387 case LookupResult::NotFound:
12388 case LookupResult::NotFoundInCurrentInstantiation:
12389 case LookupResult::Ambiguous:
12390 break;
12391 }
12392
12393 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12394 // Maybe we will complain about the shadowed template parameter.
12395 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12396 // Just pretend that we didn't see the previous declaration.
12397 PrevDecl = 0;
12398 }
12399
12400 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12401 PrevDecl = 0;
12402
12403 SourceLocation TSSL = D.getLocStart();
12404 MSPropertyDecl *NewPD;
12405 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12406 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12407 II, T, TInfo, TSSL,
12408 Data.GetterId, Data.SetterId);
12409 ProcessDeclAttributes(TUScope, NewPD, D);
12410 NewPD->setAccess(AS);
12411
12412 if (NewPD->isInvalidDecl())
12413 Record->setInvalidDecl();
12414
12415 if (D.getDeclSpec().isModulePrivateSpecified())
12416 NewPD->setModulePrivate();
12417
12418 if (NewPD->isInvalidDecl() && PrevDecl) {
12419 // Don't introduce NewFD into scope; there's already something
12420 // with the same name in the same scope.
12421 } else if (II) {
12422 PushOnScopeChains(NewPD, S);
12423 } else
12424 Record->addDecl(NewPD);
12425
12426 return NewPD;
12427}