blob: a318f64765f4456ab9d63be788812c7dc0833b6a [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000040#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000041#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000042
43using namespace clang;
44
Chris Lattner8123a952008-04-10 02:22:51 +000045//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
Chris Lattner9e979552008-04-12 23:52:44 +000049namespace {
50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51 /// the default argument of a parameter to determine whether it
52 /// contains any ill-formed subexpressions. For example, this will
53 /// diagnose the use of local variables or parameters within the
54 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000055 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000056 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000057 Expr *DefaultArg;
58 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 public:
Mike Stump1eb44332009-09-09 15:08:12 +000061 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000062 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000063
Chris Lattner9e979552008-04-12 23:52:44 +000064 bool VisitExpr(Expr *Node);
65 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000066 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000067 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000068 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000069 };
Chris Lattner8123a952008-04-10 02:22:51 +000070
Chris Lattner9e979552008-04-12 23:52:44 +000071 /// VisitExpr - Visit all of the children of this expression.
72 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
73 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000074 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000075 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000076 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000077 }
78
Chris Lattner9e979552008-04-12 23:52:44 +000079 /// VisitDeclRefExpr - Visit a reference to a declaration, to
80 /// determine whether this declaration can be used in the default
81 /// argument expression.
82 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000083 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000084 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
85 // C++ [dcl.fct.default]p9
86 // Default arguments are evaluated each time the function is
87 // called. The order of evaluation of function arguments is
88 // unspecified. Consequently, parameters of a function shall not
89 // be used in default argument expressions, even if they are not
90 // evaluated. Parameters of a function declared before a default
91 // argument expression are in scope and can hide namespace and
92 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000093 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000094 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000095 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000096 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000097 // C++ [dcl.fct.default]p7
98 // Local variables shall not be used in default argument
99 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000100 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000101 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000102 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000103 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000104 }
Chris Lattner8123a952008-04-10 02:22:51 +0000105
Douglas Gregor3996f232008-11-04 13:41:56 +0000106 return false;
107 }
Chris Lattner9e979552008-04-12 23:52:44 +0000108
Douglas Gregor796da182008-11-04 14:32:21 +0000109 /// VisitCXXThisExpr - Visit a C++ "this" expression.
110 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
111 // C++ [dcl.fct.default]p8:
112 // The keyword this shall not be used in a default argument of a
113 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000114 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000115 diag::err_param_default_argument_references_this)
116 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000117 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000118
John McCall045d2522013-04-09 01:56:28 +0000119 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
120 bool Invalid = false;
121 for (PseudoObjectExpr::semantics_iterator
122 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
123 Expr *E = *i;
124
125 // Look through bindings.
126 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
127 E = OVE->getSourceExpr();
128 assert(E && "pseudo-object binding without source expression?");
129 }
130
131 Invalid |= Visit(E);
132 }
133 return Invalid;
134 }
135
Douglas Gregorf0459f82012-02-10 23:30:22 +0000136 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
137 // C++11 [expr.lambda.prim]p13:
138 // A lambda-expression appearing in a default argument shall not
139 // implicitly or explicitly capture any entity.
140 if (Lambda->capture_begin() == Lambda->capture_end())
141 return false;
142
143 return S->Diag(Lambda->getLocStart(),
144 diag::err_lambda_capture_default_arg);
145 }
Chris Lattner8123a952008-04-10 02:22:51 +0000146}
147
Richard Smith0b0ca472013-04-10 06:11:48 +0000148void
149Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
150 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000151 // If we have an MSAny spec already, don't bother.
152 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000153 return;
154
155 const FunctionProtoType *Proto
156 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000157 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
158 if (!Proto)
159 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000160
161 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
162
163 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000164 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000165 ClearExceptions();
166 ComputedEST = EST;
167 return;
168 }
169
Richard Smith7a614d82011-06-11 17:19:42 +0000170 // FIXME: If the call to this decl is using any of its default arguments, we
171 // need to search them for potentially-throwing calls.
172
Sean Hunt001cad92011-05-10 00:49:42 +0000173 // If this function has a basic noexcept, it doesn't affect the outcome.
174 if (EST == EST_BasicNoexcept)
175 return;
176
177 // If we have a throw-all spec at this point, ignore the function.
178 if (ComputedEST == EST_None)
179 return;
180
181 // If we're still at noexcept(true) and there's a nothrow() callee,
182 // change to that specification.
183 if (EST == EST_DynamicNone) {
184 if (ComputedEST == EST_BasicNoexcept)
185 ComputedEST = EST_DynamicNone;
186 return;
187 }
188
189 // Check out noexcept specs.
190 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000191 FunctionProtoType::NoexceptResult NR =
192 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000193 assert(NR != FunctionProtoType::NR_NoNoexcept &&
194 "Must have noexcept result for EST_ComputedNoexcept.");
195 assert(NR != FunctionProtoType::NR_Dependent &&
196 "Should not generate implicit declarations for dependent cases, "
197 "and don't know how to handle them anyway.");
198
199 // noexcept(false) -> no spec on the new function
200 if (NR == FunctionProtoType::NR_Throw) {
201 ClearExceptions();
202 ComputedEST = EST_None;
203 }
204 // noexcept(true) won't change anything either.
205 return;
206 }
207
208 assert(EST == EST_Dynamic && "EST case not considered earlier.");
209 assert(ComputedEST != EST_None &&
210 "Shouldn't collect exceptions when throw-all is guaranteed.");
211 ComputedEST = EST_Dynamic;
212 // Record the exceptions in this function's exception specification.
213 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
214 EEnd = Proto->exception_end();
215 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000217 Exceptions.push_back(*E);
218}
219
Richard Smith7a614d82011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithe6975e92012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssoned961f92009-08-25 02:29:20 +0000249bool
John McCall9ae2f072010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000271 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000273
Richard Smith6c3af3d2013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Anders Carlssoned961f92009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson9351c172009-08-25 03:18:48 +0000292 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000293}
294
Chris Lattner8123a952008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000298void
John McCalld226f652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000302 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCalld226f652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner3d1cee32008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6f526752010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlsson66e30672009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
John McCall9ae2f072010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000329}
330
Douglas Gregor61366e92008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCalld226f652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param)
343 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Anders Carlsson5e300d12009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000346}
347
Douglas Gregor72b505b2008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
John McCalld226f652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Anders Carlsson5e300d12009-06-12 16:51:40 +0000356 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Anders Carlsson5e300d12009-06-12 16:51:40 +0000358 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000359}
360
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000361/// CheckExtraCXXDefaultArguments - Check for any extra default
362/// arguments in the declarator, which is not a function declaration
363/// or definition and therefore is not permitted to have default
364/// arguments. This routine should be invoked for every declarator
365/// that is not a function declaration or definition.
366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367 // C++ [dcl.fct.default]p3
368 // A default argument expression shall be specified only in the
369 // parameter-declaration-clause of a function declaration or in a
370 // template-parameter (14.1). It shall not be specified for a
371 // parameter pack. If it is specified in a
372 // parameter-declaration-clause, it shall not occur within a
373 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000374 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000376 DeclaratorChunk &chunk = D.getTypeObject(i);
377 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000378 if (MightBeFunction) {
379 // This is a function declaration. It can have default arguments, but
380 // keep looking in case its return type is a function type with default
381 // arguments.
382 MightBeFunction = false;
383 continue;
384 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000385 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
386 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000387 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000388 if (Param->hasUnparsedDefaultArg()) {
389 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000391 << SourceRange((*Toks)[1].getLocation(),
392 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000393 delete Toks;
394 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000395 } else if (Param->getDefaultArg()) {
396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397 << Param->getDefaultArg()->getSourceRange();
398 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000399 }
400 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000401 } else if (chunk.Kind != DeclaratorChunk::Paren) {
402 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000403 }
404 }
405}
406
Craig Topper1a6eac82012-09-21 04:33:26 +0000407/// MergeCXXFunctionDecl - Merge two declarations of the same C++
408/// function, once we already know that they have the same
409/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
410/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000411bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
412 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000413 bool Invalid = false;
414
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000416 // For non-template functions, default arguments can be added in
417 // later declarations of a function in the same
418 // scope. Declarations in different scopes have completely
419 // distinct sets of default arguments. That is, declarations in
420 // inner scopes do not acquire default arguments from
421 // declarations in outer scopes, and vice versa. In a given
422 // function declaration, all parameters subsequent to a
423 // parameter with a default argument shall have default
424 // arguments supplied in this or previous declarations. A
425 // default argument shall not be redefined by a later
426 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000427 //
428 // C++ [dcl.fct.default]p6:
429 // Except for member functions of class templates, the default arguments
430 // in a member function definition that appears outside of the class
431 // definition are added to the set of default arguments provided by the
432 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000433 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
434 ParmVarDecl *OldParam = Old->getParamDecl(p);
435 ParmVarDecl *NewParam = New->getParamDecl(p);
436
James Molloy9cda03f2012-03-13 08:55:35 +0000437 bool OldParamHasDfl = OldParam->hasDefaultArg();
438 bool NewParamHasDfl = NewParam->hasDefaultArg();
439
440 NamedDecl *ND = Old;
441 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
442 // Ignore default parameters of old decl if they are not in
443 // the same scope.
444 OldParamHasDfl = false;
445
446 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000447
Francois Pichet8d051e02011-04-10 03:03:52 +0000448 unsigned DiagDefaultParamID =
449 diag::err_param_default_argument_redefinition;
450
451 // MSVC accepts that default parameters be redefined for member functions
452 // of template class. The new default parameter's value is ignored.
453 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000454 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000455 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
456 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000457 // Merge the old default argument into the new parameter.
458 NewParam->setHasInheritedDefaultArg();
459 if (OldParam->hasUninstantiatedDefaultArg())
460 NewParam->setUninstantiatedDefaultArg(
461 OldParam->getUninstantiatedDefaultArg());
462 else
463 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000464 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000465 Invalid = false;
466 }
467 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000468
Francois Pichet8cf90492011-04-10 04:58:30 +0000469 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
470 // hint here. Alternatively, we could walk the type-source information
471 // for NewParam to find the last source location in the type... but it
472 // isn't worth the effort right now. This is the kind of test case that
473 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000474 // int f(int);
475 // void g(int (*fp)(int) = f);
476 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000477 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000478 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000479
480 // Look for the function declaration where the default argument was
481 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000482 for (FunctionDecl *Older = Old->getPreviousDecl();
483 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000484 if (!Older->getParamDecl(p)->hasDefaultArg())
485 break;
486
487 OldParam = Older->getParamDecl(p);
488 }
489
490 Diag(OldParam->getLocation(), diag::note_previous_definition)
491 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000492 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000493 // Merge the old default argument into the new parameter.
494 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000495 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000496 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000497 if (OldParam->hasUninstantiatedDefaultArg())
498 NewParam->setUninstantiatedDefaultArg(
499 OldParam->getUninstantiatedDefaultArg());
500 else
John McCall3d6c1782010-05-04 01:53:42 +0000501 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000502 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000503 if (New->getDescribedFunctionTemplate()) {
504 // Paragraph 4, quoted above, only applies to non-template functions.
505 Diag(NewParam->getLocation(),
506 diag::err_param_default_argument_template_redecl)
507 << NewParam->getDefaultArgRange();
508 Diag(Old->getLocation(), diag::note_template_prev_declaration)
509 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000510 } else if (New->getTemplateSpecializationKind()
511 != TSK_ImplicitInstantiation &&
512 New->getTemplateSpecializationKind() != TSK_Undeclared) {
513 // C++ [temp.expr.spec]p21:
514 // Default function arguments shall not be specified in a declaration
515 // or a definition for one of the following explicit specializations:
516 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000517 // - the explicit specialization of a member function template;
518 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000519 // template where the class template specialization to which the
520 // member function specialization belongs is implicitly
521 // instantiated.
522 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
523 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
524 << New->getDeclName()
525 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000526 } else if (New->getDeclContext()->isDependentContext()) {
527 // C++ [dcl.fct.default]p6 (DR217):
528 // Default arguments for a member function of a class template shall
529 // be specified on the initial declaration of the member function
530 // within the class template.
531 //
532 // Reading the tea leaves a bit in DR217 and its reference to DR205
533 // leads me to the conclusion that one cannot add default function
534 // arguments for an out-of-line definition of a member function of a
535 // dependent type.
536 int WhichKind = 2;
537 if (CXXRecordDecl *Record
538 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
539 if (Record->getDescribedClassTemplate())
540 WhichKind = 0;
541 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
542 WhichKind = 1;
543 else
544 WhichKind = 2;
545 }
546
547 Diag(NewParam->getLocation(),
548 diag::err_param_default_argument_member_template_redecl)
549 << WhichKind
550 << NewParam->getDefaultArgRange();
551 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000552 }
553 }
554
Richard Smithb8abff62012-11-28 03:45:24 +0000555 // DR1344: If a default argument is added outside a class definition and that
556 // default argument makes the function a special member function, the program
557 // is ill-formed. This can only happen for constructors.
558 if (isa<CXXConstructorDecl>(New) &&
559 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
560 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
561 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
562 if (NewSM != OldSM) {
563 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
564 assert(NewParam->hasDefaultArg());
565 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
566 << NewParam->getDefaultArgRange() << NewSM;
567 Diag(Old->getLocation(), diag::note_previous_declaration);
568 }
569 }
570
Richard Smithff234882012-02-20 23:28:05 +0000571 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000572 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000573 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000574 if (New->isConstexpr() != Old->isConstexpr()) {
575 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
576 << New << New->isConstexpr();
577 Diag(Old->getLocation(), diag::note_previous_declaration);
578 Invalid = true;
579 }
580
Douglas Gregore13ad832010-02-12 07:32:17 +0000581 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000582 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000583
Douglas Gregorcda9c672009-02-16 17:45:42 +0000584 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000585}
586
Sebastian Redl60618fa2011-03-12 11:50:43 +0000587/// \brief Merge the exception specifications of two variable declarations.
588///
589/// This is called when there's a redeclaration of a VarDecl. The function
590/// checks if the redeclaration might have an exception specification and
591/// validates compatibility and merges the specs if necessary.
592void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
593 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000594 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000595 return;
596
597 assert(Context.hasSameType(New->getType(), Old->getType()) &&
598 "Should only be called if types are otherwise the same.");
599
600 QualType NewType = New->getType();
601 QualType OldType = Old->getType();
602
603 // We're only interested in pointers and references to functions, as well
604 // as pointers to member functions.
605 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
606 NewType = R->getPointeeType();
607 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
608 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
609 NewType = P->getPointeeType();
610 OldType = OldType->getAs<PointerType>()->getPointeeType();
611 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
612 NewType = M->getPointeeType();
613 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
614 }
615
616 if (!NewType->isFunctionProtoType())
617 return;
618
619 // There's lots of special cases for functions. For function pointers, system
620 // libraries are hopefully not as broken so that we don't need these
621 // workarounds.
622 if (CheckEquivalentExceptionSpec(
623 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
624 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
625 New->setInvalidDecl();
626 }
627}
628
Chris Lattner3d1cee32008-04-08 05:04:30 +0000629/// CheckCXXDefaultArguments - Verify that the default arguments for a
630/// function declaration are well-formed according to C++
631/// [dcl.fct.default].
632void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
633 unsigned NumParams = FD->getNumParams();
634 unsigned p;
635
Douglas Gregorc6889e72012-02-14 22:28:59 +0000636 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
637 isa<CXXMethodDecl>(FD) &&
638 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
639
Chris Lattner3d1cee32008-04-08 05:04:30 +0000640 // Find first parameter with a default argument
641 for (p = 0; p < NumParams; ++p) {
642 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000643 if (Param->hasDefaultArg()) {
644 // C++11 [expr.prim.lambda]p5:
645 // [...] Default arguments (8.3.6) shall not be specified in the
646 // parameter-declaration-clause of a lambda-declarator.
647 //
648 // FIXME: Core issue 974 strikes this sentence, we only provide an
649 // extension warning.
650 if (IsLambda)
651 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
652 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000653 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000654 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000655 }
656
657 // C++ [dcl.fct.default]p4:
658 // In a given function declaration, all parameters
659 // subsequent to a parameter with a default argument shall
660 // have default arguments supplied in this or previous
661 // declarations. A default argument shall not be redefined
662 // by a later declaration (not even to the same value).
663 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000664 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000665 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000666 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000667 if (Param->isInvalidDecl())
668 /* We already complained about this parameter. */;
669 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000670 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000671 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000672 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000673 else
Mike Stump1eb44332009-09-09 15:08:12 +0000674 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000675 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000676
Chris Lattner3d1cee32008-04-08 05:04:30 +0000677 LastMissingDefaultArg = p;
678 }
679 }
680
681 if (LastMissingDefaultArg > 0) {
682 // Some default arguments were missing. Clear out all of the
683 // default arguments up to (and including) the last missing
684 // default argument, so that we leave the function parameters
685 // in a semantically valid state.
686 for (p = 0; p <= LastMissingDefaultArg; ++p) {
687 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000688 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000689 Param->setDefaultArg(0);
690 }
691 }
692 }
693}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000694
Richard Smith9f569cc2011-10-01 02:31:28 +0000695// CheckConstexprParameterTypes - Check whether a function's parameter types
696// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000697// diagnostic and return false.
698static bool CheckConstexprParameterTypes(Sema &SemaRef,
699 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000700 unsigned ArgIndex = 0;
701 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
702 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
703 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
704 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
705 SourceLocation ParamLoc = PD->getLocation();
706 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000707 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000708 diag::err_constexpr_non_literal_param,
709 ArgIndex+1, PD->getSourceRange(),
710 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000711 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000712 }
Joao Matos17d35c32012-08-31 22:18:20 +0000713 return true;
714}
715
716/// \brief Get diagnostic %select index for tag kind for
717/// record diagnostic message.
718/// WARNING: Indexes apply to particular diagnostics only!
719///
720/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000721static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000722 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000723 case TTK_Struct: return 0;
724 case TTK_Interface: return 1;
725 case TTK_Class: return 2;
726 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000727 }
Joao Matos17d35c32012-08-31 22:18:20 +0000728}
729
730// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
731// the requirements of a constexpr function definition or a constexpr
732// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000733// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000734//
Richard Smith86c3ae42012-02-13 03:54:03 +0000735// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
736bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000737 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
738 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000739 // C++11 [dcl.constexpr]p4:
740 // The definition of a constexpr constructor shall satisfy the following
741 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000742 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000743 const CXXRecordDecl *RD = MD->getParent();
744 if (RD->getNumVBases()) {
745 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
746 << isa<CXXConstructorDecl>(NewFD)
747 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
748 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
749 E = RD->vbases_end(); I != E; ++I)
750 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000751 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000752 return false;
753 }
Richard Smith35340502012-01-13 04:54:00 +0000754 }
755
756 if (!isa<CXXConstructorDecl>(NewFD)) {
757 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000758 // The definition of a constexpr function shall satisfy the following
759 // constraints:
760 // - it shall not be virtual;
761 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
762 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000763 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000764
Richard Smith86c3ae42012-02-13 03:54:03 +0000765 // If it's not obvious why this function is virtual, find an overridden
766 // function which uses the 'virtual' keyword.
767 const CXXMethodDecl *WrittenVirtual = Method;
768 while (!WrittenVirtual->isVirtualAsWritten())
769 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
770 if (WrittenVirtual != Method)
771 Diag(WrittenVirtual->getLocation(),
772 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000773 return false;
774 }
775
776 // - its return type shall be a literal type;
777 QualType RT = NewFD->getResultType();
778 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000779 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000780 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000781 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000782 }
783
Richard Smith35340502012-01-13 04:54:00 +0000784 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000785 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000786 return false;
787
Richard Smith9f569cc2011-10-01 02:31:28 +0000788 return true;
789}
790
791/// Check the given declaration statement is legal within a constexpr function
792/// body. C++0x [dcl.constexpr]p3,p4.
793///
794/// \return true if the body is OK, false if we have diagnosed a problem.
795static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
796 DeclStmt *DS) {
797 // C++0x [dcl.constexpr]p3 and p4:
798 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
799 // contain only
800 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
801 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
802 switch ((*DclIt)->getKind()) {
803 case Decl::StaticAssert:
804 case Decl::Using:
805 case Decl::UsingShadow:
806 case Decl::UsingDirective:
807 case Decl::UnresolvedUsingTypename:
808 // - static_assert-declarations
809 // - using-declarations,
810 // - using-directives,
811 continue;
812
813 case Decl::Typedef:
814 case Decl::TypeAlias: {
815 // - typedef declarations and alias-declarations that do not define
816 // classes or enumerations,
817 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
818 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
819 // Don't allow variably-modified types in constexpr functions.
820 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
821 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
822 << TL.getSourceRange() << TL.getType()
823 << isa<CXXConstructorDecl>(Dcl);
824 return false;
825 }
826 continue;
827 }
828
829 case Decl::Enum:
830 case Decl::CXXRecord:
831 // As an extension, we allow the declaration (but not the definition) of
832 // classes and enumerations in all declarations, not just in typedef and
833 // alias declarations.
834 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
835 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
836 << isa<CXXConstructorDecl>(Dcl);
837 return false;
838 }
839 continue;
840
841 case Decl::Var:
842 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
843 << isa<CXXConstructorDecl>(Dcl);
844 return false;
845
846 default:
847 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
848 << isa<CXXConstructorDecl>(Dcl);
849 return false;
850 }
851 }
852
853 return true;
854}
855
856/// Check that the given field is initialized within a constexpr constructor.
857///
858/// \param Dcl The constexpr constructor being checked.
859/// \param Field The field being checked. This may be a member of an anonymous
860/// struct or union nested within the class being checked.
861/// \param Inits All declarations, including anonymous struct/union members and
862/// indirect members, for which any initialization was provided.
863/// \param Diagnosed Set to true if an error is produced.
864static void CheckConstexprCtorInitializer(Sema &SemaRef,
865 const FunctionDecl *Dcl,
866 FieldDecl *Field,
867 llvm::SmallSet<Decl*, 16> &Inits,
868 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000869 if (Field->isUnnamedBitfield())
870 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000871
872 if (Field->isAnonymousStructOrUnion() &&
873 Field->getType()->getAsCXXRecordDecl()->isEmpty())
874 return;
875
Richard Smith9f569cc2011-10-01 02:31:28 +0000876 if (!Inits.count(Field)) {
877 if (!Diagnosed) {
878 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
879 Diagnosed = true;
880 }
881 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
882 } else if (Field->isAnonymousStructOrUnion()) {
883 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
884 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
885 I != E; ++I)
886 // If an anonymous union contains an anonymous struct of which any member
887 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000888 if (!RD->isUnion() || Inits.count(*I))
889 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000890 }
891}
892
893/// Check the body for the given constexpr function declaration only contains
894/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
895///
896/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000897bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000898 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000899 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000900 // The definition of a constexpr function shall satisfy the following
901 // constraints: [...]
902 // - its function-body shall be = delete, = default, or a
903 // compound-statement
904 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000905 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000906 // In the definition of a constexpr constructor, [...]
907 // - its function-body shall not be a function-try-block;
908 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
909 << isa<CXXConstructorDecl>(Dcl);
910 return false;
911 }
912
913 // - its function-body shall be [...] a compound-statement that contains only
914 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
915
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000916 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smith9f569cc2011-10-01 02:31:28 +0000917 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
918 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
919 switch ((*BodyIt)->getStmtClass()) {
920 case Stmt::NullStmtClass:
921 // - null statements,
922 continue;
923
924 case Stmt::DeclStmtClass:
925 // - static_assert-declarations
926 // - using-declarations,
927 // - using-directives,
928 // - typedef declarations and alias-declarations that do not define
929 // classes or enumerations,
930 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
931 return false;
932 continue;
933
934 case Stmt::ReturnStmtClass:
935 // - and exactly one return statement;
936 if (isa<CXXConstructorDecl>(Dcl))
937 break;
938
939 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000940 continue;
941
942 default:
943 break;
944 }
945
946 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
947 << isa<CXXConstructorDecl>(Dcl);
948 return false;
949 }
950
951 if (const CXXConstructorDecl *Constructor
952 = dyn_cast<CXXConstructorDecl>(Dcl)) {
953 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000954 // DR1359:
955 // - every non-variant non-static data member and base class sub-object
956 // shall be initialized;
957 // - if the class is a non-empty union, or for each non-empty anonymous
958 // union member of a non-union class, exactly one non-static data member
959 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000960 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000961 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000962 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
963 return false;
964 }
Richard Smith6e433752011-10-10 16:38:04 +0000965 } else if (!Constructor->isDependentContext() &&
966 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000967 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
968
969 // Skip detailed checking if we have enough initializers, and we would
970 // allow at most one initializer per member.
971 bool AnyAnonStructUnionMembers = false;
972 unsigned Fields = 0;
973 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
974 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000975 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000976 AnyAnonStructUnionMembers = true;
977 break;
978 }
979 }
980 if (AnyAnonStructUnionMembers ||
981 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
982 // Check initialization of non-static data members. Base classes are
983 // always initialized so do not need to be checked. Dependent bases
984 // might not have initializers in the member initializer list.
985 llvm::SmallSet<Decl*, 16> Inits;
986 for (CXXConstructorDecl::init_const_iterator
987 I = Constructor->init_begin(), E = Constructor->init_end();
988 I != E; ++I) {
989 if (FieldDecl *FD = (*I)->getMember())
990 Inits.insert(FD);
991 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
992 Inits.insert(ID->chain_begin(), ID->chain_end());
993 }
994
995 bool Diagnosed = false;
996 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
997 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000998 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000999 if (Diagnosed)
1000 return false;
1001 }
1002 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001003 } else {
1004 if (ReturnStmts.empty()) {
1005 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
1006 return false;
1007 }
1008 if (ReturnStmts.size() > 1) {
1009 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
1010 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1011 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1012 return false;
1013 }
1014 }
1015
Richard Smith5ba73e12012-02-04 00:33:54 +00001016 // C++11 [dcl.constexpr]p5:
1017 // if no function argument values exist such that the function invocation
1018 // substitution would produce a constant expression, the program is
1019 // ill-formed; no diagnostic required.
1020 // C++11 [dcl.constexpr]p3:
1021 // - every constructor call and implicit conversion used in initializing the
1022 // return value shall be one of those allowed in a constant expression.
1023 // C++11 [dcl.constexpr]p4:
1024 // - every constructor involved in initializing non-static data members and
1025 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001026 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001027 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001028 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001029 << isa<CXXConstructorDecl>(Dcl);
1030 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1031 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001032 // Don't return false here: we allow this for compatibility in
1033 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001034 }
1035
Richard Smith9f569cc2011-10-01 02:31:28 +00001036 return true;
1037}
1038
Douglas Gregorb48fe382008-10-31 09:07:45 +00001039/// isCurrentClassName - Determine whether the identifier II is the
1040/// name of the class type currently being defined. In the case of
1041/// nested classes, this will only return true if II is the name of
1042/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001043bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1044 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001045 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001046
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001047 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001048 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001049 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001050 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1051 } else
1052 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1053
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001054 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001055 return &II == CurDecl->getIdentifier();
1056 else
1057 return false;
1058}
1059
Douglas Gregor229d47a2012-11-10 07:24:09 +00001060/// \brief Determine whether the given class is a base class of the given
1061/// class, including looking at dependent bases.
1062static bool findCircularInheritance(const CXXRecordDecl *Class,
1063 const CXXRecordDecl *Current) {
1064 SmallVector<const CXXRecordDecl*, 8> Queue;
1065
1066 Class = Class->getCanonicalDecl();
1067 while (true) {
1068 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1069 E = Current->bases_end();
1070 I != E; ++I) {
1071 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1072 if (!Base)
1073 continue;
1074
1075 Base = Base->getDefinition();
1076 if (!Base)
1077 continue;
1078
1079 if (Base->getCanonicalDecl() == Class)
1080 return true;
1081
1082 Queue.push_back(Base);
1083 }
1084
1085 if (Queue.empty())
1086 return false;
1087
1088 Current = Queue.back();
1089 Queue.pop_back();
1090 }
1091
1092 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001093}
1094
Mike Stump1eb44332009-09-09 15:08:12 +00001095/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001096///
1097/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1098/// and returns NULL otherwise.
1099CXXBaseSpecifier *
1100Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1101 SourceRange SpecifierRange,
1102 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001103 TypeSourceInfo *TInfo,
1104 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001105 QualType BaseType = TInfo->getType();
1106
Douglas Gregor2943aed2009-03-03 04:44:36 +00001107 // C++ [class.union]p1:
1108 // A union shall not have base classes.
1109 if (Class->isUnion()) {
1110 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1111 << SpecifierRange;
1112 return 0;
1113 }
1114
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001115 if (EllipsisLoc.isValid() &&
1116 !TInfo->getType()->containsUnexpandedParameterPack()) {
1117 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1118 << TInfo->getTypeLoc().getSourceRange();
1119 EllipsisLoc = SourceLocation();
1120 }
Douglas Gregord777e282012-11-10 01:18:17 +00001121
1122 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1123
1124 if (BaseType->isDependentType()) {
1125 // Make sure that we don't have circular inheritance among our dependent
1126 // bases. For non-dependent bases, the check for completeness below handles
1127 // this.
1128 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1129 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1130 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001131 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001132 Diag(BaseLoc, diag::err_circular_inheritance)
1133 << BaseType << Context.getTypeDeclType(Class);
1134
1135 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1136 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1137 << BaseType;
1138
1139 return 0;
1140 }
1141 }
1142
Mike Stump1eb44332009-09-09 15:08:12 +00001143 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001144 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001145 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001146 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001147
1148 // Base specifiers must be record types.
1149 if (!BaseType->isRecordType()) {
1150 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1151 return 0;
1152 }
1153
1154 // C++ [class.union]p1:
1155 // A union shall not be used as a base class.
1156 if (BaseType->isUnionType()) {
1157 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1158 return 0;
1159 }
1160
1161 // C++ [class.derived]p2:
1162 // The class-name in a base-specifier shall not be an incompletely
1163 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001164 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001165 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001166 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001167 return 0;
John McCall572fc622010-08-17 07:23:57 +00001168 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001169
Eli Friedman1d954f62009-08-15 21:55:26 +00001170 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001171 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001172 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001173 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001174 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001175 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1176 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001177
Anders Carlsson1d209272011-03-25 14:55:14 +00001178 // C++ [class]p3:
1179 // If a class is marked final and it appears as a base-type-specifier in
1180 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001181 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001182 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1183 << CXXBaseDecl->getDeclName();
1184 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1185 << CXXBaseDecl->getDeclName();
1186 return 0;
1187 }
1188
John McCall572fc622010-08-17 07:23:57 +00001189 if (BaseDecl->isInvalidDecl())
1190 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001191
1192 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001193 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001194 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001195 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001196}
1197
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001198/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1199/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001200/// example:
1201/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001202/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001203BaseResult
John McCalld226f652010-08-21 09:40:31 +00001204Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001205 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001206 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001207 ParsedType basetype, SourceLocation BaseLoc,
1208 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001209 if (!classdecl)
1210 return true;
1211
Douglas Gregor40808ce2009-03-09 23:48:35 +00001212 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001213 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001214 if (!Class)
1215 return true;
1216
Richard Smith05321402013-02-19 23:47:15 +00001217 // We do not support any C++11 attributes on base-specifiers yet.
1218 // Diagnose any attributes we see.
1219 if (!Attributes.empty()) {
1220 for (AttributeList *Attr = Attributes.getList(); Attr;
1221 Attr = Attr->getNext()) {
1222 if (Attr->isInvalid() ||
1223 Attr->getKind() == AttributeList::IgnoredAttribute)
1224 continue;
1225 Diag(Attr->getLoc(),
1226 Attr->getKind() == AttributeList::UnknownAttribute
1227 ? diag::warn_unknown_attribute_ignored
1228 : diag::err_base_specifier_attribute)
1229 << Attr->getName();
1230 }
1231 }
1232
Nick Lewycky56062202010-07-26 16:56:01 +00001233 TypeSourceInfo *TInfo = 0;
1234 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001235
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001236 if (EllipsisLoc.isInvalid() &&
1237 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001238 UPPC_BaseType))
1239 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001240
Douglas Gregor2943aed2009-03-03 04:44:36 +00001241 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001242 Virtual, Access, TInfo,
1243 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001244 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001245 else
1246 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Douglas Gregor2943aed2009-03-03 04:44:36 +00001248 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001249}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001250
Douglas Gregor2943aed2009-03-03 04:44:36 +00001251/// \brief Performs the actual work of attaching the given base class
1252/// specifiers to a C++ class.
1253bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1254 unsigned NumBases) {
1255 if (NumBases == 0)
1256 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001257
1258 // Used to keep track of which base types we have already seen, so
1259 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001260 // that the key is always the unqualified canonical type of the base
1261 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001262 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1263
1264 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001265 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001266 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001267 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001268 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001269 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001270 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001271
1272 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1273 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001274 // C++ [class.mi]p3:
1275 // A class shall not be specified as a direct base class of a
1276 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001277 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001278 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001279 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001280 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001281
1282 // Delete the duplicate base class specifier; we're going to
1283 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001284 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001285
1286 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001287 } else {
1288 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001289 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001290 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001291 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1292 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1293 if (Class->isInterface() &&
1294 (!RD->isInterface() ||
1295 KnownBase->getAccessSpecifier() != AS_public)) {
1296 // The Microsoft extension __interface does not permit bases that
1297 // are not themselves public interfaces.
1298 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1299 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1300 << RD->getSourceRange();
1301 Invalid = true;
1302 }
1303 if (RD->hasAttr<WeakAttr>())
1304 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1305 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001306 }
1307 }
1308
1309 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001310 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001311
1312 // Delete the remaining (good) base class specifiers, since their
1313 // data has been copied into the CXXRecordDecl.
1314 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001315 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001316
1317 return Invalid;
1318}
1319
1320/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1321/// class, after checking whether there are any duplicate base
1322/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001323void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001324 unsigned NumBases) {
1325 if (!ClassDecl || !Bases || !NumBases)
1326 return;
1327
1328 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001329 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001330 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001331}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001332
Douglas Gregora8f32e02009-10-06 17:59:45 +00001333/// \brief Determine whether the type \p Derived is a C++ class that is
1334/// derived from the type \p Base.
1335bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001336 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001337 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001338
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001339 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001340 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001341 return false;
1342
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001343 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001344 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001345 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001346
1347 // If either the base or the derived type is invalid, don't try to
1348 // check whether one is derived from the other.
1349 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1350 return false;
1351
John McCall86ff3082010-02-04 22:26:26 +00001352 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1353 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001354}
1355
1356/// \brief Determine whether the type \p Derived is a C++ class that is
1357/// derived from the type \p Base.
1358bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001359 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001360 return false;
1361
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001362 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001363 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001364 return false;
1365
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001366 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001367 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001368 return false;
1369
Douglas Gregora8f32e02009-10-06 17:59:45 +00001370 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1371}
1372
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001373void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001374 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001375 assert(BasePathArray.empty() && "Base path array must be empty!");
1376 assert(Paths.isRecordingPaths() && "Must record paths!");
1377
1378 const CXXBasePath &Path = Paths.front();
1379
1380 // We first go backward and check if we have a virtual base.
1381 // FIXME: It would be better if CXXBasePath had the base specifier for
1382 // the nearest virtual base.
1383 unsigned Start = 0;
1384 for (unsigned I = Path.size(); I != 0; --I) {
1385 if (Path[I - 1].Base->isVirtual()) {
1386 Start = I - 1;
1387 break;
1388 }
1389 }
1390
1391 // Now add all bases.
1392 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001393 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001394}
1395
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001396/// \brief Determine whether the given base path includes a virtual
1397/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001398bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1399 for (CXXCastPath::const_iterator B = BasePath.begin(),
1400 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001401 B != BEnd; ++B)
1402 if ((*B)->isVirtual())
1403 return true;
1404
1405 return false;
1406}
1407
Douglas Gregora8f32e02009-10-06 17:59:45 +00001408/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1409/// conversion (where Derived and Base are class types) is
1410/// well-formed, meaning that the conversion is unambiguous (and
1411/// that all of the base classes are accessible). Returns true
1412/// and emits a diagnostic if the code is ill-formed, returns false
1413/// otherwise. Loc is the location where this routine should point to
1414/// if there is an error, and Range is the source range to highlight
1415/// if there is an error.
1416bool
1417Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001418 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001419 unsigned AmbigiousBaseConvID,
1420 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001421 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001422 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001423 // First, determine whether the path from Derived to Base is
1424 // ambiguous. This is slightly more expensive than checking whether
1425 // the Derived to Base conversion exists, because here we need to
1426 // explore multiple paths to determine if there is an ambiguity.
1427 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1428 /*DetectVirtual=*/false);
1429 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1430 assert(DerivationOkay &&
1431 "Can only be used with a derived-to-base conversion");
1432 (void)DerivationOkay;
1433
1434 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001435 if (InaccessibleBaseID) {
1436 // Check that the base class can be accessed.
1437 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1438 InaccessibleBaseID)) {
1439 case AR_inaccessible:
1440 return true;
1441 case AR_accessible:
1442 case AR_dependent:
1443 case AR_delayed:
1444 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001445 }
John McCall6b2accb2010-02-10 09:31:12 +00001446 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001447
1448 // Build a base path if necessary.
1449 if (BasePath)
1450 BuildBasePathArray(Paths, *BasePath);
1451 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001452 }
1453
1454 // We know that the derived-to-base conversion is ambiguous, and
1455 // we're going to produce a diagnostic. Perform the derived-to-base
1456 // search just one more time to compute all of the possible paths so
1457 // that we can print them out. This is more expensive than any of
1458 // the previous derived-to-base checks we've done, but at this point
1459 // performance isn't as much of an issue.
1460 Paths.clear();
1461 Paths.setRecordingPaths(true);
1462 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1463 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1464 (void)StillOkay;
1465
1466 // Build up a textual representation of the ambiguous paths, e.g.,
1467 // D -> B -> A, that will be used to illustrate the ambiguous
1468 // conversions in the diagnostic. We only print one of the paths
1469 // to each base class subobject.
1470 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1471
1472 Diag(Loc, AmbigiousBaseConvID)
1473 << Derived << Base << PathDisplayStr << Range << Name;
1474 return true;
1475}
1476
1477bool
1478Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001479 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001480 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001481 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001482 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001483 IgnoreAccess ? 0
1484 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001485 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001486 Loc, Range, DeclarationName(),
1487 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001488}
1489
1490
1491/// @brief Builds a string representing ambiguous paths from a
1492/// specific derived class to different subobjects of the same base
1493/// class.
1494///
1495/// This function builds a string that can be used in error messages
1496/// to show the different paths that one can take through the
1497/// inheritance hierarchy to go from the derived class to different
1498/// subobjects of a base class. The result looks something like this:
1499/// @code
1500/// struct D -> struct B -> struct A
1501/// struct D -> struct C -> struct A
1502/// @endcode
1503std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1504 std::string PathDisplayStr;
1505 std::set<unsigned> DisplayedPaths;
1506 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1507 Path != Paths.end(); ++Path) {
1508 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1509 // We haven't displayed a path to this particular base
1510 // class subobject yet.
1511 PathDisplayStr += "\n ";
1512 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1513 for (CXXBasePath::const_iterator Element = Path->begin();
1514 Element != Path->end(); ++Element)
1515 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1516 }
1517 }
1518
1519 return PathDisplayStr;
1520}
1521
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001522//===----------------------------------------------------------------------===//
1523// C++ class member Handling
1524//===----------------------------------------------------------------------===//
1525
Abramo Bagnara6206d532010-06-05 05:09:32 +00001526/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001527bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1528 SourceLocation ASLoc,
1529 SourceLocation ColonLoc,
1530 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001531 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001532 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001533 ASLoc, ColonLoc);
1534 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001535 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001536}
1537
Richard Smitha4b39652012-08-06 03:25:17 +00001538/// CheckOverrideControl - Check C++11 override control semantics.
1539void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001540 if (D->isInvalidDecl())
1541 return;
1542
Chris Lattner5f9e2722011-07-23 10:55:15 +00001543 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001544
Richard Smitha4b39652012-08-06 03:25:17 +00001545 // Do we know which functions this declaration might be overriding?
1546 bool OverridesAreKnown = !MD ||
1547 (!MD->getParent()->hasAnyDependentBases() &&
1548 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001549
Richard Smitha4b39652012-08-06 03:25:17 +00001550 if (!MD || !MD->isVirtual()) {
1551 if (OverridesAreKnown) {
1552 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1553 Diag(OA->getLocation(),
1554 diag::override_keyword_only_allowed_on_virtual_member_functions)
1555 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1556 D->dropAttr<OverrideAttr>();
1557 }
1558 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1559 Diag(FA->getLocation(),
1560 diag::override_keyword_only_allowed_on_virtual_member_functions)
1561 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1562 D->dropAttr<FinalAttr>();
1563 }
1564 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001565 return;
1566 }
Richard Smitha4b39652012-08-06 03:25:17 +00001567
1568 if (!OverridesAreKnown)
1569 return;
1570
1571 // C++11 [class.virtual]p5:
1572 // If a virtual function is marked with the virt-specifier override and
1573 // does not override a member function of a base class, the program is
1574 // ill-formed.
1575 bool HasOverriddenMethods =
1576 MD->begin_overridden_methods() != MD->end_overridden_methods();
1577 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1578 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1579 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001580}
1581
Richard Smitha4b39652012-08-06 03:25:17 +00001582/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001583/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001584/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001585bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1586 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001587 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001588 return false;
1589
1590 Diag(New->getLocation(), diag::err_final_function_overridden)
1591 << New->getDeclName();
1592 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1593 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001594}
1595
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001596static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001597 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1598 // FIXME: Destruction of ObjC lifetime types has side-effects.
1599 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1600 return !RD->isCompleteDefinition() ||
1601 !RD->hasTrivialDefaultConstructor() ||
1602 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001603 return false;
1604}
1605
John McCall76da55d2013-04-16 07:28:30 +00001606static AttributeList *getMSPropertyAttr(AttributeList *list) {
1607 for (AttributeList* it = list; it != 0; it = it->getNext())
1608 if (it->isDeclspecPropertyAttribute())
1609 return it;
1610 return 0;
1611}
1612
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001613/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1614/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001615/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001616/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1617/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001618NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001619Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001620 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001621 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001622 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001623 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001624 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1625 DeclarationName Name = NameInfo.getName();
1626 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001627
1628 // For anonymous bitfields, the location should point to the type.
1629 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001630 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001631
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001632 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001633
John McCall4bde1e12010-06-04 08:34:12 +00001634 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001635 assert(!DS.isFriendSpecified());
1636
Richard Smith1ab0d902011-06-25 02:28:38 +00001637 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001638
John McCalle402e722012-09-25 07:32:39 +00001639 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1640 // The Microsoft extension __interface only permits public member functions
1641 // and prohibits constructors, destructors, operators, non-public member
1642 // functions, static methods and data members.
1643 unsigned InvalidDecl;
1644 bool ShowDeclName = true;
1645 if (!isFunc)
1646 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1647 else if (AS != AS_public)
1648 InvalidDecl = 2;
1649 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1650 InvalidDecl = 3;
1651 else switch (Name.getNameKind()) {
1652 case DeclarationName::CXXConstructorName:
1653 InvalidDecl = 4;
1654 ShowDeclName = false;
1655 break;
1656
1657 case DeclarationName::CXXDestructorName:
1658 InvalidDecl = 5;
1659 ShowDeclName = false;
1660 break;
1661
1662 case DeclarationName::CXXOperatorName:
1663 case DeclarationName::CXXConversionFunctionName:
1664 InvalidDecl = 6;
1665 break;
1666
1667 default:
1668 InvalidDecl = 0;
1669 break;
1670 }
1671
1672 if (InvalidDecl) {
1673 if (ShowDeclName)
1674 Diag(Loc, diag::err_invalid_member_in_interface)
1675 << (InvalidDecl-1) << Name;
1676 else
1677 Diag(Loc, diag::err_invalid_member_in_interface)
1678 << (InvalidDecl-1) << "";
1679 return 0;
1680 }
1681 }
1682
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001683 // C++ 9.2p6: A member shall not be declared to have automatic storage
1684 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001685 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1686 // data members and cannot be applied to names declared const or static,
1687 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001688 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001689 case DeclSpec::SCS_unspecified:
1690 case DeclSpec::SCS_typedef:
1691 case DeclSpec::SCS_static:
1692 break;
1693 case DeclSpec::SCS_mutable:
1694 if (isFunc) {
1695 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Richard Smithec642442013-04-12 22:46:28 +00001697 // FIXME: It would be nicer if the keyword was ignored only for this
1698 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001699 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001700 }
1701 break;
1702 default:
1703 Diag(DS.getStorageClassSpecLoc(),
1704 diag::err_storageclass_invalid_for_member);
1705 D.getMutableDeclSpec().ClearStorageClassSpecs();
1706 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001707 }
1708
Sebastian Redl669d5d72008-11-14 23:42:31 +00001709 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1710 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001711 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001712
David Blaikie1d87fba2013-01-30 01:22:18 +00001713 if (DS.isConstexprSpecified() && isInstField) {
1714 SemaDiagnosticBuilder B =
1715 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1716 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1717 if (InitStyle == ICIS_NoInit) {
1718 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1719 D.getMutableDeclSpec().ClearConstexprSpec();
1720 const char *PrevSpec;
1721 unsigned DiagID;
1722 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1723 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001724 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001725 assert(!Failed && "Making a constexpr member const shouldn't fail");
1726 } else {
1727 B << 1;
1728 const char *PrevSpec;
1729 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001730 if (D.getMutableDeclSpec().SetStorageClassSpec(
1731 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001732 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001733 "This is the only DeclSpec that should fail to be applied");
1734 B << 1;
1735 } else {
1736 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1737 isInstField = false;
1738 }
1739 }
1740 }
1741
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001742 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001743 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001744 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001745
1746 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001747 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001748 Diag(Loc, diag::err_bad_variable_name)
1749 << Name;
1750 return 0;
1751 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001752
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001753 IdentifierInfo *II = Name.getAsIdentifierInfo();
1754
Douglas Gregorf2503652011-09-21 14:40:46 +00001755 // Member field could not be with "template" keyword.
1756 // So TemplateParameterLists should be empty in this case.
1757 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001758 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001759 if (TemplateParams->size()) {
1760 // There is no such thing as a member field template.
1761 Diag(D.getIdentifierLoc(), diag::err_template_member)
1762 << II
1763 << SourceRange(TemplateParams->getTemplateLoc(),
1764 TemplateParams->getRAngleLoc());
1765 } else {
1766 // There is an extraneous 'template<>' for this member.
1767 Diag(TemplateParams->getTemplateLoc(),
1768 diag::err_template_member_noparams)
1769 << II
1770 << SourceRange(TemplateParams->getTemplateLoc(),
1771 TemplateParams->getRAngleLoc());
1772 }
1773 return 0;
1774 }
1775
Douglas Gregor922fff22010-10-13 22:19:53 +00001776 if (SS.isSet() && !SS.isInvalid()) {
1777 // The user provided a superfluous scope specifier inside a class
1778 // definition:
1779 //
1780 // class X {
1781 // int X::member;
1782 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001783 if (DeclContext *DC = computeDeclContext(SS, false))
1784 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001785 else
1786 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1787 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001788
Douglas Gregor922fff22010-10-13 22:19:53 +00001789 SS.clear();
1790 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001791
John McCall76da55d2013-04-16 07:28:30 +00001792 AttributeList *MSPropertyAttr =
1793 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1794 if (MSPropertyAttr) {
1795 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1796 BitWidth, InitStyle, AS, MSPropertyAttr);
1797 isInstField = false;
1798 } else {
1799 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1800 BitWidth, InitStyle, AS);
1801 }
Chris Lattner6f8ce142009-03-05 23:03:49 +00001802 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001803 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001804 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001805
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001806 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001807 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001808 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001809 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001810
1811 // Non-instance-fields can't have a bitfield.
1812 if (BitWidth) {
1813 if (Member->isInvalidDecl()) {
1814 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001815 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001816 // C++ 9.6p3: A bit-field shall not be a static member.
1817 // "static member 'A' cannot be a bit-field"
1818 Diag(Loc, diag::err_static_not_bitfield)
1819 << Name << BitWidth->getSourceRange();
1820 } else if (isa<TypedefDecl>(Member)) {
1821 // "typedef member 'x' cannot be a bit-field"
1822 Diag(Loc, diag::err_typedef_not_bitfield)
1823 << Name << BitWidth->getSourceRange();
1824 } else {
1825 // A function typedef ("typedef int f(); f a;").
1826 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1827 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001828 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001829 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001830 }
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Chris Lattner8b963ef2009-03-05 23:01:03 +00001832 BitWidth = 0;
1833 Member->setInvalidDecl();
1834 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001835
1836 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001837
Douglas Gregor37b372b2009-08-20 22:52:58 +00001838 // If we have declared a member function template, set the access of the
1839 // templated declaration as well.
1840 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1841 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001842 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001843
Richard Smitha4b39652012-08-06 03:25:17 +00001844 if (VS.isOverrideSpecified())
1845 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1846 if (VS.isFinalSpecified())
1847 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001848
Douglas Gregorf5251602011-03-08 17:10:18 +00001849 if (VS.getLastLocation().isValid()) {
1850 // Update the end location of a method that has a virt-specifiers.
1851 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1852 MD->setRangeEnd(VS.getLastLocation());
1853 }
Richard Smitha4b39652012-08-06 03:25:17 +00001854
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001855 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001856
Douglas Gregor10bd3682008-11-17 22:58:34 +00001857 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001858
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001859 if (isInstField) {
1860 FieldDecl *FD = cast<FieldDecl>(Member);
1861 FieldCollector->Add(FD);
1862
1863 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1864 FD->getLocation())
1865 != DiagnosticsEngine::Ignored) {
1866 // Remember all explicit private FieldDecls that have a name, no side
1867 // effects and are not part of a dependent type declaration.
1868 if (!FD->isImplicit() && FD->getDeclName() &&
1869 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001870 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001871 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001872 !InitializationHasSideEffects(*FD))
1873 UnusedPrivateFields.insert(FD);
1874 }
1875 }
1876
John McCalld226f652010-08-21 09:40:31 +00001877 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001878}
1879
Hans Wennborg471f9852012-09-18 15:58:06 +00001880namespace {
1881 class UninitializedFieldVisitor
1882 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1883 Sema &S;
1884 ValueDecl *VD;
1885 public:
1886 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1887 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001888 S(S) {
1889 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1890 this->VD = IFD->getAnonField();
1891 else
1892 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001893 }
1894
1895 void HandleExpr(Expr *E) {
1896 if (!E) return;
1897
1898 // Expressions like x(x) sometimes lack the surrounding expressions
1899 // but need to be checked anyways.
1900 HandleValue(E);
1901 Visit(E);
1902 }
1903
1904 void HandleValue(Expr *E) {
1905 E = E->IgnoreParens();
1906
1907 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1908 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001909 return;
1910
1911 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1912 // or union.
1913 MemberExpr *FieldME = ME;
1914
Hans Wennborg471f9852012-09-18 15:58:06 +00001915 Expr *Base = E;
1916 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001917 ME = cast<MemberExpr>(Base);
1918
1919 if (isa<VarDecl>(ME->getMemberDecl()))
1920 return;
1921
1922 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1923 if (!FD->isAnonymousStructOrUnion())
1924 FieldME = ME;
1925
Hans Wennborg471f9852012-09-18 15:58:06 +00001926 Base = ME->getBase();
1927 }
1928
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001929 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00001930 unsigned diag = VD->getType()->isReferenceType()
1931 ? diag::warn_reference_field_is_uninit
1932 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001933 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001934 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001935 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00001936 }
1937
1938 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1939 HandleValue(CO->getTrueExpr());
1940 HandleValue(CO->getFalseExpr());
1941 return;
1942 }
1943
1944 if (BinaryConditionalOperator *BCO =
1945 dyn_cast<BinaryConditionalOperator>(E)) {
1946 HandleValue(BCO->getCommon());
1947 HandleValue(BCO->getFalseExpr());
1948 return;
1949 }
1950
1951 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1952 switch (BO->getOpcode()) {
1953 default:
1954 return;
1955 case(BO_PtrMemD):
1956 case(BO_PtrMemI):
1957 HandleValue(BO->getLHS());
1958 return;
1959 case(BO_Comma):
1960 HandleValue(BO->getRHS());
1961 return;
1962 }
1963 }
1964 }
1965
1966 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1967 if (E->getCastKind() == CK_LValueToRValue)
1968 HandleValue(E->getSubExpr());
1969
1970 Inherited::VisitImplicitCastExpr(E);
1971 }
1972
1973 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1974 Expr *Callee = E->getCallee();
1975 if (isa<MemberExpr>(Callee))
1976 HandleValue(Callee);
1977
1978 Inherited::VisitCXXMemberCallExpr(E);
1979 }
1980 };
1981 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1982 ValueDecl *VD) {
1983 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1984 }
1985} // namespace
1986
Richard Smith7a614d82011-06-11 17:19:42 +00001987/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001988/// in-class initializer for a non-static C++ class member, and after
1989/// instantiating an in-class initializer in a class template. Such actions
1990/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001991void
Richard Smithca523302012-06-10 03:12:00 +00001992Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001993 Expr *InitExpr) {
1994 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001995 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1996 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001997
1998 if (!InitExpr) {
1999 FD->setInvalidDecl();
2000 FD->removeInClassInitializer();
2001 return;
2002 }
2003
Peter Collingbournefef21892011-10-23 18:59:44 +00002004 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2005 FD->setInvalidDecl();
2006 FD->removeInClassInitializer();
2007 return;
2008 }
2009
Hans Wennborg471f9852012-09-18 15:58:06 +00002010 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2011 != DiagnosticsEngine::Ignored) {
2012 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2013 }
2014
Richard Smith7a614d82011-06-11 17:19:42 +00002015 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002016 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00002017 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002018 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00002019 << /*at end of ctor*/1 << InitExpr->getSourceRange();
2020 }
Sebastian Redl33deb352012-02-22 10:50:08 +00002021 Expr **Inits = &InitExpr;
2022 unsigned NumInits = 1;
2023 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002024 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002025 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002026 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00002027 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
2028 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00002029 if (Init.isInvalid()) {
2030 FD->setInvalidDecl();
2031 return;
2032 }
Richard Smith7a614d82011-06-11 17:19:42 +00002033 }
2034
Richard Smith41956372013-01-14 22:39:08 +00002035 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002036 // The initialization of each base and member constitutes a
2037 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002038 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002039 if (Init.isInvalid()) {
2040 FD->setInvalidDecl();
2041 return;
2042 }
2043
2044 InitExpr = Init.release();
2045
2046 FD->setInClassInitializer(InitExpr);
2047}
2048
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002049/// \brief Find the direct and/or virtual base specifiers that
2050/// correspond to the given base type, for use in base initialization
2051/// within a constructor.
2052static bool FindBaseInitializer(Sema &SemaRef,
2053 CXXRecordDecl *ClassDecl,
2054 QualType BaseType,
2055 const CXXBaseSpecifier *&DirectBaseSpec,
2056 const CXXBaseSpecifier *&VirtualBaseSpec) {
2057 // First, check for a direct base class.
2058 DirectBaseSpec = 0;
2059 for (CXXRecordDecl::base_class_const_iterator Base
2060 = ClassDecl->bases_begin();
2061 Base != ClassDecl->bases_end(); ++Base) {
2062 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2063 // We found a direct base of this type. That's what we're
2064 // initializing.
2065 DirectBaseSpec = &*Base;
2066 break;
2067 }
2068 }
2069
2070 // Check for a virtual base class.
2071 // FIXME: We might be able to short-circuit this if we know in advance that
2072 // there are no virtual bases.
2073 VirtualBaseSpec = 0;
2074 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2075 // We haven't found a base yet; search the class hierarchy for a
2076 // virtual base class.
2077 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2078 /*DetectVirtual=*/false);
2079 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2080 BaseType, Paths)) {
2081 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2082 Path != Paths.end(); ++Path) {
2083 if (Path->back().Base->isVirtual()) {
2084 VirtualBaseSpec = Path->back().Base;
2085 break;
2086 }
2087 }
2088 }
2089 }
2090
2091 return DirectBaseSpec || VirtualBaseSpec;
2092}
2093
Sebastian Redl6df65482011-09-24 17:48:25 +00002094/// \brief Handle a C++ member initializer using braced-init-list syntax.
2095MemInitResult
2096Sema::ActOnMemInitializer(Decl *ConstructorD,
2097 Scope *S,
2098 CXXScopeSpec &SS,
2099 IdentifierInfo *MemberOrBase,
2100 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002101 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002102 SourceLocation IdLoc,
2103 Expr *InitList,
2104 SourceLocation EllipsisLoc) {
2105 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002106 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002107 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002108}
2109
2110/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002111MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002112Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002113 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002114 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002115 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002116 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002117 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002118 SourceLocation IdLoc,
2119 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002120 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002121 SourceLocation RParenLoc,
2122 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002123 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2124 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002125 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002126 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002127 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002128}
2129
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002130namespace {
2131
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002132// Callback to only accept typo corrections that can be a valid C++ member
2133// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002134class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2135 public:
2136 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2137 : ClassDecl(ClassDecl) {}
2138
2139 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2140 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2141 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2142 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2143 else
2144 return isa<TypeDecl>(ND);
2145 }
2146 return false;
2147 }
2148
2149 private:
2150 CXXRecordDecl *ClassDecl;
2151};
2152
2153}
2154
Sebastian Redl6df65482011-09-24 17:48:25 +00002155/// \brief Handle a C++ member initializer.
2156MemInitResult
2157Sema::BuildMemInitializer(Decl *ConstructorD,
2158 Scope *S,
2159 CXXScopeSpec &SS,
2160 IdentifierInfo *MemberOrBase,
2161 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002162 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002163 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002164 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002165 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002166 if (!ConstructorD)
2167 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002169 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002170
2171 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002172 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002173 if (!Constructor) {
2174 // The user wrote a constructor initializer on a function that is
2175 // not a C++ constructor. Ignore the error for now, because we may
2176 // have more member initializers coming; we'll diagnose it just
2177 // once in ActOnMemInitializers.
2178 return true;
2179 }
2180
2181 CXXRecordDecl *ClassDecl = Constructor->getParent();
2182
2183 // C++ [class.base.init]p2:
2184 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002185 // constructor's class and, if not found in that scope, are looked
2186 // up in the scope containing the constructor's definition.
2187 // [Note: if the constructor's class contains a member with the
2188 // same name as a direct or virtual base class of the class, a
2189 // mem-initializer-id naming the member or base class and composed
2190 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002191 // mem-initializer-id for the hidden base class may be specified
2192 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002193 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002194 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002195 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002196 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002197 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002198 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002199 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2200 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002201 if (EllipsisLoc.isValid())
2202 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002203 << MemberOrBase
2204 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002205
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002206 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002207 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002208 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002209 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002210 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002211 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002212 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002213
2214 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002215 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002216 } else if (DS.getTypeSpecType() == TST_decltype) {
2217 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002218 } else {
2219 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2220 LookupParsedName(R, S, &SS);
2221
2222 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2223 if (!TyD) {
2224 if (R.isAmbiguous()) return true;
2225
John McCallfd225442010-04-09 19:01:14 +00002226 // We don't want access-control diagnostics here.
2227 R.suppressDiagnostics();
2228
Douglas Gregor7a886e12010-01-19 06:46:48 +00002229 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2230 bool NotUnknownSpecialization = false;
2231 DeclContext *DC = computeDeclContext(SS, false);
2232 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2233 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2234
2235 if (!NotUnknownSpecialization) {
2236 // When the scope specifier can refer to a member of an unknown
2237 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002238 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2239 SS.getWithLocInContext(Context),
2240 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002241 if (BaseType.isNull())
2242 return true;
2243
Douglas Gregor7a886e12010-01-19 06:46:48 +00002244 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002245 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002246 }
2247 }
2248
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002249 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002250 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002251 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002252 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002253 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002254 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002255 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2256 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002257 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002258 // We have found a non-static data member with a similar
2259 // name to what was typed; complain and initialize that
2260 // member.
2261 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2262 << MemberOrBase << true << CorrectedQuotedStr
2263 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2264 Diag(Member->getLocation(), diag::note_previous_decl)
2265 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002266
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002267 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002268 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002269 const CXXBaseSpecifier *DirectBaseSpec;
2270 const CXXBaseSpecifier *VirtualBaseSpec;
2271 if (FindBaseInitializer(*this, ClassDecl,
2272 Context.getTypeDeclType(Type),
2273 DirectBaseSpec, VirtualBaseSpec)) {
2274 // We have found a direct or virtual base class with a
2275 // similar name to what was typed; complain and initialize
2276 // that base class.
2277 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002278 << MemberOrBase << false << CorrectedQuotedStr
2279 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002280
2281 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2282 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002283 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002284 diag::note_base_class_specified_here)
2285 << BaseSpec->getType()
2286 << BaseSpec->getSourceRange();
2287
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002288 TyD = Type;
2289 }
2290 }
2291 }
2292
Douglas Gregor7a886e12010-01-19 06:46:48 +00002293 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002294 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002295 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002296 return true;
2297 }
John McCall2b194412009-12-21 10:41:20 +00002298 }
2299
Douglas Gregor7a886e12010-01-19 06:46:48 +00002300 if (BaseType.isNull()) {
2301 BaseType = Context.getTypeDeclType(TyD);
2302 if (SS.isSet()) {
2303 NestedNameSpecifier *Qualifier =
2304 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002305
Douglas Gregor7a886e12010-01-19 06:46:48 +00002306 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002307 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002308 }
John McCall2b194412009-12-21 10:41:20 +00002309 }
2310 }
Mike Stump1eb44332009-09-09 15:08:12 +00002311
John McCalla93c9342009-12-07 02:54:59 +00002312 if (!TInfo)
2313 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002314
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002315 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002316}
2317
Chandler Carruth81c64772011-09-03 01:14:15 +00002318/// Checks a member initializer expression for cases where reference (or
2319/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002320static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2321 Expr *Init,
2322 SourceLocation IdLoc) {
2323 QualType MemberTy = Member->getType();
2324
2325 // We only handle pointers and references currently.
2326 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2327 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2328 return;
2329
2330 const bool IsPointer = MemberTy->isPointerType();
2331 if (IsPointer) {
2332 if (const UnaryOperator *Op
2333 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2334 // The only case we're worried about with pointers requires taking the
2335 // address.
2336 if (Op->getOpcode() != UO_AddrOf)
2337 return;
2338
2339 Init = Op->getSubExpr();
2340 } else {
2341 // We only handle address-of expression initializers for pointers.
2342 return;
2343 }
2344 }
2345
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002346 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2347 // Taking the address of a temporary will be diagnosed as a hard error.
2348 if (IsPointer)
2349 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002350
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002351 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2352 << Member << Init->getSourceRange();
2353 } else if (const DeclRefExpr *DRE
2354 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2355 // We only warn when referring to a non-reference parameter declaration.
2356 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2357 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002358 return;
2359
2360 S.Diag(Init->getExprLoc(),
2361 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2362 : diag::warn_bind_ref_member_to_parameter)
2363 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002364 } else {
2365 // Other initializers are fine.
2366 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002367 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002368
2369 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2370 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002371}
2372
John McCallf312b1e2010-08-26 23:41:50 +00002373MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002374Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002375 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002376 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2377 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2378 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002379 "Member must be a FieldDecl or IndirectFieldDecl");
2380
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002381 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002382 return true;
2383
Douglas Gregor464b2f02010-11-05 22:21:31 +00002384 if (Member->isInvalidDecl())
2385 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002386
John McCallb4190042009-11-04 23:02:40 +00002387 // Diagnose value-uses of fields to initialize themselves, e.g.
2388 // foo(foo)
2389 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002390 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002391 Expr **Args;
2392 unsigned NumArgs;
2393 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2394 Args = ParenList->getExprs();
2395 NumArgs = ParenList->getNumExprs();
Richard Smithc83c2302012-12-19 01:39:02 +00002396 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002397 Args = InitList->getInits();
2398 NumArgs = InitList->getNumInits();
Richard Smithc83c2302012-12-19 01:39:02 +00002399 } else {
2400 // Template instantiation doesn't reconstruct ParenListExprs for us.
2401 Args = &Init;
2402 NumArgs = 1;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002403 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002404
Richard Trieude5e75c2012-06-14 23:11:34 +00002405 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2406 != DiagnosticsEngine::Ignored)
2407 for (unsigned i = 0; i < NumArgs; ++i)
2408 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002409 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002410 // initializing the i'th field, throw a warning if any of the >= i'th
2411 // fields are used, as they are not yet initialized.
2412 // Right now we are only handling the case where the i'th field uses
2413 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002414 // Also need to take into account that some fields may be initialized by
2415 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002416 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002417
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002418 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002419
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002420 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002421 // Can't check initialization for a member of dependent type or when
2422 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002423 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002424 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002425 bool InitList = false;
2426 if (isa<InitListExpr>(Init)) {
2427 InitList = true;
2428 Args = &Init;
2429 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002430
2431 if (isStdInitializerList(Member->getType(), 0)) {
2432 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2433 << /*at end of ctor*/1 << InitRange;
2434 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002435 }
2436
Chandler Carruth894aed92010-12-06 09:23:57 +00002437 // Initialize the member.
2438 InitializedEntity MemberEntity =
2439 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2440 : InitializedEntity::InitializeMember(IndirectMember, 0);
2441 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002442 InitList ? InitializationKind::CreateDirectList(IdLoc)
2443 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2444 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002445
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002446 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2447 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002448 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002449 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002450 if (MemberInit.isInvalid())
2451 return true;
2452
Richard Smith41956372013-01-14 22:39:08 +00002453 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002454 // The initialization of each base and member constitutes a
2455 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002456 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002457 if (MemberInit.isInvalid())
2458 return true;
2459
Richard Smithc83c2302012-12-19 01:39:02 +00002460 Init = MemberInit.get();
2461 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002462 }
2463
Chandler Carruth894aed92010-12-06 09:23:57 +00002464 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002465 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2466 InitRange.getBegin(), Init,
2467 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002468 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002469 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2470 InitRange.getBegin(), Init,
2471 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002472 }
Eli Friedman59c04372009-07-29 19:44:27 +00002473}
2474
John McCallf312b1e2010-08-26 23:41:50 +00002475MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002476Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002477 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002478 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002479 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002480 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002481 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002482 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002483
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002484 bool InitList = true;
2485 Expr **Args = &Init;
2486 unsigned NumArgs = 1;
2487 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2488 InitList = false;
2489 Args = ParenList->getExprs();
2490 NumArgs = ParenList->getNumExprs();
2491 }
2492
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002493 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002494 // Initialize the object.
2495 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2496 QualType(ClassDecl->getTypeForDecl(), 0));
2497 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002498 InitList ? InitializationKind::CreateDirectList(NameLoc)
2499 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2500 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002501 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2502 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002503 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002504 0);
Sean Hunt41717662011-02-26 19:13:13 +00002505 if (DelegationInit.isInvalid())
2506 return true;
2507
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002508 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2509 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002510
Richard Smith41956372013-01-14 22:39:08 +00002511 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002512 // The initialization of each base and member constitutes a
2513 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002514 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2515 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002516 if (DelegationInit.isInvalid())
2517 return true;
2518
Eli Friedmand21016f2012-05-19 23:35:23 +00002519 // If we are in a dependent context, template instantiation will
2520 // perform this type-checking again. Just save the arguments that we
2521 // received in a ParenListExpr.
2522 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2523 // of the information that we have about the base
2524 // initializer. However, deconstructing the ASTs is a dicey process,
2525 // and this approach is far more likely to get the corner cases right.
2526 if (CurContext->isDependentContext())
2527 DelegationInit = Owned(Init);
2528
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002529 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002530 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002531 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002532}
2533
2534MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002535Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002536 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002537 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002538 SourceLocation BaseLoc
2539 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002540
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002541 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2542 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2543 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2544
2545 // C++ [class.base.init]p2:
2546 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002547 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002548 // of that class, the mem-initializer is ill-formed. A
2549 // mem-initializer-list can initialize a base class using any
2550 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002551 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002552
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002553 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002554 if (EllipsisLoc.isValid()) {
2555 // This is a pack expansion.
2556 if (!BaseType->containsUnexpandedParameterPack()) {
2557 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002558 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002559
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002560 EllipsisLoc = SourceLocation();
2561 }
2562 } else {
2563 // Check for any unexpanded parameter packs.
2564 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2565 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002566
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002567 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002568 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002569 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002570
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002571 // Check for direct and virtual base classes.
2572 const CXXBaseSpecifier *DirectBaseSpec = 0;
2573 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2574 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002575 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2576 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002577 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002578
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002579 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2580 VirtualBaseSpec);
2581
2582 // C++ [base.class.init]p2:
2583 // Unless the mem-initializer-id names a nonstatic data member of the
2584 // constructor's class or a direct or virtual base of that class, the
2585 // mem-initializer is ill-formed.
2586 if (!DirectBaseSpec && !VirtualBaseSpec) {
2587 // If the class has any dependent bases, then it's possible that
2588 // one of those types will resolve to the same type as
2589 // BaseType. Therefore, just treat this as a dependent base
2590 // class initialization. FIXME: Should we try to check the
2591 // initialization anyway? It seems odd.
2592 if (ClassDecl->hasAnyDependentBases())
2593 Dependent = true;
2594 else
2595 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2596 << BaseType << Context.getTypeDeclType(ClassDecl)
2597 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2598 }
2599 }
2600
2601 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002602 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002603
Sebastian Redl6df65482011-09-24 17:48:25 +00002604 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2605 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002606 InitRange.getBegin(), Init,
2607 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002608 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002609
2610 // C++ [base.class.init]p2:
2611 // If a mem-initializer-id is ambiguous because it designates both
2612 // a direct non-virtual base class and an inherited virtual base
2613 // class, the mem-initializer is ill-formed.
2614 if (DirectBaseSpec && VirtualBaseSpec)
2615 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002616 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002617
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002618 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002619 if (!BaseSpec)
2620 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2621
2622 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002623 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002624 Expr **Args = &Init;
2625 unsigned NumArgs = 1;
2626 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002627 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002628 Args = ParenList->getExprs();
2629 NumArgs = ParenList->getNumExprs();
2630 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002631
2632 InitializedEntity BaseEntity =
2633 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2634 InitializationKind Kind =
2635 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2636 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2637 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002638 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2639 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002640 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002641 if (BaseInit.isInvalid())
2642 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002643
Richard Smith41956372013-01-14 22:39:08 +00002644 // C++11 [class.base.init]p7:
2645 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002646 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002647 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002648 if (BaseInit.isInvalid())
2649 return true;
2650
2651 // If we are in a dependent context, template instantiation will
2652 // perform this type-checking again. Just save the arguments that we
2653 // received in a ParenListExpr.
2654 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2655 // of the information that we have about the base
2656 // initializer. However, deconstructing the ASTs is a dicey process,
2657 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002658 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002659 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002660
Sean Huntcbb67482011-01-08 20:30:50 +00002661 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002662 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002663 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002664 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002665 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002666}
2667
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002668// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002669static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2670 if (T.isNull()) T = E->getType();
2671 QualType TargetType = SemaRef.BuildReferenceType(
2672 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002673 SourceLocation ExprLoc = E->getLocStart();
2674 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2675 TargetType, ExprLoc);
2676
2677 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2678 SourceRange(ExprLoc, ExprLoc),
2679 E->getSourceRange()).take();
2680}
2681
Anders Carlssone5ef7402010-04-23 03:10:23 +00002682/// ImplicitInitializerKind - How an implicit base or member initializer should
2683/// initialize its base or member.
2684enum ImplicitInitializerKind {
2685 IIK_Default,
2686 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002687 IIK_Move,
2688 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002689};
2690
Anders Carlssondefefd22010-04-23 02:00:02 +00002691static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002692BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002693 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002694 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002695 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002696 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002697 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002698 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2699 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002700
John McCall60d7b3a2010-08-24 06:29:42 +00002701 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002702
2703 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002704 case IIK_Inherit: {
2705 const CXXRecordDecl *Inherited =
2706 Constructor->getInheritedConstructor()->getParent();
2707 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2708 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2709 // C++11 [class.inhctor]p8:
2710 // Each expression in the expression-list is of the form
2711 // static_cast<T&&>(p), where p is the name of the corresponding
2712 // constructor parameter and T is the declared type of p.
2713 SmallVector<Expr*, 16> Args;
2714 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2715 ParmVarDecl *PD = Constructor->getParamDecl(I);
2716 ExprResult ArgExpr =
2717 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2718 VK_LValue, SourceLocation());
2719 if (ArgExpr.isInvalid())
2720 return true;
2721 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2722 }
2723
2724 InitializationKind InitKind = InitializationKind::CreateDirect(
2725 Constructor->getLocation(), SourceLocation(), SourceLocation());
2726 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2727 Args.data(), Args.size());
2728 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2729 break;
2730 }
2731 }
2732 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002733 case IIK_Default: {
2734 InitializationKind InitKind
2735 = InitializationKind::CreateDefault(Constructor->getLocation());
2736 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002737 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002738 break;
2739 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002740
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002741 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002742 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002743 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002744 ParmVarDecl *Param = Constructor->getParamDecl(0);
2745 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002746
Anders Carlssone5ef7402010-04-23 03:10:23 +00002747 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002748 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002749 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002750 Constructor->getLocation(), ParamType,
2751 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002752
Eli Friedman5f2987c2012-02-02 03:46:19 +00002753 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2754
Anders Carlssonc7957502010-04-24 22:02:54 +00002755 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002756 QualType ArgTy =
2757 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2758 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002759
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002760 if (Moving) {
2761 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2762 }
2763
John McCallf871d0c2010-08-07 06:22:56 +00002764 CXXCastPath BasePath;
2765 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002766 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2767 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002768 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002769 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002770
Anders Carlssone5ef7402010-04-23 03:10:23 +00002771 InitializationKind InitKind
2772 = InitializationKind::CreateDirect(Constructor->getLocation(),
2773 SourceLocation(), SourceLocation());
2774 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2775 &CopyCtorArg, 1);
2776 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002777 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002778 break;
2779 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002780 }
John McCall9ae2f072010-08-23 23:25:46 +00002781
Douglas Gregor53c374f2010-12-07 00:41:46 +00002782 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002783 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002784 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002785
Anders Carlssondefefd22010-04-23 02:00:02 +00002786 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002787 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002788 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2789 SourceLocation()),
2790 BaseSpec->isVirtual(),
2791 SourceLocation(),
2792 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002793 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002794 SourceLocation());
2795
Anders Carlssondefefd22010-04-23 02:00:02 +00002796 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002797}
2798
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002799static bool RefersToRValueRef(Expr *MemRef) {
2800 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2801 return Referenced->getType()->isRValueReferenceType();
2802}
2803
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002804static bool
2805BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002806 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002807 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002808 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002809 if (Field->isInvalidDecl())
2810 return true;
2811
Chandler Carruthf186b542010-06-29 23:50:44 +00002812 SourceLocation Loc = Constructor->getLocation();
2813
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002814 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2815 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002816 ParmVarDecl *Param = Constructor->getParamDecl(0);
2817 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002818
2819 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002820 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2821 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002822
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002823 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002824 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002825 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002826 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002827
Eli Friedman5f2987c2012-02-02 03:46:19 +00002828 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2829
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002830 if (Moving) {
2831 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2832 }
2833
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002834 // Build a reference to this field within the parameter.
2835 CXXScopeSpec SS;
2836 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2837 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002838 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2839 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002840 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002841 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002842 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002843 ParamType, Loc,
2844 /*IsArrow=*/false,
2845 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002846 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002847 /*FirstQualifierInScope=*/0,
2848 MemberLookup,
2849 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002850 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002851 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002852
2853 // C++11 [class.copy]p15:
2854 // - if a member m has rvalue reference type T&&, it is direct-initialized
2855 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002856 if (RefersToRValueRef(CtorArg.get())) {
2857 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002858 }
2859
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002860 // When the field we are copying is an array, create index variables for
2861 // each dimension of the array. We use these index variables to subscript
2862 // the source array, and other clients (e.g., CodeGen) will perform the
2863 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002864 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002865 QualType BaseType = Field->getType();
2866 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002867 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002868 while (const ConstantArrayType *Array
2869 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002870 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002871 // Create the iteration variable for this array index.
2872 IdentifierInfo *IterationVarName = 0;
2873 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002874 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002875 llvm::raw_svector_ostream OS(Str);
2876 OS << "__i" << IndexVariables.size();
2877 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2878 }
2879 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002880 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002881 IterationVarName, SizeType,
2882 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002883 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002884 IndexVariables.push_back(IterationVar);
2885
2886 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002887 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002888 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002889 assert(!IterationVarRef.isInvalid() &&
2890 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002891 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2892 assert(!IterationVarRef.isInvalid() &&
2893 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002894
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002895 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002896 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002897 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002898 Loc);
2899 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002900 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002901
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002902 BaseType = Array->getElementType();
2903 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002904
2905 // The array subscript expression is an lvalue, which is wrong for moving.
2906 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002907 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002908
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002909 // Construct the entity that we will be initializing. For an array, this
2910 // will be first element in the array, which may require several levels
2911 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002912 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002913 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002914 if (Indirect)
2915 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2916 else
2917 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002918 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2919 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2920 0,
2921 Entities.back()));
2922
2923 // Direct-initialize to use the copy constructor.
2924 InitializationKind InitKind =
2925 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2926
Sebastian Redl74e611a2011-09-04 18:14:28 +00002927 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002928 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002929 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002930
John McCall60d7b3a2010-08-24 06:29:42 +00002931 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002932 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002933 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002934 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002935 if (MemberInit.isInvalid())
2936 return true;
2937
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002938 if (Indirect) {
2939 assert(IndexVariables.size() == 0 &&
2940 "Indirect field improperly initialized");
2941 CXXMemberInit
2942 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2943 Loc, Loc,
2944 MemberInit.takeAs<Expr>(),
2945 Loc);
2946 } else
2947 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2948 Loc, MemberInit.takeAs<Expr>(),
2949 Loc,
2950 IndexVariables.data(),
2951 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002952 return false;
2953 }
2954
Richard Smith07b0fdc2013-03-18 21:12:30 +00002955 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
2956 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002957
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002958 QualType FieldBaseElementType =
2959 SemaRef.Context.getBaseElementType(Field->getType());
2960
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002961 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002962 InitializedEntity InitEntity
2963 = Indirect? InitializedEntity::InitializeMember(Indirect)
2964 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002965 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002966 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002967
2968 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002969 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002970 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002971
Douglas Gregor53c374f2010-12-07 00:41:46 +00002972 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002973 if (MemberInit.isInvalid())
2974 return true;
2975
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002976 if (Indirect)
2977 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2978 Indirect, Loc,
2979 Loc,
2980 MemberInit.get(),
2981 Loc);
2982 else
2983 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2984 Field, Loc, Loc,
2985 MemberInit.get(),
2986 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002987 return false;
2988 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002989
Sean Hunt1f2f3842011-05-17 00:19:05 +00002990 if (!Field->getParent()->isUnion()) {
2991 if (FieldBaseElementType->isReferenceType()) {
2992 SemaRef.Diag(Constructor->getLocation(),
2993 diag::err_uninitialized_member_in_ctor)
2994 << (int)Constructor->isImplicit()
2995 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2996 << 0 << Field->getDeclName();
2997 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2998 return true;
2999 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003000
Sean Hunt1f2f3842011-05-17 00:19:05 +00003001 if (FieldBaseElementType.isConstQualified()) {
3002 SemaRef.Diag(Constructor->getLocation(),
3003 diag::err_uninitialized_member_in_ctor)
3004 << (int)Constructor->isImplicit()
3005 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3006 << 1 << Field->getDeclName();
3007 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3008 return true;
3009 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003010 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003011
David Blaikie4e4d0842012-03-11 07:00:24 +00003012 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003013 FieldBaseElementType->isObjCRetainableType() &&
3014 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3015 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003016 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003017 // Default-initialize Objective-C pointers to NULL.
3018 CXXMemberInit
3019 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3020 Loc, Loc,
3021 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3022 Loc);
3023 return false;
3024 }
3025
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003026 // Nothing to initialize.
3027 CXXMemberInit = 0;
3028 return false;
3029}
John McCallf1860e52010-05-20 23:23:51 +00003030
3031namespace {
3032struct BaseAndFieldInfo {
3033 Sema &S;
3034 CXXConstructorDecl *Ctor;
3035 bool AnyErrorsInInits;
3036 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003037 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003038 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003039
3040 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3041 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003042 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3043 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003044 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003045 else if (Generated && Ctor->isMoveConstructor())
3046 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003047 else if (Ctor->getInheritedConstructor())
3048 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003049 else
3050 IIK = IIK_Default;
3051 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003052
3053 bool isImplicitCopyOrMove() const {
3054 switch (IIK) {
3055 case IIK_Copy:
3056 case IIK_Move:
3057 return true;
3058
3059 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003060 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003061 return false;
3062 }
David Blaikie30263482012-01-20 21:50:17 +00003063
3064 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003065 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003066
3067 bool addFieldInitializer(CXXCtorInitializer *Init) {
3068 AllToInit.push_back(Init);
3069
3070 // Check whether this initializer makes the field "used".
3071 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
3072 S.UnusedPrivateFields.remove(Init->getAnyMember());
3073
3074 return false;
3075 }
John McCallf1860e52010-05-20 23:23:51 +00003076};
3077}
3078
Richard Smitha4950662011-09-19 13:34:43 +00003079/// \brief Determine whether the given indirect field declaration is somewhere
3080/// within an anonymous union.
3081static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3082 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3083 CEnd = F->chain_end();
3084 C != CEnd; ++C)
3085 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3086 if (Record->isUnion())
3087 return true;
3088
3089 return false;
3090}
3091
Douglas Gregorddb21472011-11-02 23:04:16 +00003092/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3093/// array type.
3094static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3095 if (T->isIncompleteArrayType())
3096 return true;
3097
3098 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3099 if (!ArrayT->getSize())
3100 return true;
3101
3102 T = ArrayT->getElementType();
3103 }
3104
3105 return false;
3106}
3107
Richard Smith7a614d82011-06-11 17:19:42 +00003108static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003109 FieldDecl *Field,
3110 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003111
Chandler Carruthe861c602010-06-30 02:59:29 +00003112 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003113 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3114 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003115
Richard Smith0b8220a2012-08-07 21:30:42 +00003116 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003117 // has a brace-or-equal-initializer, the entity is initialized as specified
3118 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003119 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003120 CXXCtorInitializer *Init;
3121 if (Indirect)
3122 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3123 SourceLocation(),
3124 SourceLocation(), 0,
3125 SourceLocation());
3126 else
3127 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3128 SourceLocation(),
3129 SourceLocation(), 0,
3130 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003131 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003132 }
3133
Richard Smithc115f632011-09-18 11:14:50 +00003134 // Don't build an implicit initializer for union members if none was
3135 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003136 if (Field->getParent()->isUnion() ||
3137 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003138 return false;
3139
Douglas Gregorddb21472011-11-02 23:04:16 +00003140 // Don't initialize incomplete or zero-length arrays.
3141 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3142 return false;
3143
John McCallf1860e52010-05-20 23:23:51 +00003144 // Don't try to build an implicit initializer if there were semantic
3145 // errors in any of the initializers (and therefore we might be
3146 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003147 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003148 return false;
3149
Sean Huntcbb67482011-01-08 20:30:50 +00003150 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003151 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3152 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003153 return true;
John McCallf1860e52010-05-20 23:23:51 +00003154
Richard Smith0b8220a2012-08-07 21:30:42 +00003155 if (!Init)
3156 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003157
Richard Smith0b8220a2012-08-07 21:30:42 +00003158 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003159}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003160
3161bool
3162Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3163 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003164 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003165 Constructor->setNumCtorInitializers(1);
3166 CXXCtorInitializer **initializer =
3167 new (Context) CXXCtorInitializer*[1];
3168 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3169 Constructor->setCtorInitializers(initializer);
3170
Sean Huntb76af9c2011-05-03 23:05:34 +00003171 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003172 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003173 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3174 }
3175
Sean Huntc1598702011-05-05 00:05:47 +00003176 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003177
Sean Hunt059ce0d2011-05-01 07:04:31 +00003178 return false;
3179}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003180
David Blaikie93c86172013-01-17 05:26:25 +00003181bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3182 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003183 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003184 // Just store the initializers as written, they will be checked during
3185 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003186 if (!Initializers.empty()) {
3187 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003188 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003189 new (Context) CXXCtorInitializer*[Initializers.size()];
3190 memcpy(baseOrMemberInitializers, Initializers.data(),
3191 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003192 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003193 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003194
3195 // Let template instantiation know whether we had errors.
3196 if (AnyErrors)
3197 Constructor->setInvalidDecl();
3198
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003199 return false;
3200 }
3201
John McCallf1860e52010-05-20 23:23:51 +00003202 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003203
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003204 // We need to build the initializer AST according to order of construction
3205 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003206 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003207 if (!ClassDecl)
3208 return true;
3209
Eli Friedman80c30da2009-11-09 19:20:36 +00003210 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003211
David Blaikie93c86172013-01-17 05:26:25 +00003212 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003213 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003214
3215 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003216 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003217 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003218 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003219 }
3220
Anders Carlsson711f34a2010-04-21 19:52:01 +00003221 // Keep track of the direct virtual bases.
3222 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3223 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3224 E = ClassDecl->bases_end(); I != E; ++I) {
3225 if (I->isVirtual())
3226 DirectVBases.insert(I);
3227 }
3228
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003229 // Push virtual bases before others.
3230 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3231 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3232
Sean Huntcbb67482011-01-08 20:30:50 +00003233 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003234 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3235 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003236 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003237 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003238 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003239 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003240 VBase, IsInheritedVirtualBase,
3241 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003242 HadError = true;
3243 continue;
3244 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003245
John McCallf1860e52010-05-20 23:23:51 +00003246 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003247 }
3248 }
Mike Stump1eb44332009-09-09 15:08:12 +00003249
John McCallf1860e52010-05-20 23:23:51 +00003250 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003251 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3252 E = ClassDecl->bases_end(); Base != E; ++Base) {
3253 // Virtuals are in the virtual base list and already constructed.
3254 if (Base->isVirtual())
3255 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003256
Sean Huntcbb67482011-01-08 20:30:50 +00003257 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003258 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3259 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003260 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003261 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003262 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003263 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003264 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003265 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003266 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003267 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003268
John McCallf1860e52010-05-20 23:23:51 +00003269 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003270 }
3271 }
Mike Stump1eb44332009-09-09 15:08:12 +00003272
John McCallf1860e52010-05-20 23:23:51 +00003273 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003274 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3275 MemEnd = ClassDecl->decls_end();
3276 Mem != MemEnd; ++Mem) {
3277 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003278 // C++ [class.bit]p2:
3279 // A declaration for a bit-field that omits the identifier declares an
3280 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3281 // initialized.
3282 if (F->isUnnamedBitfield())
3283 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003284
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003285 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003286 // handle anonymous struct/union fields based on their individual
3287 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003288 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003289 continue;
3290
3291 if (CollectFieldInitializer(*this, Info, F))
3292 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003293 continue;
3294 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003295
3296 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003297 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003298 continue;
3299
3300 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3301 if (F->getType()->isIncompleteArrayType()) {
3302 assert(ClassDecl->hasFlexibleArrayMember() &&
3303 "Incomplete array type is not valid");
3304 continue;
3305 }
3306
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003307 // Initialize each field of an anonymous struct individually.
3308 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3309 HadError = true;
3310
3311 continue;
3312 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003313 }
Mike Stump1eb44332009-09-09 15:08:12 +00003314
David Blaikie93c86172013-01-17 05:26:25 +00003315 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003316 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003317 Constructor->setNumCtorInitializers(NumInitializers);
3318 CXXCtorInitializer **baseOrMemberInitializers =
3319 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003320 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003321 NumInitializers * sizeof(CXXCtorInitializer*));
3322 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003323
John McCallef027fe2010-03-16 21:39:52 +00003324 // Constructors implicitly reference the base and member
3325 // destructors.
3326 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3327 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003328 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003329
3330 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003331}
3332
David Blaikieee000bb2013-01-17 08:49:22 +00003333static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003334 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003335 const RecordDecl *RD = RT->getDecl();
3336 if (RD->isAnonymousStructOrUnion()) {
3337 for (RecordDecl::field_iterator Field = RD->field_begin(),
3338 E = RD->field_end(); Field != E; ++Field)
3339 PopulateKeysForFields(*Field, IdealInits);
3340 return;
3341 }
Eli Friedman6347f422009-07-21 19:28:10 +00003342 }
David Blaikieee000bb2013-01-17 08:49:22 +00003343 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003344}
3345
Anders Carlssonea356fb2010-04-02 05:42:15 +00003346static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003347 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003348}
3349
Anders Carlssonea356fb2010-04-02 05:42:15 +00003350static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003351 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003352 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003353 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003354
David Blaikieee000bb2013-01-17 08:49:22 +00003355 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003356}
3357
David Blaikie93c86172013-01-17 05:26:25 +00003358static void DiagnoseBaseOrMemInitializerOrder(
3359 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3360 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003361 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003362 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003363
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003364 // Don't check initializers order unless the warning is enabled at the
3365 // location of at least one initializer.
3366 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003367 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003368 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003369 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3370 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003371 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003372 ShouldCheckOrder = true;
3373 break;
3374 }
3375 }
3376 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003377 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003378
John McCalld6ca8da2010-04-10 07:37:23 +00003379 // Build the list of bases and members in the order that they'll
3380 // actually be initialized. The explicit initializers should be in
3381 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003382 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003383
Anders Carlsson071d6102010-04-02 03:38:04 +00003384 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3385
John McCalld6ca8da2010-04-10 07:37:23 +00003386 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003387 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003388 ClassDecl->vbases_begin(),
3389 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003390 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003391
John McCalld6ca8da2010-04-10 07:37:23 +00003392 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003393 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003394 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003395 if (Base->isVirtual())
3396 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003397 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003398 }
Mike Stump1eb44332009-09-09 15:08:12 +00003399
John McCalld6ca8da2010-04-10 07:37:23 +00003400 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003401 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003402 E = ClassDecl->field_end(); Field != E; ++Field) {
3403 if (Field->isUnnamedBitfield())
3404 continue;
3405
David Blaikieee000bb2013-01-17 08:49:22 +00003406 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003407 }
3408
John McCalld6ca8da2010-04-10 07:37:23 +00003409 unsigned NumIdealInits = IdealInitKeys.size();
3410 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003411
Sean Huntcbb67482011-01-08 20:30:50 +00003412 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003413 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003414 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003415 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003416
3417 // Scan forward to try to find this initializer in the idealized
3418 // initializers list.
3419 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3420 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003421 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003422
3423 // If we didn't find this initializer, it must be because we
3424 // scanned past it on a previous iteration. That can only
3425 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003426 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003427 Sema::SemaDiagnosticBuilder D =
3428 SemaRef.Diag(PrevInit->getSourceLocation(),
3429 diag::warn_initializer_out_of_order);
3430
Francois Pichet00eb3f92010-12-04 09:14:42 +00003431 if (PrevInit->isAnyMemberInitializer())
3432 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003433 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003434 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003435
Francois Pichet00eb3f92010-12-04 09:14:42 +00003436 if (Init->isAnyMemberInitializer())
3437 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003438 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003439 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003440
3441 // Move back to the initializer's location in the ideal list.
3442 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3443 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003444 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003445
3446 assert(IdealIndex != NumIdealInits &&
3447 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003448 }
John McCalld6ca8da2010-04-10 07:37:23 +00003449
3450 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003451 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003452}
3453
John McCall3c3ccdb2010-04-10 09:28:51 +00003454namespace {
3455bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003456 CXXCtorInitializer *Init,
3457 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003458 if (!PrevInit) {
3459 PrevInit = Init;
3460 return false;
3461 }
3462
Douglas Gregordc392c12013-03-25 23:28:23 +00003463 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003464 S.Diag(Init->getSourceLocation(),
3465 diag::err_multiple_mem_initialization)
3466 << Field->getDeclName()
3467 << Init->getSourceRange();
3468 else {
John McCallf4c73712011-01-19 06:33:43 +00003469 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003470 assert(BaseClass && "neither field nor base");
3471 S.Diag(Init->getSourceLocation(),
3472 diag::err_multiple_base_initialization)
3473 << QualType(BaseClass, 0)
3474 << Init->getSourceRange();
3475 }
3476 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3477 << 0 << PrevInit->getSourceRange();
3478
3479 return true;
3480}
3481
Sean Huntcbb67482011-01-08 20:30:50 +00003482typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003483typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3484
3485bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003486 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003487 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003488 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003489 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003490 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003491
3492 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003493 if (Parent->isUnion()) {
3494 UnionEntry &En = Unions[Parent];
3495 if (En.first && En.first != Child) {
3496 S.Diag(Init->getSourceLocation(),
3497 diag::err_multiple_mem_union_initialization)
3498 << Field->getDeclName()
3499 << Init->getSourceRange();
3500 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3501 << 0 << En.second->getSourceRange();
3502 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003503 }
3504 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003505 En.first = Child;
3506 En.second = Init;
3507 }
David Blaikie6fe29652011-11-17 06:01:57 +00003508 if (!Parent->isAnonymousStructOrUnion())
3509 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003510 }
3511
3512 Child = Parent;
3513 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003514 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003515
3516 return false;
3517}
3518}
3519
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003520/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003521void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003522 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003523 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003524 bool AnyErrors) {
3525 if (!ConstructorDecl)
3526 return;
3527
3528 AdjustDeclIfTemplate(ConstructorDecl);
3529
3530 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003531 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003532
3533 if (!Constructor) {
3534 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3535 return;
3536 }
3537
John McCall3c3ccdb2010-04-10 09:28:51 +00003538 // Mapping for the duplicate initializers check.
3539 // For member initializers, this is keyed with a FieldDecl*.
3540 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003541 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003542
3543 // Mapping for the inconsistent anonymous-union initializers check.
3544 RedundantUnionMap MemberUnions;
3545
Anders Carlssonea356fb2010-04-02 05:42:15 +00003546 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003547 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003548 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003549
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003550 // Set the source order index.
3551 Init->setSourceOrder(i);
3552
Francois Pichet00eb3f92010-12-04 09:14:42 +00003553 if (Init->isAnyMemberInitializer()) {
3554 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003555 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3556 CheckRedundantUnionInit(*this, Init, MemberUnions))
3557 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003558 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003559 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3560 if (CheckRedundantInit(*this, Init, Members[Key]))
3561 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003562 } else {
3563 assert(Init->isDelegatingInitializer());
3564 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003565 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003566 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003567 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003568 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003569 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003570 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003571 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003572 // Return immediately as the initializer is set.
3573 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003574 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003575 }
3576
Anders Carlssonea356fb2010-04-02 05:42:15 +00003577 if (HadError)
3578 return;
3579
David Blaikie93c86172013-01-17 05:26:25 +00003580 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003581
David Blaikie93c86172013-01-17 05:26:25 +00003582 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003583}
3584
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003585void
John McCallef027fe2010-03-16 21:39:52 +00003586Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3587 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003588 // Ignore dependent contexts. Also ignore unions, since their members never
3589 // have destructors implicitly called.
3590 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003591 return;
John McCall58e6f342010-03-16 05:22:47 +00003592
3593 // FIXME: all the access-control diagnostics are positioned on the
3594 // field/base declaration. That's probably good; that said, the
3595 // user might reasonably want to know why the destructor is being
3596 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003597
Anders Carlsson9f853df2009-11-17 04:44:12 +00003598 // Non-static data members.
3599 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3600 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003601 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003602 if (Field->isInvalidDecl())
3603 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003604
3605 // Don't destroy incomplete or zero-length arrays.
3606 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3607 continue;
3608
Anders Carlsson9f853df2009-11-17 04:44:12 +00003609 QualType FieldType = Context.getBaseElementType(Field->getType());
3610
3611 const RecordType* RT = FieldType->getAs<RecordType>();
3612 if (!RT)
3613 continue;
3614
3615 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003616 if (FieldClassDecl->isInvalidDecl())
3617 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003618 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003619 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003620 // The destructor for an implicit anonymous union member is never invoked.
3621 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3622 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003623
Douglas Gregordb89f282010-07-01 22:47:18 +00003624 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003625 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003626 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003627 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003628 << Field->getDeclName()
3629 << FieldType);
3630
Eli Friedman5f2987c2012-02-02 03:46:19 +00003631 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003632 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003633 }
3634
John McCall58e6f342010-03-16 05:22:47 +00003635 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3636
Anders Carlsson9f853df2009-11-17 04:44:12 +00003637 // Bases.
3638 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3639 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003640 // Bases are always records in a well-formed non-dependent class.
3641 const RecordType *RT = Base->getType()->getAs<RecordType>();
3642
3643 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003644 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003645 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003646
John McCall58e6f342010-03-16 05:22:47 +00003647 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003648 // If our base class is invalid, we probably can't get its dtor anyway.
3649 if (BaseClassDecl->isInvalidDecl())
3650 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003651 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003652 continue;
John McCall58e6f342010-03-16 05:22:47 +00003653
Douglas Gregordb89f282010-07-01 22:47:18 +00003654 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003655 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003656
3657 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003658 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003659 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003660 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003661 << Base->getSourceRange(),
3662 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003663
Eli Friedman5f2987c2012-02-02 03:46:19 +00003664 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003665 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003666 }
3667
3668 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003669 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3670 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003671
3672 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003673 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003674
3675 // Ignore direct virtual bases.
3676 if (DirectVirtualBases.count(RT))
3677 continue;
3678
John McCall58e6f342010-03-16 05:22:47 +00003679 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003680 // If our base class is invalid, we probably can't get its dtor anyway.
3681 if (BaseClassDecl->isInvalidDecl())
3682 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003683 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003684 continue;
John McCall58e6f342010-03-16 05:22:47 +00003685
Douglas Gregordb89f282010-07-01 22:47:18 +00003686 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003687 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003688 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003689 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003690 << VBase->getType(),
3691 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003692
Eli Friedman5f2987c2012-02-02 03:46:19 +00003693 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003694 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003695 }
3696}
3697
John McCalld226f652010-08-21 09:40:31 +00003698void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003699 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003700 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003701
Mike Stump1eb44332009-09-09 15:08:12 +00003702 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003703 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003704 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003705}
3706
Mike Stump1eb44332009-09-09 15:08:12 +00003707bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003708 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003709 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3710 unsigned DiagID;
3711 AbstractDiagSelID SelID;
3712
3713 public:
3714 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3715 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3716
3717 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003718 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003719 if (SelID == -1)
3720 S.Diag(Loc, DiagID) << T;
3721 else
3722 S.Diag(Loc, DiagID) << SelID << T;
3723 }
3724 } Diagnoser(DiagID, SelID);
3725
3726 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003727}
3728
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003729bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003730 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003731 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003732 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003733
Anders Carlsson11f21a02009-03-23 19:10:31 +00003734 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003735 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003736
Ted Kremenek6217b802009-07-29 21:53:49 +00003737 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003738 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003739 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003740 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003741
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003742 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003743 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003744 }
Mike Stump1eb44332009-09-09 15:08:12 +00003745
Ted Kremenek6217b802009-07-29 21:53:49 +00003746 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003747 if (!RT)
3748 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003749
John McCall86ff3082010-02-04 22:26:26 +00003750 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003751
John McCall94c3b562010-08-18 09:41:07 +00003752 // We can't answer whether something is abstract until it has a
3753 // definition. If it's currently being defined, we'll walk back
3754 // over all the declarations when we have a full definition.
3755 const CXXRecordDecl *Def = RD->getDefinition();
3756 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003757 return false;
3758
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003759 if (!RD->isAbstract())
3760 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003761
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003762 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003763 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003764
John McCall94c3b562010-08-18 09:41:07 +00003765 return true;
3766}
3767
3768void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3769 // Check if we've already emitted the list of pure virtual functions
3770 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003771 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003772 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003773
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003774 CXXFinalOverriderMap FinalOverriders;
3775 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003776
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003777 // Keep a set of seen pure methods so we won't diagnose the same method
3778 // more than once.
3779 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3780
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003781 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3782 MEnd = FinalOverriders.end();
3783 M != MEnd;
3784 ++M) {
3785 for (OverridingMethods::iterator SO = M->second.begin(),
3786 SOEnd = M->second.end();
3787 SO != SOEnd; ++SO) {
3788 // C++ [class.abstract]p4:
3789 // A class is abstract if it contains or inherits at least one
3790 // pure virtual function for which the final overrider is pure
3791 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003792
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003793 //
3794 if (SO->second.size() != 1)
3795 continue;
3796
3797 if (!SO->second.front().Method->isPure())
3798 continue;
3799
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003800 if (!SeenPureMethods.insert(SO->second.front().Method))
3801 continue;
3802
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003803 Diag(SO->second.front().Method->getLocation(),
3804 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003805 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003806 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003807 }
3808
3809 if (!PureVirtualClassDiagSet)
3810 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3811 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003812}
3813
Anders Carlsson8211eff2009-03-24 01:19:16 +00003814namespace {
John McCall94c3b562010-08-18 09:41:07 +00003815struct AbstractUsageInfo {
3816 Sema &S;
3817 CXXRecordDecl *Record;
3818 CanQualType AbstractType;
3819 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003820
John McCall94c3b562010-08-18 09:41:07 +00003821 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3822 : S(S), Record(Record),
3823 AbstractType(S.Context.getCanonicalType(
3824 S.Context.getTypeDeclType(Record))),
3825 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003826
John McCall94c3b562010-08-18 09:41:07 +00003827 void DiagnoseAbstractType() {
3828 if (Invalid) return;
3829 S.DiagnoseAbstractType(Record);
3830 Invalid = true;
3831 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003832
John McCall94c3b562010-08-18 09:41:07 +00003833 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3834};
3835
3836struct CheckAbstractUsage {
3837 AbstractUsageInfo &Info;
3838 const NamedDecl *Ctx;
3839
3840 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3841 : Info(Info), Ctx(Ctx) {}
3842
3843 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3844 switch (TL.getTypeLocClass()) {
3845#define ABSTRACT_TYPELOC(CLASS, PARENT)
3846#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003847 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003848#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003849 }
John McCall94c3b562010-08-18 09:41:07 +00003850 }
Mike Stump1eb44332009-09-09 15:08:12 +00003851
John McCall94c3b562010-08-18 09:41:07 +00003852 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3853 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3854 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003855 if (!TL.getArg(I))
3856 continue;
3857
John McCall94c3b562010-08-18 09:41:07 +00003858 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3859 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003860 }
John McCall94c3b562010-08-18 09:41:07 +00003861 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003862
John McCall94c3b562010-08-18 09:41:07 +00003863 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3864 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3865 }
Mike Stump1eb44332009-09-09 15:08:12 +00003866
John McCall94c3b562010-08-18 09:41:07 +00003867 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3868 // Visit the type parameters from a permissive context.
3869 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3870 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3871 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3872 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3873 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3874 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003875 }
John McCall94c3b562010-08-18 09:41:07 +00003876 }
Mike Stump1eb44332009-09-09 15:08:12 +00003877
John McCall94c3b562010-08-18 09:41:07 +00003878 // Visit pointee types from a permissive context.
3879#define CheckPolymorphic(Type) \
3880 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3881 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3882 }
3883 CheckPolymorphic(PointerTypeLoc)
3884 CheckPolymorphic(ReferenceTypeLoc)
3885 CheckPolymorphic(MemberPointerTypeLoc)
3886 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003887 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003888
John McCall94c3b562010-08-18 09:41:07 +00003889 /// Handle all the types we haven't given a more specific
3890 /// implementation for above.
3891 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3892 // Every other kind of type that we haven't called out already
3893 // that has an inner type is either (1) sugar or (2) contains that
3894 // inner type in some way as a subobject.
3895 if (TypeLoc Next = TL.getNextTypeLoc())
3896 return Visit(Next, Sel);
3897
3898 // If there's no inner type and we're in a permissive context,
3899 // don't diagnose.
3900 if (Sel == Sema::AbstractNone) return;
3901
3902 // Check whether the type matches the abstract type.
3903 QualType T = TL.getType();
3904 if (T->isArrayType()) {
3905 Sel = Sema::AbstractArrayType;
3906 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003907 }
John McCall94c3b562010-08-18 09:41:07 +00003908 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3909 if (CT != Info.AbstractType) return;
3910
3911 // It matched; do some magic.
3912 if (Sel == Sema::AbstractArrayType) {
3913 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3914 << T << TL.getSourceRange();
3915 } else {
3916 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3917 << Sel << T << TL.getSourceRange();
3918 }
3919 Info.DiagnoseAbstractType();
3920 }
3921};
3922
3923void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3924 Sema::AbstractDiagSelID Sel) {
3925 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3926}
3927
3928}
3929
3930/// Check for invalid uses of an abstract type in a method declaration.
3931static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3932 CXXMethodDecl *MD) {
3933 // No need to do the check on definitions, which require that
3934 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003935 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003936 return;
3937
3938 // For safety's sake, just ignore it if we don't have type source
3939 // information. This should never happen for non-implicit methods,
3940 // but...
3941 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3942 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3943}
3944
3945/// Check for invalid uses of an abstract type within a class definition.
3946static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3947 CXXRecordDecl *RD) {
3948 for (CXXRecordDecl::decl_iterator
3949 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3950 Decl *D = *I;
3951 if (D->isImplicit()) continue;
3952
3953 // Methods and method templates.
3954 if (isa<CXXMethodDecl>(D)) {
3955 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3956 } else if (isa<FunctionTemplateDecl>(D)) {
3957 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3958 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3959
3960 // Fields and static variables.
3961 } else if (isa<FieldDecl>(D)) {
3962 FieldDecl *FD = cast<FieldDecl>(D);
3963 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3964 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3965 } else if (isa<VarDecl>(D)) {
3966 VarDecl *VD = cast<VarDecl>(D);
3967 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3968 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3969
3970 // Nested classes and class templates.
3971 } else if (isa<CXXRecordDecl>(D)) {
3972 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3973 } else if (isa<ClassTemplateDecl>(D)) {
3974 CheckAbstractClassUsage(Info,
3975 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3976 }
3977 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003978}
3979
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003980/// \brief Perform semantic checks on a class definition that has been
3981/// completing, introducing implicitly-declared members, checking for
3982/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003983void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003984 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003985 return;
3986
John McCall94c3b562010-08-18 09:41:07 +00003987 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3988 AbstractUsageInfo Info(*this, Record);
3989 CheckAbstractClassUsage(Info, Record);
3990 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003991
3992 // If this is not an aggregate type and has no user-declared constructor,
3993 // complain about any non-static data members of reference or const scalar
3994 // type, since they will never get initializers.
3995 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003996 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3997 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003998 bool Complained = false;
3999 for (RecordDecl::field_iterator F = Record->field_begin(),
4000 FEnd = Record->field_end();
4001 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004002 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004003 continue;
4004
Douglas Gregor325e5932010-04-15 00:00:53 +00004005 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004006 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004007 if (!Complained) {
4008 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4009 << Record->getTagKind() << Record;
4010 Complained = true;
4011 }
4012
4013 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4014 << F->getType()->isReferenceType()
4015 << F->getDeclName();
4016 }
4017 }
4018 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004019
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004020 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004021 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004022
4023 if (Record->getIdentifier()) {
4024 // C++ [class.mem]p13:
4025 // If T is the name of a class, then each of the following shall have a
4026 // name different from T:
4027 // - every member of every anonymous union that is a member of class T.
4028 //
4029 // C++ [class.mem]p14:
4030 // In addition, if class T has a user-declared constructor (12.1), every
4031 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004032 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4033 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4034 ++I) {
4035 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004036 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4037 isa<IndirectFieldDecl>(D)) {
4038 Diag(D->getLocation(), diag::err_member_name_of_class)
4039 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004040 break;
4041 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004042 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004043 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004044
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004045 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004046 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004047 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004048 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004049 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4050 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4051 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004052
David Blaikieb6b5b972012-09-21 03:21:07 +00004053 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4054 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4055 DiagnoseAbstractType(Record);
4056 }
4057
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004058 if (!Record->isDependentType()) {
4059 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4060 MEnd = Record->method_end();
4061 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004062 // See if a method overloads virtual methods in a base
4063 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004064 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004065 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004066
4067 // Check whether the explicitly-defaulted special members are valid.
4068 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4069 CheckExplicitlyDefaultedSpecialMember(*M);
4070
4071 // For an explicitly defaulted or deleted special member, we defer
4072 // determining triviality until the class is complete. That time is now!
4073 if (!M->isImplicit() && !M->isUserProvided()) {
4074 CXXSpecialMember CSM = getSpecialMember(*M);
4075 if (CSM != CXXInvalid) {
4076 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4077
4078 // Inform the class that we've finished declaring this member.
4079 Record->finishedDefaultedOrDeletedMember(*M);
4080 }
4081 }
4082 }
4083 }
4084
4085 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4086 // function that is not a constructor declares that member function to be
4087 // const. [...] The class of which that function is a member shall be
4088 // a literal type.
4089 //
4090 // If the class has virtual bases, any constexpr members will already have
4091 // been diagnosed by the checks performed on the member declaration, so
4092 // suppress this (less useful) diagnostic.
4093 //
4094 // We delay this until we know whether an explicitly-defaulted (or deleted)
4095 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004096 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004097 !Record->isLiteral() && !Record->getNumVBases()) {
4098 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4099 MEnd = Record->method_end();
4100 M != MEnd; ++M) {
4101 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4102 switch (Record->getTemplateSpecializationKind()) {
4103 case TSK_ImplicitInstantiation:
4104 case TSK_ExplicitInstantiationDeclaration:
4105 case TSK_ExplicitInstantiationDefinition:
4106 // If a template instantiates to a non-literal type, but its members
4107 // instantiate to constexpr functions, the template is technically
4108 // ill-formed, but we allow it for sanity.
4109 continue;
4110
4111 case TSK_Undeclared:
4112 case TSK_ExplicitSpecialization:
4113 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4114 diag::err_constexpr_method_non_literal);
4115 break;
4116 }
4117
4118 // Only produce one error per class.
4119 break;
4120 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004121 }
4122 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004123
Richard Smith07b0fdc2013-03-18 21:12:30 +00004124 // Declare inheriting constructors. We do this eagerly here because:
4125 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004126 // constructors from different classes.
4127 // - The lazy declaration of the other implicit constructors is so as to not
4128 // waste space and performance on classes that are not meant to be
4129 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004130 // have inheriting constructors.
4131 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004132}
4133
Richard Smith7756afa2012-06-10 05:43:50 +00004134/// Is the special member function which would be selected to perform the
4135/// specified operation on the specified class type a constexpr constructor?
4136static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4137 Sema::CXXSpecialMember CSM,
4138 bool ConstArg) {
4139 Sema::SpecialMemberOverloadResult *SMOR =
4140 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4141 false, false, false, false);
4142 if (!SMOR || !SMOR->getMethod())
4143 // A constructor we wouldn't select can't be "involved in initializing"
4144 // anything.
4145 return true;
4146 return SMOR->getMethod()->isConstexpr();
4147}
4148
4149/// Determine whether the specified special member function would be constexpr
4150/// if it were implicitly defined.
4151static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4152 Sema::CXXSpecialMember CSM,
4153 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004154 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004155 return false;
4156
4157 // C++11 [dcl.constexpr]p4:
4158 // In the definition of a constexpr constructor [...]
4159 switch (CSM) {
4160 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004161 // Since default constructor lookup is essentially trivial (and cannot
4162 // involve, for instance, template instantiation), we compute whether a
4163 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4164 //
4165 // This is important for performance; we need to know whether the default
4166 // constructor is constexpr to determine whether the type is a literal type.
4167 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4168
Richard Smith7756afa2012-06-10 05:43:50 +00004169 case Sema::CXXCopyConstructor:
4170 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004171 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004172 break;
4173
4174 case Sema::CXXCopyAssignment:
4175 case Sema::CXXMoveAssignment:
4176 case Sema::CXXDestructor:
4177 case Sema::CXXInvalid:
4178 return false;
4179 }
4180
4181 // -- if the class is a non-empty union, or for each non-empty anonymous
4182 // union member of a non-union class, exactly one non-static data member
4183 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004184 //
4185 // If we squint, this is guaranteed, since exactly one non-static data member
4186 // will be initialized (if the constructor isn't deleted), we just don't know
4187 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004188 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004189 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004190
4191 // -- the class shall not have any virtual base classes;
4192 if (ClassDecl->getNumVBases())
4193 return false;
4194
4195 // -- every constructor involved in initializing [...] base class
4196 // sub-objects shall be a constexpr constructor;
4197 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4198 BEnd = ClassDecl->bases_end();
4199 B != BEnd; ++B) {
4200 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4201 if (!BaseType) continue;
4202
4203 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4204 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4205 return false;
4206 }
4207
4208 // -- every constructor involved in initializing non-static data members
4209 // [...] shall be a constexpr constructor;
4210 // -- every non-static data member and base class sub-object shall be
4211 // initialized
4212 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4213 FEnd = ClassDecl->field_end();
4214 F != FEnd; ++F) {
4215 if (F->isInvalidDecl())
4216 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004217 if (const RecordType *RecordTy =
4218 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004219 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4220 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4221 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004222 }
4223 }
4224
4225 // All OK, it's constexpr!
4226 return true;
4227}
4228
Richard Smithb9d0b762012-07-27 04:22:15 +00004229static Sema::ImplicitExceptionSpecification
4230computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4231 switch (S.getSpecialMember(MD)) {
4232 case Sema::CXXDefaultConstructor:
4233 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4234 case Sema::CXXCopyConstructor:
4235 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4236 case Sema::CXXCopyAssignment:
4237 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4238 case Sema::CXXMoveConstructor:
4239 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4240 case Sema::CXXMoveAssignment:
4241 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4242 case Sema::CXXDestructor:
4243 return S.ComputeDefaultedDtorExceptionSpec(MD);
4244 case Sema::CXXInvalid:
4245 break;
4246 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004247 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4248 "only special members have implicit exception specs");
4249 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004250}
4251
Richard Smithdd25e802012-07-30 23:48:14 +00004252static void
4253updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4254 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4255 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4256 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004257 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4258 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004259}
4260
Richard Smithb9d0b762012-07-27 04:22:15 +00004261void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4262 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4263 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4264 return;
4265
Richard Smithdd25e802012-07-30 23:48:14 +00004266 // Evaluate the exception specification.
4267 ImplicitExceptionSpecification ExceptSpec =
4268 computeImplicitExceptionSpec(*this, Loc, MD);
4269
4270 // Update the type of the special member to use it.
4271 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4272
4273 // A user-provided destructor can be defined outside the class. When that
4274 // happens, be sure to update the exception specification on both
4275 // declarations.
4276 const FunctionProtoType *CanonicalFPT =
4277 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4278 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4279 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4280 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004281}
4282
Richard Smith3003e1d2012-05-15 04:39:51 +00004283void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4284 CXXRecordDecl *RD = MD->getParent();
4285 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004286
Richard Smith3003e1d2012-05-15 04:39:51 +00004287 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4288 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004289
4290 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004291 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004292 bool First = MD == MD->getCanonicalDecl();
4293
4294 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004295
4296 // C++11 [dcl.fct.def.default]p1:
4297 // A function that is explicitly defaulted shall
4298 // -- be a special member function (checked elsewhere),
4299 // -- have the same type (except for ref-qualifiers, and except that a
4300 // copy operation can take a non-const reference) as an implicit
4301 // declaration, and
4302 // -- not have default arguments.
4303 unsigned ExpectedParams = 1;
4304 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4305 ExpectedParams = 0;
4306 if (MD->getNumParams() != ExpectedParams) {
4307 // This also checks for default arguments: a copy or move constructor with a
4308 // default argument is classified as a default constructor, and assignment
4309 // operations and destructors can't have default arguments.
4310 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4311 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004312 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004313 } else if (MD->isVariadic()) {
4314 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4315 << CSM << MD->getSourceRange();
4316 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004317 }
4318
Richard Smith3003e1d2012-05-15 04:39:51 +00004319 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004320
Richard Smith7756afa2012-06-10 05:43:50 +00004321 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004322 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004323 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004324 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004325 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004326
Richard Smith3003e1d2012-05-15 04:39:51 +00004327 QualType ReturnType = Context.VoidTy;
4328 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4329 // Check for return type matching.
4330 ReturnType = Type->getResultType();
4331 QualType ExpectedReturnType =
4332 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4333 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4334 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4335 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4336 HadError = true;
4337 }
4338
4339 // A defaulted special member cannot have cv-qualifiers.
4340 if (Type->getTypeQuals()) {
4341 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4342 << (CSM == CXXMoveAssignment);
4343 HadError = true;
4344 }
4345 }
4346
4347 // Check for parameter type matching.
4348 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004349 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004350 if (ExpectedParams && ArgType->isReferenceType()) {
4351 // Argument must be reference to possibly-const T.
4352 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004353 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004354
4355 if (ReferentType.isVolatileQualified()) {
4356 Diag(MD->getLocation(),
4357 diag::err_defaulted_special_member_volatile_param) << CSM;
4358 HadError = true;
4359 }
4360
Richard Smith7756afa2012-06-10 05:43:50 +00004361 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004362 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4363 Diag(MD->getLocation(),
4364 diag::err_defaulted_special_member_copy_const_param)
4365 << (CSM == CXXCopyAssignment);
4366 // FIXME: Explain why this special member can't be const.
4367 } else {
4368 Diag(MD->getLocation(),
4369 diag::err_defaulted_special_member_move_const_param)
4370 << (CSM == CXXMoveAssignment);
4371 }
4372 HadError = true;
4373 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004374 } else if (ExpectedParams) {
4375 // A copy assignment operator can take its argument by value, but a
4376 // defaulted one cannot.
4377 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004378 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004379 HadError = true;
4380 }
Sean Huntbe631222011-05-17 20:44:43 +00004381
Richard Smith61802452011-12-22 02:22:31 +00004382 // C++11 [dcl.fct.def.default]p2:
4383 // An explicitly-defaulted function may be declared constexpr only if it
4384 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004385 // Do not apply this rule to members of class templates, since core issue 1358
4386 // makes such functions always instantiate to constexpr functions. For
4387 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004388 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4389 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004390 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4391 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4392 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004393 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004394 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004395 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004396
Richard Smith61802452011-12-22 02:22:31 +00004397 // and may have an explicit exception-specification only if it is compatible
4398 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004399 if (Type->hasExceptionSpec()) {
4400 // Delay the check if this is the first declaration of the special member,
4401 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004402 if (First) {
4403 // If the exception specification needs to be instantiated, do so now,
4404 // before we clobber it with an EST_Unevaluated specification below.
4405 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4406 InstantiateExceptionSpec(MD->getLocStart(), MD);
4407 Type = MD->getType()->getAs<FunctionProtoType>();
4408 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004409 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004410 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004411 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4412 }
Richard Smith61802452011-12-22 02:22:31 +00004413
4414 // If a function is explicitly defaulted on its first declaration,
4415 if (First) {
4416 // -- it is implicitly considered to be constexpr if the implicit
4417 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004418 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004419
Richard Smith3003e1d2012-05-15 04:39:51 +00004420 // -- it is implicitly considered to have the same exception-specification
4421 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004422 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4423 EPI.ExceptionSpecType = EST_Unevaluated;
4424 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004425 MD->setType(Context.getFunctionType(ReturnType,
4426 ArrayRef<QualType>(&ArgType,
4427 ExpectedParams),
4428 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004429 }
4430
Richard Smith3003e1d2012-05-15 04:39:51 +00004431 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004432 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004433 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004434 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004435 // C++11 [dcl.fct.def.default]p4:
4436 // [For a] user-provided explicitly-defaulted function [...] if such a
4437 // function is implicitly defined as deleted, the program is ill-formed.
4438 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4439 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004440 }
4441 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004442
Richard Smith3003e1d2012-05-15 04:39:51 +00004443 if (HadError)
4444 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004445}
4446
Richard Smith1d28caf2012-12-11 01:14:52 +00004447/// Check whether the exception specification provided for an
4448/// explicitly-defaulted special member matches the exception specification
4449/// that would have been generated for an implicit special member, per
4450/// C++11 [dcl.fct.def.default]p2.
4451void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4452 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4453 // Compute the implicit exception specification.
4454 FunctionProtoType::ExtProtoInfo EPI;
4455 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4456 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Jordan Rosebea522f2013-03-08 21:51:21 +00004457 Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004458
4459 // Ensure that it matches.
4460 CheckEquivalentExceptionSpec(
4461 PDiag(diag::err_incorrect_defaulted_exception_spec)
4462 << getSpecialMember(MD), PDiag(),
4463 ImplicitType, SourceLocation(),
4464 SpecifiedType, MD->getLocation());
4465}
4466
4467void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4468 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4469 I != N; ++I)
4470 CheckExplicitlyDefaultedMemberExceptionSpec(
4471 DelayedDefaultedMemberExceptionSpecs[I].first,
4472 DelayedDefaultedMemberExceptionSpecs[I].second);
4473
4474 DelayedDefaultedMemberExceptionSpecs.clear();
4475}
4476
Richard Smith7d5088a2012-02-18 02:02:13 +00004477namespace {
4478struct SpecialMemberDeletionInfo {
4479 Sema &S;
4480 CXXMethodDecl *MD;
4481 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004482 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004483
4484 // Properties of the special member, computed for convenience.
4485 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4486 SourceLocation Loc;
4487
4488 bool AllFieldsAreConst;
4489
4490 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004491 Sema::CXXSpecialMember CSM, bool Diagnose)
4492 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004493 IsConstructor(false), IsAssignment(false), IsMove(false),
4494 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4495 AllFieldsAreConst(true) {
4496 switch (CSM) {
4497 case Sema::CXXDefaultConstructor:
4498 case Sema::CXXCopyConstructor:
4499 IsConstructor = true;
4500 break;
4501 case Sema::CXXMoveConstructor:
4502 IsConstructor = true;
4503 IsMove = true;
4504 break;
4505 case Sema::CXXCopyAssignment:
4506 IsAssignment = true;
4507 break;
4508 case Sema::CXXMoveAssignment:
4509 IsAssignment = true;
4510 IsMove = true;
4511 break;
4512 case Sema::CXXDestructor:
4513 break;
4514 case Sema::CXXInvalid:
4515 llvm_unreachable("invalid special member kind");
4516 }
4517
4518 if (MD->getNumParams()) {
4519 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4520 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4521 }
4522 }
4523
4524 bool inUnion() const { return MD->getParent()->isUnion(); }
4525
4526 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004527 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4528 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004529 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004530 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4531 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4532 Quals = 0;
4533 return S.LookupSpecialMember(Class, CSM,
4534 ConstArg || (Quals & Qualifiers::Const),
4535 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004536 MD->getRefQualifier() == RQ_RValue,
4537 TQ & Qualifiers::Const,
4538 TQ & Qualifiers::Volatile);
4539 }
4540
Richard Smith6c4c36c2012-03-30 20:53:28 +00004541 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004542
Richard Smith6c4c36c2012-03-30 20:53:28 +00004543 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004544 bool shouldDeleteForField(FieldDecl *FD);
4545 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004546
Richard Smith517bb842012-07-18 03:51:16 +00004547 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4548 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004549 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4550 Sema::SpecialMemberOverloadResult *SMOR,
4551 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004552
4553 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004554};
4555}
4556
John McCall12d8d802012-04-09 20:53:23 +00004557/// Is the given special member inaccessible when used on the given
4558/// sub-object.
4559bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4560 CXXMethodDecl *target) {
4561 /// If we're operating on a base class, the object type is the
4562 /// type of this special member.
4563 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004564 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004565 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4566 objectTy = S.Context.getTypeDeclType(MD->getParent());
4567 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4568
4569 // If we're operating on a field, the object type is the type of the field.
4570 } else {
4571 objectTy = S.Context.getTypeDeclType(target->getParent());
4572 }
4573
4574 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4575}
4576
Richard Smith6c4c36c2012-03-30 20:53:28 +00004577/// Check whether we should delete a special member due to the implicit
4578/// definition containing a call to a special member of a subobject.
4579bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4580 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4581 bool IsDtorCallInCtor) {
4582 CXXMethodDecl *Decl = SMOR->getMethod();
4583 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4584
4585 int DiagKind = -1;
4586
4587 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4588 DiagKind = !Decl ? 0 : 1;
4589 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4590 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004591 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004592 DiagKind = 3;
4593 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4594 !Decl->isTrivial()) {
4595 // A member of a union must have a trivial corresponding special member.
4596 // As a weird special case, a destructor call from a union's constructor
4597 // must be accessible and non-deleted, but need not be trivial. Such a
4598 // destructor is never actually called, but is semantically checked as
4599 // if it were.
4600 DiagKind = 4;
4601 }
4602
4603 if (DiagKind == -1)
4604 return false;
4605
4606 if (Diagnose) {
4607 if (Field) {
4608 S.Diag(Field->getLocation(),
4609 diag::note_deleted_special_member_class_subobject)
4610 << CSM << MD->getParent() << /*IsField*/true
4611 << Field << DiagKind << IsDtorCallInCtor;
4612 } else {
4613 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4614 S.Diag(Base->getLocStart(),
4615 diag::note_deleted_special_member_class_subobject)
4616 << CSM << MD->getParent() << /*IsField*/false
4617 << Base->getType() << DiagKind << IsDtorCallInCtor;
4618 }
4619
4620 if (DiagKind == 1)
4621 S.NoteDeletedFunction(Decl);
4622 // FIXME: Explain inaccessibility if DiagKind == 3.
4623 }
4624
4625 return true;
4626}
4627
Richard Smith9a561d52012-02-26 09:11:52 +00004628/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004629/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004630bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004631 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004632 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004633
4634 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004635 // -- any direct or virtual base class, or non-static data member with no
4636 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004637 // either M has no default constructor or overload resolution as applied
4638 // to M's default constructor results in an ambiguity or in a function
4639 // that is deleted or inaccessible
4640 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4641 // -- a direct or virtual base class B that cannot be copied/moved because
4642 // overload resolution, as applied to B's corresponding special member,
4643 // results in an ambiguity or a function that is deleted or inaccessible
4644 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004645 // C++11 [class.dtor]p5:
4646 // -- any direct or virtual base class [...] has a type with a destructor
4647 // that is deleted or inaccessible
4648 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004649 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004650 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004651 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004652
Richard Smith6c4c36c2012-03-30 20:53:28 +00004653 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4654 // -- any direct or virtual base class or non-static data member has a
4655 // type with a destructor that is deleted or inaccessible
4656 if (IsConstructor) {
4657 Sema::SpecialMemberOverloadResult *SMOR =
4658 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4659 false, false, false, false, false);
4660 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4661 return true;
4662 }
4663
Richard Smith9a561d52012-02-26 09:11:52 +00004664 return false;
4665}
4666
4667/// Check whether we should delete a special member function due to the class
4668/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004669bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004670 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004671 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004672}
4673
4674/// Check whether we should delete a special member function due to the class
4675/// having a particular non-static data member.
4676bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4677 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4678 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4679
4680 if (CSM == Sema::CXXDefaultConstructor) {
4681 // For a default constructor, all references must be initialized in-class
4682 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004683 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4684 if (Diagnose)
4685 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4686 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004687 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004688 }
Richard Smith79363f52012-02-27 06:07:25 +00004689 // C++11 [class.ctor]p5: any non-variant non-static data member of
4690 // const-qualified type (or array thereof) with no
4691 // brace-or-equal-initializer does not have a user-provided default
4692 // constructor.
4693 if (!inUnion() && FieldType.isConstQualified() &&
4694 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004695 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4696 if (Diagnose)
4697 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004698 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004699 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004700 }
4701
4702 if (inUnion() && !FieldType.isConstQualified())
4703 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004704 } else if (CSM == Sema::CXXCopyConstructor) {
4705 // For a copy constructor, data members must not be of rvalue reference
4706 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004707 if (FieldType->isRValueReferenceType()) {
4708 if (Diagnose)
4709 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4710 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004711 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004712 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004713 } else if (IsAssignment) {
4714 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004715 if (FieldType->isReferenceType()) {
4716 if (Diagnose)
4717 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4718 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004719 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004720 }
4721 if (!FieldRecord && FieldType.isConstQualified()) {
4722 // C++11 [class.copy]p23:
4723 // -- a non-static data member of const non-class type (or array thereof)
4724 if (Diagnose)
4725 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004726 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004727 return true;
4728 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004729 }
4730
4731 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004732 // Some additional restrictions exist on the variant members.
4733 if (!inUnion() && FieldRecord->isUnion() &&
4734 FieldRecord->isAnonymousStructOrUnion()) {
4735 bool AllVariantFieldsAreConst = true;
4736
Richard Smithdf8dc862012-03-29 19:00:10 +00004737 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004738 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4739 UE = FieldRecord->field_end();
4740 UI != UE; ++UI) {
4741 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004742
4743 if (!UnionFieldType.isConstQualified())
4744 AllVariantFieldsAreConst = false;
4745
Richard Smith9a561d52012-02-26 09:11:52 +00004746 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4747 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004748 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4749 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004750 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004751 }
4752
4753 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004754 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004755 FieldRecord->field_begin() != FieldRecord->field_end()) {
4756 if (Diagnose)
4757 S.Diag(FieldRecord->getLocation(),
4758 diag::note_deleted_default_ctor_all_const)
4759 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004760 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004761 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004762
Richard Smithdf8dc862012-03-29 19:00:10 +00004763 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004764 // This is technically non-conformant, but sanity demands it.
4765 return false;
4766 }
4767
Richard Smith517bb842012-07-18 03:51:16 +00004768 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4769 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004770 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004771 }
4772
4773 return false;
4774}
4775
4776/// C++11 [class.ctor] p5:
4777/// A defaulted default constructor for a class X is defined as deleted if
4778/// X is a union and all of its variant members are of const-qualified type.
4779bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004780 // This is a silly definition, because it gives an empty union a deleted
4781 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004782 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4783 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4784 if (Diagnose)
4785 S.Diag(MD->getParent()->getLocation(),
4786 diag::note_deleted_default_ctor_all_const)
4787 << MD->getParent() << /*not anonymous union*/0;
4788 return true;
4789 }
4790 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004791}
4792
4793/// Determine whether a defaulted special member function should be defined as
4794/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4795/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004796bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4797 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004798 if (MD->isInvalidDecl())
4799 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004800 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004801 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004802 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004803 return false;
4804
Richard Smith7d5088a2012-02-18 02:02:13 +00004805 // C++11 [expr.lambda.prim]p19:
4806 // The closure type associated with a lambda-expression has a
4807 // deleted (8.4.3) default constructor and a deleted copy
4808 // assignment operator.
4809 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004810 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4811 if (Diagnose)
4812 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004813 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004814 }
4815
Richard Smith5bdaac52012-04-02 20:59:25 +00004816 // For an anonymous struct or union, the copy and assignment special members
4817 // will never be used, so skip the check. For an anonymous union declared at
4818 // namespace scope, the constructor and destructor are used.
4819 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4820 RD->isAnonymousStructOrUnion())
4821 return false;
4822
Richard Smith6c4c36c2012-03-30 20:53:28 +00004823 // C++11 [class.copy]p7, p18:
4824 // If the class definition declares a move constructor or move assignment
4825 // operator, an implicitly declared copy constructor or copy assignment
4826 // operator is defined as deleted.
4827 if (MD->isImplicit() &&
4828 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4829 CXXMethodDecl *UserDeclaredMove = 0;
4830
4831 // In Microsoft mode, a user-declared move only causes the deletion of the
4832 // corresponding copy operation, not both copy operations.
4833 if (RD->hasUserDeclaredMoveConstructor() &&
4834 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4835 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004836
4837 // Find any user-declared move constructor.
4838 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4839 E = RD->ctor_end(); I != E; ++I) {
4840 if (I->isMoveConstructor()) {
4841 UserDeclaredMove = *I;
4842 break;
4843 }
4844 }
Richard Smith1c931be2012-04-02 18:40:40 +00004845 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004846 } else if (RD->hasUserDeclaredMoveAssignment() &&
4847 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4848 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004849
4850 // Find any user-declared move assignment operator.
4851 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4852 E = RD->method_end(); I != E; ++I) {
4853 if (I->isMoveAssignmentOperator()) {
4854 UserDeclaredMove = *I;
4855 break;
4856 }
4857 }
Richard Smith1c931be2012-04-02 18:40:40 +00004858 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004859 }
4860
4861 if (UserDeclaredMove) {
4862 Diag(UserDeclaredMove->getLocation(),
4863 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004864 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004865 << UserDeclaredMove->isMoveAssignmentOperator();
4866 return true;
4867 }
4868 }
Sean Hunte16da072011-10-10 06:18:57 +00004869
Richard Smith5bdaac52012-04-02 20:59:25 +00004870 // Do access control from the special member function
4871 ContextRAII MethodContext(*this, MD);
4872
Richard Smith9a561d52012-02-26 09:11:52 +00004873 // C++11 [class.dtor]p5:
4874 // -- for a virtual destructor, lookup of the non-array deallocation function
4875 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004876 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004877 FunctionDecl *OperatorDelete = 0;
4878 DeclarationName Name =
4879 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4880 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004881 OperatorDelete, false)) {
4882 if (Diagnose)
4883 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004884 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004885 }
Richard Smith9a561d52012-02-26 09:11:52 +00004886 }
4887
Richard Smith6c4c36c2012-03-30 20:53:28 +00004888 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004889
Sean Huntcdee3fe2011-05-11 22:34:38 +00004890 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004891 BE = RD->bases_end(); BI != BE; ++BI)
4892 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004893 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004894 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004895
4896 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004897 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004898 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004899 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004900
4901 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004902 FE = RD->field_end(); FI != FE; ++FI)
4903 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004904 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004905 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004906
Richard Smith7d5088a2012-02-18 02:02:13 +00004907 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004908 return true;
4909
4910 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004911}
4912
Richard Smithac713512012-12-08 02:53:02 +00004913/// Perform lookup for a special member of the specified kind, and determine
4914/// whether it is trivial. If the triviality can be determined without the
4915/// lookup, skip it. This is intended for use when determining whether a
4916/// special member of a containing object is trivial, and thus does not ever
4917/// perform overload resolution for default constructors.
4918///
4919/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4920/// member that was most likely to be intended to be trivial, if any.
4921static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4922 Sema::CXXSpecialMember CSM, unsigned Quals,
4923 CXXMethodDecl **Selected) {
4924 if (Selected)
4925 *Selected = 0;
4926
4927 switch (CSM) {
4928 case Sema::CXXInvalid:
4929 llvm_unreachable("not a special member");
4930
4931 case Sema::CXXDefaultConstructor:
4932 // C++11 [class.ctor]p5:
4933 // A default constructor is trivial if:
4934 // - all the [direct subobjects] have trivial default constructors
4935 //
4936 // Note, no overload resolution is performed in this case.
4937 if (RD->hasTrivialDefaultConstructor())
4938 return true;
4939
4940 if (Selected) {
4941 // If there's a default constructor which could have been trivial, dig it
4942 // out. Otherwise, if there's any user-provided default constructor, point
4943 // to that as an example of why there's not a trivial one.
4944 CXXConstructorDecl *DefCtor = 0;
4945 if (RD->needsImplicitDefaultConstructor())
4946 S.DeclareImplicitDefaultConstructor(RD);
4947 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4948 CE = RD->ctor_end(); CI != CE; ++CI) {
4949 if (!CI->isDefaultConstructor())
4950 continue;
4951 DefCtor = *CI;
4952 if (!DefCtor->isUserProvided())
4953 break;
4954 }
4955
4956 *Selected = DefCtor;
4957 }
4958
4959 return false;
4960
4961 case Sema::CXXDestructor:
4962 // C++11 [class.dtor]p5:
4963 // A destructor is trivial if:
4964 // - all the direct [subobjects] have trivial destructors
4965 if (RD->hasTrivialDestructor())
4966 return true;
4967
4968 if (Selected) {
4969 if (RD->needsImplicitDestructor())
4970 S.DeclareImplicitDestructor(RD);
4971 *Selected = RD->getDestructor();
4972 }
4973
4974 return false;
4975
4976 case Sema::CXXCopyConstructor:
4977 // C++11 [class.copy]p12:
4978 // A copy constructor is trivial if:
4979 // - the constructor selected to copy each direct [subobject] is trivial
4980 if (RD->hasTrivialCopyConstructor()) {
4981 if (Quals == Qualifiers::Const)
4982 // We must either select the trivial copy constructor or reach an
4983 // ambiguity; no need to actually perform overload resolution.
4984 return true;
4985 } else if (!Selected) {
4986 return false;
4987 }
4988 // In C++98, we are not supposed to perform overload resolution here, but we
4989 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4990 // cases like B as having a non-trivial copy constructor:
4991 // struct A { template<typename T> A(T&); };
4992 // struct B { mutable A a; };
4993 goto NeedOverloadResolution;
4994
4995 case Sema::CXXCopyAssignment:
4996 // C++11 [class.copy]p25:
4997 // A copy assignment operator is trivial if:
4998 // - the assignment operator selected to copy each direct [subobject] is
4999 // trivial
5000 if (RD->hasTrivialCopyAssignment()) {
5001 if (Quals == Qualifiers::Const)
5002 return true;
5003 } else if (!Selected) {
5004 return false;
5005 }
5006 // In C++98, we are not supposed to perform overload resolution here, but we
5007 // treat that as a language defect.
5008 goto NeedOverloadResolution;
5009
5010 case Sema::CXXMoveConstructor:
5011 case Sema::CXXMoveAssignment:
5012 NeedOverloadResolution:
5013 Sema::SpecialMemberOverloadResult *SMOR =
5014 S.LookupSpecialMember(RD, CSM,
5015 Quals & Qualifiers::Const,
5016 Quals & Qualifiers::Volatile,
5017 /*RValueThis*/false, /*ConstThis*/false,
5018 /*VolatileThis*/false);
5019
5020 // The standard doesn't describe how to behave if the lookup is ambiguous.
5021 // We treat it as not making the member non-trivial, just like the standard
5022 // mandates for the default constructor. This should rarely matter, because
5023 // the member will also be deleted.
5024 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5025 return true;
5026
5027 if (!SMOR->getMethod()) {
5028 assert(SMOR->getKind() ==
5029 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5030 return false;
5031 }
5032
5033 // We deliberately don't check if we found a deleted special member. We're
5034 // not supposed to!
5035 if (Selected)
5036 *Selected = SMOR->getMethod();
5037 return SMOR->getMethod()->isTrivial();
5038 }
5039
5040 llvm_unreachable("unknown special method kind");
5041}
5042
Benjamin Kramera574c892013-02-15 12:30:38 +00005043static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005044 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5045 CI != CE; ++CI)
5046 if (!CI->isImplicit())
5047 return *CI;
5048
5049 // Look for constructor templates.
5050 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5051 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5052 if (CXXConstructorDecl *CD =
5053 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5054 return CD;
5055 }
5056
5057 return 0;
5058}
5059
5060/// The kind of subobject we are checking for triviality. The values of this
5061/// enumeration are used in diagnostics.
5062enum TrivialSubobjectKind {
5063 /// The subobject is a base class.
5064 TSK_BaseClass,
5065 /// The subobject is a non-static data member.
5066 TSK_Field,
5067 /// The object is actually the complete object.
5068 TSK_CompleteObject
5069};
5070
5071/// Check whether the special member selected for a given type would be trivial.
5072static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5073 QualType SubType,
5074 Sema::CXXSpecialMember CSM,
5075 TrivialSubobjectKind Kind,
5076 bool Diagnose) {
5077 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5078 if (!SubRD)
5079 return true;
5080
5081 CXXMethodDecl *Selected;
5082 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5083 Diagnose ? &Selected : 0))
5084 return true;
5085
5086 if (Diagnose) {
5087 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5088 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5089 << Kind << SubType.getUnqualifiedType();
5090 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5091 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5092 } else if (!Selected)
5093 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5094 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5095 else if (Selected->isUserProvided()) {
5096 if (Kind == TSK_CompleteObject)
5097 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5098 << Kind << SubType.getUnqualifiedType() << CSM;
5099 else {
5100 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5101 << Kind << SubType.getUnqualifiedType() << CSM;
5102 S.Diag(Selected->getLocation(), diag::note_declared_at);
5103 }
5104 } else {
5105 if (Kind != TSK_CompleteObject)
5106 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5107 << Kind << SubType.getUnqualifiedType() << CSM;
5108
5109 // Explain why the defaulted or deleted special member isn't trivial.
5110 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5111 }
5112 }
5113
5114 return false;
5115}
5116
5117/// Check whether the members of a class type allow a special member to be
5118/// trivial.
5119static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5120 Sema::CXXSpecialMember CSM,
5121 bool ConstArg, bool Diagnose) {
5122 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5123 FE = RD->field_end(); FI != FE; ++FI) {
5124 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5125 continue;
5126
5127 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5128
5129 // Pretend anonymous struct or union members are members of this class.
5130 if (FI->isAnonymousStructOrUnion()) {
5131 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5132 CSM, ConstArg, Diagnose))
5133 return false;
5134 continue;
5135 }
5136
5137 // C++11 [class.ctor]p5:
5138 // A default constructor is trivial if [...]
5139 // -- no non-static data member of its class has a
5140 // brace-or-equal-initializer
5141 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5142 if (Diagnose)
5143 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5144 return false;
5145 }
5146
5147 // Objective C ARC 4.3.5:
5148 // [...] nontrivally ownership-qualified types are [...] not trivially
5149 // default constructible, copy constructible, move constructible, copy
5150 // assignable, move assignable, or destructible [...]
5151 if (S.getLangOpts().ObjCAutoRefCount &&
5152 FieldType.hasNonTrivialObjCLifetime()) {
5153 if (Diagnose)
5154 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5155 << RD << FieldType.getObjCLifetime();
5156 return false;
5157 }
5158
5159 if (ConstArg && !FI->isMutable())
5160 FieldType.addConst();
5161 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5162 TSK_Field, Diagnose))
5163 return false;
5164 }
5165
5166 return true;
5167}
5168
5169/// Diagnose why the specified class does not have a trivial special member of
5170/// the given kind.
5171void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5172 QualType Ty = Context.getRecordType(RD);
5173 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5174 Ty.addConst();
5175
5176 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5177 TSK_CompleteObject, /*Diagnose*/true);
5178}
5179
5180/// Determine whether a defaulted or deleted special member function is trivial,
5181/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5182/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5183bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5184 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005185 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5186
5187 CXXRecordDecl *RD = MD->getParent();
5188
5189 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005190
5191 // C++11 [class.copy]p12, p25:
5192 // A [special member] is trivial if its declared parameter type is the same
5193 // as if it had been implicitly declared [...]
5194 switch (CSM) {
5195 case CXXDefaultConstructor:
5196 case CXXDestructor:
5197 // Trivial default constructors and destructors cannot have parameters.
5198 break;
5199
5200 case CXXCopyConstructor:
5201 case CXXCopyAssignment: {
5202 // Trivial copy operations always have const, non-volatile parameter types.
5203 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005204 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005205 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5206 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5207 if (Diagnose)
5208 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5209 << Param0->getSourceRange() << Param0->getType()
5210 << Context.getLValueReferenceType(
5211 Context.getRecordType(RD).withConst());
5212 return false;
5213 }
5214 break;
5215 }
5216
5217 case CXXMoveConstructor:
5218 case CXXMoveAssignment: {
5219 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005220 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005221 const RValueReferenceType *RT =
5222 Param0->getType()->getAs<RValueReferenceType>();
5223 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5224 if (Diagnose)
5225 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5226 << Param0->getSourceRange() << Param0->getType()
5227 << Context.getRValueReferenceType(Context.getRecordType(RD));
5228 return false;
5229 }
5230 break;
5231 }
5232
5233 case CXXInvalid:
5234 llvm_unreachable("not a special member");
5235 }
5236
5237 // FIXME: We require that the parameter-declaration-clause is equivalent to
5238 // that of an implicit declaration, not just that the declared parameter type
5239 // matches, in order to prevent absuridities like a function simultaneously
5240 // being a trivial copy constructor and a non-trivial default constructor.
5241 // This issue has not yet been assigned a core issue number.
5242 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5243 if (Diagnose)
5244 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5245 diag::note_nontrivial_default_arg)
5246 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5247 return false;
5248 }
5249 if (MD->isVariadic()) {
5250 if (Diagnose)
5251 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5252 return false;
5253 }
5254
5255 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5256 // A copy/move [constructor or assignment operator] is trivial if
5257 // -- the [member] selected to copy/move each direct base class subobject
5258 // is trivial
5259 //
5260 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5261 // A [default constructor or destructor] is trivial if
5262 // -- all the direct base classes have trivial [default constructors or
5263 // destructors]
5264 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5265 BE = RD->bases_end(); BI != BE; ++BI)
5266 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5267 ConstArg ? BI->getType().withConst()
5268 : BI->getType(),
5269 CSM, TSK_BaseClass, Diagnose))
5270 return false;
5271
5272 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5273 // A copy/move [constructor or assignment operator] for a class X is
5274 // trivial if
5275 // -- for each non-static data member of X that is of class type (or array
5276 // thereof), the constructor selected to copy/move that member is
5277 // trivial
5278 //
5279 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5280 // A [default constructor or destructor] is trivial if
5281 // -- for all of the non-static data members of its class that are of class
5282 // type (or array thereof), each such class has a trivial [default
5283 // constructor or destructor]
5284 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5285 return false;
5286
5287 // C++11 [class.dtor]p5:
5288 // A destructor is trivial if [...]
5289 // -- the destructor is not virtual
5290 if (CSM == CXXDestructor && MD->isVirtual()) {
5291 if (Diagnose)
5292 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5293 return false;
5294 }
5295
5296 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5297 // A [special member] for class X is trivial if [...]
5298 // -- class X has no virtual functions and no virtual base classes
5299 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5300 if (!Diagnose)
5301 return false;
5302
5303 if (RD->getNumVBases()) {
5304 // Check for virtual bases. We already know that the corresponding
5305 // member in all bases is trivial, so vbases must all be direct.
5306 CXXBaseSpecifier &BS = *RD->vbases_begin();
5307 assert(BS.isVirtual());
5308 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5309 return false;
5310 }
5311
5312 // Must have a virtual method.
5313 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5314 ME = RD->method_end(); MI != ME; ++MI) {
5315 if (MI->isVirtual()) {
5316 SourceLocation MLoc = MI->getLocStart();
5317 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5318 return false;
5319 }
5320 }
5321
5322 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5323 }
5324
5325 // Looks like it's trivial!
5326 return true;
5327}
5328
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005329/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005330namespace {
5331 struct FindHiddenVirtualMethodData {
5332 Sema *S;
5333 CXXMethodDecl *Method;
5334 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005335 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005336 };
5337}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005338
David Blaikie5f750682012-10-19 00:53:08 +00005339/// \brief Check whether any most overriden method from MD in Methods
5340static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5341 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5342 if (MD->size_overridden_methods() == 0)
5343 return Methods.count(MD->getCanonicalDecl());
5344 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5345 E = MD->end_overridden_methods();
5346 I != E; ++I)
5347 if (CheckMostOverridenMethods(*I, Methods))
5348 return true;
5349 return false;
5350}
5351
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005352/// \brief Member lookup function that determines whether a given C++
5353/// method overloads virtual methods in a base class without overriding any,
5354/// to be used with CXXRecordDecl::lookupInBases().
5355static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5356 CXXBasePath &Path,
5357 void *UserData) {
5358 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5359
5360 FindHiddenVirtualMethodData &Data
5361 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5362
5363 DeclarationName Name = Data.Method->getDeclName();
5364 assert(Name.getNameKind() == DeclarationName::Identifier);
5365
5366 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005367 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005368 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005369 !Path.Decls.empty();
5370 Path.Decls = Path.Decls.slice(1)) {
5371 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005372 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005373 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005374 foundSameNameMethod = true;
5375 // Interested only in hidden virtual methods.
5376 if (!MD->isVirtual())
5377 continue;
5378 // If the method we are checking overrides a method from its base
5379 // don't warn about the other overloaded methods.
5380 if (!Data.S->IsOverload(Data.Method, MD, false))
5381 return true;
5382 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005383 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005384 overloadedMethods.push_back(MD);
5385 }
5386 }
5387
5388 if (foundSameNameMethod)
5389 Data.OverloadedMethods.append(overloadedMethods.begin(),
5390 overloadedMethods.end());
5391 return foundSameNameMethod;
5392}
5393
David Blaikie5f750682012-10-19 00:53:08 +00005394/// \brief Add the most overriden methods from MD to Methods
5395static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5396 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5397 if (MD->size_overridden_methods() == 0)
5398 Methods.insert(MD->getCanonicalDecl());
5399 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5400 E = MD->end_overridden_methods();
5401 I != E; ++I)
5402 AddMostOverridenMethods(*I, Methods);
5403}
5404
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005405/// \brief See if a method overloads virtual methods in a base class without
5406/// overriding any.
5407void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5408 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005409 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005410 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005411 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005412 return;
5413
5414 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5415 /*bool RecordPaths=*/false,
5416 /*bool DetectVirtual=*/false);
5417 FindHiddenVirtualMethodData Data;
5418 Data.Method = MD;
5419 Data.S = this;
5420
5421 // Keep the base methods that were overriden or introduced in the subclass
5422 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005423 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5424 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5425 NamedDecl *ND = *I;
5426 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005427 ND = shad->getTargetDecl();
5428 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5429 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005430 }
5431
5432 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5433 !Data.OverloadedMethods.empty()) {
5434 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5435 << MD << (Data.OverloadedMethods.size() > 1);
5436
5437 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5438 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005439 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005440 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005441 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5442 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005443 }
5444 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005445}
5446
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005447void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005448 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005449 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005450 SourceLocation RBrac,
5451 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005452 if (!TagDecl)
5453 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005454
Douglas Gregor42af25f2009-05-11 19:58:34 +00005455 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005456
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005457 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5458 if (l->getKind() != AttributeList::AT_Visibility)
5459 continue;
5460 l->setInvalid();
5461 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5462 l->getName();
5463 }
5464
David Blaikie77b6de02011-09-22 02:58:26 +00005465 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005466 // strict aliasing violation!
5467 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005468 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005469
Douglas Gregor23c94db2010-07-02 17:43:08 +00005470 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005471 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005472}
5473
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005474/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5475/// special functions, such as the default constructor, copy
5476/// constructor, or destructor, to the given C++ class (C++
5477/// [special]p1). This routine can only be executed just before the
5478/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005479void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005480 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005481 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005482
Richard Smithbc2a35d2012-12-08 08:32:28 +00005483 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005484 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005485
Richard Smithbc2a35d2012-12-08 08:32:28 +00005486 // If the properties or semantics of the copy constructor couldn't be
5487 // determined while the class was being declared, force a declaration
5488 // of it now.
5489 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5490 DeclareImplicitCopyConstructor(ClassDecl);
5491 }
5492
Richard Smith80ad52f2013-01-02 11:42:31 +00005493 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005494 ++ASTContext::NumImplicitMoveConstructors;
5495
Richard Smithbc2a35d2012-12-08 08:32:28 +00005496 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5497 DeclareImplicitMoveConstructor(ClassDecl);
5498 }
5499
Douglas Gregora376d102010-07-02 21:50:04 +00005500 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5501 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005502
5503 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005504 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005505 // it shows up in the right place in the vtable and that we diagnose
5506 // problems with the implicit exception specification.
5507 if (ClassDecl->isDynamicClass() ||
5508 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005509 DeclareImplicitCopyAssignment(ClassDecl);
5510 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005511
Richard Smith80ad52f2013-01-02 11:42:31 +00005512 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005513 ++ASTContext::NumImplicitMoveAssignmentOperators;
5514
5515 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005516 if (ClassDecl->isDynamicClass() ||
5517 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005518 DeclareImplicitMoveAssignment(ClassDecl);
5519 }
5520
Douglas Gregor4923aa22010-07-02 20:37:36 +00005521 if (!ClassDecl->hasUserDeclaredDestructor()) {
5522 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005523
5524 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005525 // have to declare the destructor immediately. This ensures that, e.g., it
5526 // shows up in the right place in the vtable and that we diagnose problems
5527 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005528 if (ClassDecl->isDynamicClass() ||
5529 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005530 DeclareImplicitDestructor(ClassDecl);
5531 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005532}
5533
Francois Pichet8387e2a2011-04-22 22:18:13 +00005534void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5535 if (!D)
5536 return;
5537
5538 int NumParamList = D->getNumTemplateParameterLists();
5539 for (int i = 0; i < NumParamList; i++) {
5540 TemplateParameterList* Params = D->getTemplateParameterList(i);
5541 for (TemplateParameterList::iterator Param = Params->begin(),
5542 ParamEnd = Params->end();
5543 Param != ParamEnd; ++Param) {
5544 NamedDecl *Named = cast<NamedDecl>(*Param);
5545 if (Named->getDeclName()) {
5546 S->AddDecl(Named);
5547 IdResolver.AddDecl(Named);
5548 }
5549 }
5550 }
5551}
5552
John McCalld226f652010-08-21 09:40:31 +00005553void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005554 if (!D)
5555 return;
5556
5557 TemplateParameterList *Params = 0;
5558 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5559 Params = Template->getTemplateParameters();
5560 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5561 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5562 Params = PartialSpec->getTemplateParameters();
5563 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005564 return;
5565
Douglas Gregor6569d682009-05-27 23:11:45 +00005566 for (TemplateParameterList::iterator Param = Params->begin(),
5567 ParamEnd = Params->end();
5568 Param != ParamEnd; ++Param) {
5569 NamedDecl *Named = cast<NamedDecl>(*Param);
5570 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005571 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005572 IdResolver.AddDecl(Named);
5573 }
5574 }
5575}
5576
John McCalld226f652010-08-21 09:40:31 +00005577void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005578 if (!RecordD) return;
5579 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005580 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005581 PushDeclContext(S, Record);
5582}
5583
John McCalld226f652010-08-21 09:40:31 +00005584void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005585 if (!RecordD) return;
5586 PopDeclContext();
5587}
5588
Douglas Gregor72b505b2008-12-16 21:30:33 +00005589/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5590/// parsing a top-level (non-nested) C++ class, and we are now
5591/// parsing those parts of the given Method declaration that could
5592/// not be parsed earlier (C++ [class.mem]p2), such as default
5593/// arguments. This action should enter the scope of the given
5594/// Method declaration as if we had just parsed the qualified method
5595/// name. However, it should not bring the parameters into scope;
5596/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005597void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005598}
5599
5600/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5601/// C++ method declaration. We're (re-)introducing the given
5602/// function parameter into scope for use in parsing later parts of
5603/// the method declaration. For example, we could see an
5604/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005605void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005606 if (!ParamD)
5607 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005608
John McCalld226f652010-08-21 09:40:31 +00005609 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005610
5611 // If this parameter has an unparsed default argument, clear it out
5612 // to make way for the parsed default argument.
5613 if (Param->hasUnparsedDefaultArg())
5614 Param->setDefaultArg(0);
5615
John McCalld226f652010-08-21 09:40:31 +00005616 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005617 if (Param->getDeclName())
5618 IdResolver.AddDecl(Param);
5619}
5620
5621/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5622/// processing the delayed method declaration for Method. The method
5623/// declaration is now considered finished. There may be a separate
5624/// ActOnStartOfFunctionDef action later (not necessarily
5625/// immediately!) for this method, if it was also defined inside the
5626/// class body.
John McCalld226f652010-08-21 09:40:31 +00005627void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005628 if (!MethodD)
5629 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005630
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005631 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005632
John McCalld226f652010-08-21 09:40:31 +00005633 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005634
5635 // Now that we have our default arguments, check the constructor
5636 // again. It could produce additional diagnostics or affect whether
5637 // the class has implicitly-declared destructors, among other
5638 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005639 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5640 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005641
5642 // Check the default arguments, which we may have added.
5643 if (!Method->isInvalidDecl())
5644 CheckCXXDefaultArguments(Method);
5645}
5646
Douglas Gregor42a552f2008-11-05 20:51:48 +00005647/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005648/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005649/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005650/// emit diagnostics and set the invalid bit to true. In any case, the type
5651/// will be updated to reflect a well-formed type for the constructor and
5652/// returned.
5653QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005654 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005655 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005656
5657 // C++ [class.ctor]p3:
5658 // A constructor shall not be virtual (10.3) or static (9.4). A
5659 // constructor can be invoked for a const, volatile or const
5660 // volatile object. A constructor shall not be declared const,
5661 // volatile, or const volatile (9.3.2).
5662 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005663 if (!D.isInvalidType())
5664 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5665 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5666 << SourceRange(D.getIdentifierLoc());
5667 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005668 }
John McCalld931b082010-08-26 03:08:43 +00005669 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005670 if (!D.isInvalidType())
5671 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5672 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5673 << SourceRange(D.getIdentifierLoc());
5674 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005675 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005676 }
Mike Stump1eb44332009-09-09 15:08:12 +00005677
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005678 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005679 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005680 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005681 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5682 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005683 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005684 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5685 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005686 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005687 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5688 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005689 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005690 }
Mike Stump1eb44332009-09-09 15:08:12 +00005691
Douglas Gregorc938c162011-01-26 05:01:58 +00005692 // C++0x [class.ctor]p4:
5693 // A constructor shall not be declared with a ref-qualifier.
5694 if (FTI.hasRefQualifier()) {
5695 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5696 << FTI.RefQualifierIsLValueRef
5697 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5698 D.setInvalidType();
5699 }
5700
Douglas Gregor42a552f2008-11-05 20:51:48 +00005701 // Rebuild the function type "R" without any type qualifiers (in
5702 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005703 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005704 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005705 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5706 return R;
5707
5708 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5709 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005710 EPI.RefQualifier = RQ_None;
5711
Richard Smith07b0fdc2013-03-18 21:12:30 +00005712 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005713}
5714
Douglas Gregor72b505b2008-12-16 21:30:33 +00005715/// CheckConstructor - Checks a fully-formed constructor for
5716/// well-formedness, issuing any diagnostics required. Returns true if
5717/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005718void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005719 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005720 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5721 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005722 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005723
5724 // C++ [class.copy]p3:
5725 // A declaration of a constructor for a class X is ill-formed if
5726 // its first parameter is of type (optionally cv-qualified) X and
5727 // either there are no other parameters or else all other
5728 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005729 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005730 ((Constructor->getNumParams() == 1) ||
5731 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005732 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5733 Constructor->getTemplateSpecializationKind()
5734 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005735 QualType ParamType = Constructor->getParamDecl(0)->getType();
5736 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5737 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005738 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005739 const char *ConstRef
5740 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5741 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005742 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005743 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005744
5745 // FIXME: Rather that making the constructor invalid, we should endeavor
5746 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005747 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005748 }
5749 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005750}
5751
John McCall15442822010-08-04 01:04:25 +00005752/// CheckDestructor - Checks a fully-formed destructor definition for
5753/// well-formedness, issuing any diagnostics required. Returns true
5754/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005755bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005756 CXXRecordDecl *RD = Destructor->getParent();
5757
5758 if (Destructor->isVirtual()) {
5759 SourceLocation Loc;
5760
5761 if (!Destructor->isImplicit())
5762 Loc = Destructor->getLocation();
5763 else
5764 Loc = RD->getLocation();
5765
5766 // If we have a virtual destructor, look up the deallocation function
5767 FunctionDecl *OperatorDelete = 0;
5768 DeclarationName Name =
5769 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005770 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005771 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005772
Eli Friedman5f2987c2012-02-02 03:46:19 +00005773 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005774
5775 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005776 }
Anders Carlsson37909802009-11-30 21:24:50 +00005777
5778 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005779}
5780
Mike Stump1eb44332009-09-09 15:08:12 +00005781static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005782FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5783 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5784 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005785 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005786}
5787
Douglas Gregor42a552f2008-11-05 20:51:48 +00005788/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5789/// the well-formednes of the destructor declarator @p D with type @p
5790/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005791/// emit diagnostics and set the declarator to invalid. Even if this happens,
5792/// will be updated to reflect a well-formed type for the destructor and
5793/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005794QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005795 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005796 // C++ [class.dtor]p1:
5797 // [...] A typedef-name that names a class is a class-name
5798 // (7.1.3); however, a typedef-name that names a class shall not
5799 // be used as the identifier in the declarator for a destructor
5800 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005801 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005802 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005803 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005804 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005805 else if (const TemplateSpecializationType *TST =
5806 DeclaratorType->getAs<TemplateSpecializationType>())
5807 if (TST->isTypeAlias())
5808 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5809 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005810
5811 // C++ [class.dtor]p2:
5812 // A destructor is used to destroy objects of its class type. A
5813 // destructor takes no parameters, and no return type can be
5814 // specified for it (not even void). The address of a destructor
5815 // shall not be taken. A destructor shall not be static. A
5816 // destructor can be invoked for a const, volatile or const
5817 // volatile object. A destructor shall not be declared const,
5818 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005819 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005820 if (!D.isInvalidType())
5821 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5822 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005823 << SourceRange(D.getIdentifierLoc())
5824 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5825
John McCalld931b082010-08-26 03:08:43 +00005826 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005827 }
Chris Lattner65401802009-04-25 08:28:21 +00005828 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005829 // Destructors don't have return types, but the parser will
5830 // happily parse something like:
5831 //
5832 // class X {
5833 // float ~X();
5834 // };
5835 //
5836 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005837 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5838 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5839 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005840 }
Mike Stump1eb44332009-09-09 15:08:12 +00005841
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005842 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005843 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005844 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005845 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5846 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005847 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005848 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5849 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005850 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005851 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5852 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005853 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005854 }
5855
Douglas Gregorc938c162011-01-26 05:01:58 +00005856 // C++0x [class.dtor]p2:
5857 // A destructor shall not be declared with a ref-qualifier.
5858 if (FTI.hasRefQualifier()) {
5859 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5860 << FTI.RefQualifierIsLValueRef
5861 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5862 D.setInvalidType();
5863 }
5864
Douglas Gregor42a552f2008-11-05 20:51:48 +00005865 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005866 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005867 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5868
5869 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005870 FTI.freeArgs();
5871 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005872 }
5873
Mike Stump1eb44332009-09-09 15:08:12 +00005874 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005875 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005876 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005877 D.setInvalidType();
5878 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005879
5880 // Rebuild the function type "R" without any type qualifiers or
5881 // parameters (in case any of the errors above fired) and with
5882 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005883 // types.
John McCalle23cf432010-12-14 08:05:40 +00005884 if (!D.isInvalidType())
5885 return R;
5886
Douglas Gregord92ec472010-07-01 05:10:53 +00005887 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005888 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5889 EPI.Variadic = false;
5890 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005891 EPI.RefQualifier = RQ_None;
Jordan Rosebea522f2013-03-08 21:51:21 +00005892 return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005893}
5894
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005895/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5896/// well-formednes of the conversion function declarator @p D with
5897/// type @p R. If there are any errors in the declarator, this routine
5898/// will emit diagnostics and return true. Otherwise, it will return
5899/// false. Either way, the type @p R will be updated to reflect a
5900/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005901void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005902 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005903 // C++ [class.conv.fct]p1:
5904 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005905 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005906 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005907 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005908 if (!D.isInvalidType())
5909 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5910 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5911 << SourceRange(D.getIdentifierLoc());
5912 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005913 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005914 }
John McCalla3f81372010-04-13 00:04:31 +00005915
5916 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5917
Chris Lattner6e475012009-04-25 08:35:12 +00005918 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005919 // Conversion functions don't have return types, but the parser will
5920 // happily parse something like:
5921 //
5922 // class X {
5923 // float operator bool();
5924 // };
5925 //
5926 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005927 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5928 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5929 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005930 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005931 }
5932
John McCalla3f81372010-04-13 00:04:31 +00005933 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5934
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005935 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005936 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005937 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5938
5939 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005940 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005941 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005942 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005943 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005944 D.setInvalidType();
5945 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005946
John McCalla3f81372010-04-13 00:04:31 +00005947 // Diagnose "&operator bool()" and other such nonsense. This
5948 // is actually a gcc extension which we don't support.
5949 if (Proto->getResultType() != ConvType) {
5950 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5951 << Proto->getResultType();
5952 D.setInvalidType();
5953 ConvType = Proto->getResultType();
5954 }
5955
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005956 // C++ [class.conv.fct]p4:
5957 // The conversion-type-id shall not represent a function type nor
5958 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005959 if (ConvType->isArrayType()) {
5960 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5961 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005962 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005963 } else if (ConvType->isFunctionType()) {
5964 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5965 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005966 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005967 }
5968
5969 // Rebuild the function type "R" without any parameters (in case any
5970 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005971 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005972 if (D.isInvalidType())
Jordan Rosebea522f2013-03-08 21:51:21 +00005973 R = Context.getFunctionType(ConvType, ArrayRef<QualType>(),
5974 Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005975
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005976 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005977 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005978 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005979 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005980 diag::warn_cxx98_compat_explicit_conversion_functions :
5981 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005982 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005983}
5984
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005985/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5986/// the declaration of the given C++ conversion function. This routine
5987/// is responsible for recording the conversion function in the C++
5988/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005989Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005990 assert(Conversion && "Expected to receive a conversion function declaration");
5991
Douglas Gregor9d350972008-12-12 08:25:50 +00005992 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005993
5994 // Make sure we aren't redeclaring the conversion function.
5995 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005996
5997 // C++ [class.conv.fct]p1:
5998 // [...] A conversion function is never used to convert a
5999 // (possibly cv-qualified) object to the (possibly cv-qualified)
6000 // same object type (or a reference to it), to a (possibly
6001 // cv-qualified) base class of that type (or a reference to it),
6002 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006003 // FIXME: Suppress this warning if the conversion function ends up being a
6004 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006005 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006006 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006007 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006008 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006009 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6010 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006011 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006012 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006013 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6014 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006015 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006016 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006017 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006018 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006019 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006020 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006021 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006022 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006023 }
6024
Douglas Gregore80622f2010-09-29 04:25:11 +00006025 if (FunctionTemplateDecl *ConversionTemplate
6026 = Conversion->getDescribedFunctionTemplate())
6027 return ConversionTemplate;
6028
John McCalld226f652010-08-21 09:40:31 +00006029 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006030}
6031
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006032//===----------------------------------------------------------------------===//
6033// Namespace Handling
6034//===----------------------------------------------------------------------===//
6035
Richard Smithd1a55a62012-10-04 22:13:39 +00006036/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6037/// reopened.
6038static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6039 SourceLocation Loc,
6040 IdentifierInfo *II, bool *IsInline,
6041 NamespaceDecl *PrevNS) {
6042 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006043
Richard Smithc969e6a2012-10-05 01:46:25 +00006044 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6045 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6046 // inline namespaces, with the intention of bringing names into namespace std.
6047 //
6048 // We support this just well enough to get that case working; this is not
6049 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006050 if (*IsInline && II && II->getName().startswith("__atomic") &&
6051 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006052 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006053 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6054 NS = NS->getPreviousDecl())
6055 NS->setInline(*IsInline);
6056 // Patch up the lookup table for the containing namespace. This isn't really
6057 // correct, but it's good enough for this particular case.
6058 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6059 E = PrevNS->decls_end(); I != E; ++I)
6060 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6061 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6062 return;
6063 }
6064
6065 if (PrevNS->isInline())
6066 // The user probably just forgot the 'inline', so suggest that it
6067 // be added back.
6068 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6069 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6070 else
6071 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6072 << IsInline;
6073
6074 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6075 *IsInline = PrevNS->isInline();
6076}
John McCallea318642010-08-26 09:15:37 +00006077
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006078/// ActOnStartNamespaceDef - This is called at the start of a namespace
6079/// definition.
John McCalld226f652010-08-21 09:40:31 +00006080Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006081 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006082 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006083 SourceLocation IdentLoc,
6084 IdentifierInfo *II,
6085 SourceLocation LBrace,
6086 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006087 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6088 // For anonymous namespace, take the location of the left brace.
6089 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006090 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006091 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006092 bool IsStd = false;
6093 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006094 Scope *DeclRegionScope = NamespcScope->getParent();
6095
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006096 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006097 if (II) {
6098 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006099 // The identifier in an original-namespace-definition shall not
6100 // have been previously defined in the declarative region in
6101 // which the original-namespace-definition appears. The
6102 // identifier in an original-namespace-definition is the name of
6103 // the namespace. Subsequently in that declarative region, it is
6104 // treated as an original-namespace-name.
6105 //
6106 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006107 // look through using directives, just look for any ordinary names.
6108
6109 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006110 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6111 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006112 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006113 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6114 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6115 ++I) {
6116 if ((*I)->getIdentifierNamespace() & IDNS) {
6117 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006118 break;
6119 }
6120 }
6121
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006122 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6123
6124 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006125 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006126 if (IsInline != PrevNS->isInline())
6127 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6128 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006129 } else if (PrevDecl) {
6130 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006131 Diag(Loc, diag::err_redefinition_different_kind)
6132 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006133 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006134 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006135 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006136 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006137 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006138 // This is the first "real" definition of the namespace "std", so update
6139 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006140 PrevNS = getStdNamespace();
6141 IsStd = true;
6142 AddToKnown = !IsInline;
6143 } else {
6144 // We've seen this namespace for the first time.
6145 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006146 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006147 } else {
John McCall9aeed322009-10-01 00:25:31 +00006148 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006149
6150 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006151 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006152 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006153 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006154 } else {
6155 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006156 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006157 }
6158
Richard Smithd1a55a62012-10-04 22:13:39 +00006159 if (PrevNS && IsInline != PrevNS->isInline())
6160 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6161 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006162 }
6163
6164 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6165 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006166 if (IsInvalid)
6167 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006168
6169 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006170
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006171 // FIXME: Should we be merging attributes?
6172 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006173 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006174
6175 if (IsStd)
6176 StdNamespace = Namespc;
6177 if (AddToKnown)
6178 KnownNamespaces[Namespc] = false;
6179
6180 if (II) {
6181 PushOnScopeChains(Namespc, DeclRegionScope);
6182 } else {
6183 // Link the anonymous namespace into its parent.
6184 DeclContext *Parent = CurContext->getRedeclContext();
6185 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6186 TU->setAnonymousNamespace(Namespc);
6187 } else {
6188 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006189 }
John McCall9aeed322009-10-01 00:25:31 +00006190
Douglas Gregora4181472010-03-24 00:46:35 +00006191 CurContext->addDecl(Namespc);
6192
John McCall9aeed322009-10-01 00:25:31 +00006193 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6194 // behaves as if it were replaced by
6195 // namespace unique { /* empty body */ }
6196 // using namespace unique;
6197 // namespace unique { namespace-body }
6198 // where all occurrences of 'unique' in a translation unit are
6199 // replaced by the same identifier and this identifier differs
6200 // from all other identifiers in the entire program.
6201
6202 // We just create the namespace with an empty name and then add an
6203 // implicit using declaration, just like the standard suggests.
6204 //
6205 // CodeGen enforces the "universally unique" aspect by giving all
6206 // declarations semantically contained within an anonymous
6207 // namespace internal linkage.
6208
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006209 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006210 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006211 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006212 /* 'using' */ LBrace,
6213 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006214 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006215 /* identifier */ SourceLocation(),
6216 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006217 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006218 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006219 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006220 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006221 }
6222
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006223 ActOnDocumentableDecl(Namespc);
6224
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006225 // Although we could have an invalid decl (i.e. the namespace name is a
6226 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006227 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6228 // for the namespace has the declarations that showed up in that particular
6229 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006230 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006231 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006232}
6233
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006234/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6235/// is a namespace alias, returns the namespace it points to.
6236static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6237 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6238 return AD->getNamespace();
6239 return dyn_cast_or_null<NamespaceDecl>(D);
6240}
6241
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006242/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6243/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006244void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006245 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6246 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006247 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006248 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006249 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006250 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006251}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006252
John McCall384aff82010-08-25 07:42:41 +00006253CXXRecordDecl *Sema::getStdBadAlloc() const {
6254 return cast_or_null<CXXRecordDecl>(
6255 StdBadAlloc.get(Context.getExternalSource()));
6256}
6257
6258NamespaceDecl *Sema::getStdNamespace() const {
6259 return cast_or_null<NamespaceDecl>(
6260 StdNamespace.get(Context.getExternalSource()));
6261}
6262
Douglas Gregor66992202010-06-29 17:53:46 +00006263/// \brief Retrieve the special "std" namespace, which may require us to
6264/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006265NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006266 if (!StdNamespace) {
6267 // The "std" namespace has not yet been defined, so build one implicitly.
6268 StdNamespace = NamespaceDecl::Create(Context,
6269 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006270 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006271 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006272 &PP.getIdentifierTable().get("std"),
6273 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006274 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006275 }
6276
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006277 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006278}
6279
Sebastian Redl395e04d2012-01-17 22:49:33 +00006280bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006281 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006282 "Looking for std::initializer_list outside of C++.");
6283
6284 // We're looking for implicit instantiations of
6285 // template <typename E> class std::initializer_list.
6286
6287 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6288 return false;
6289
Sebastian Redl84760e32012-01-17 22:49:58 +00006290 ClassTemplateDecl *Template = 0;
6291 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006292
Sebastian Redl84760e32012-01-17 22:49:58 +00006293 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006294
Sebastian Redl84760e32012-01-17 22:49:58 +00006295 ClassTemplateSpecializationDecl *Specialization =
6296 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6297 if (!Specialization)
6298 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006299
Sebastian Redl84760e32012-01-17 22:49:58 +00006300 Template = Specialization->getSpecializedTemplate();
6301 Arguments = Specialization->getTemplateArgs().data();
6302 } else if (const TemplateSpecializationType *TST =
6303 Ty->getAs<TemplateSpecializationType>()) {
6304 Template = dyn_cast_or_null<ClassTemplateDecl>(
6305 TST->getTemplateName().getAsTemplateDecl());
6306 Arguments = TST->getArgs();
6307 }
6308 if (!Template)
6309 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006310
6311 if (!StdInitializerList) {
6312 // Haven't recognized std::initializer_list yet, maybe this is it.
6313 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6314 if (TemplateClass->getIdentifier() !=
6315 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006316 !getStdNamespace()->InEnclosingNamespaceSetOf(
6317 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006318 return false;
6319 // This is a template called std::initializer_list, but is it the right
6320 // template?
6321 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006322 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006323 return false;
6324 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6325 return false;
6326
6327 // It's the right template.
6328 StdInitializerList = Template;
6329 }
6330
6331 if (Template != StdInitializerList)
6332 return false;
6333
6334 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006335 if (Element)
6336 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006337 return true;
6338}
6339
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006340static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6341 NamespaceDecl *Std = S.getStdNamespace();
6342 if (!Std) {
6343 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6344 return 0;
6345 }
6346
6347 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6348 Loc, Sema::LookupOrdinaryName);
6349 if (!S.LookupQualifiedName(Result, Std)) {
6350 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6351 return 0;
6352 }
6353 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6354 if (!Template) {
6355 Result.suppressDiagnostics();
6356 // We found something weird. Complain about the first thing we found.
6357 NamedDecl *Found = *Result.begin();
6358 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6359 return 0;
6360 }
6361
6362 // We found some template called std::initializer_list. Now verify that it's
6363 // correct.
6364 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006365 if (Params->getMinRequiredArguments() != 1 ||
6366 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006367 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6368 return 0;
6369 }
6370
6371 return Template;
6372}
6373
6374QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6375 if (!StdInitializerList) {
6376 StdInitializerList = LookupStdInitializerList(*this, Loc);
6377 if (!StdInitializerList)
6378 return QualType();
6379 }
6380
6381 TemplateArgumentListInfo Args(Loc, Loc);
6382 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6383 Context.getTrivialTypeSourceInfo(Element,
6384 Loc)));
6385 return Context.getCanonicalType(
6386 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6387}
6388
Sebastian Redl98d36062012-01-17 22:50:14 +00006389bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6390 // C++ [dcl.init.list]p2:
6391 // A constructor is an initializer-list constructor if its first parameter
6392 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6393 // std::initializer_list<E> for some type E, and either there are no other
6394 // parameters or else all other parameters have default arguments.
6395 if (Ctor->getNumParams() < 1 ||
6396 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6397 return false;
6398
6399 QualType ArgType = Ctor->getParamDecl(0)->getType();
6400 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6401 ArgType = RT->getPointeeType().getUnqualifiedType();
6402
6403 return isStdInitializerList(ArgType, 0);
6404}
6405
Douglas Gregor9172aa62011-03-26 22:25:30 +00006406/// \brief Determine whether a using statement is in a context where it will be
6407/// apply in all contexts.
6408static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6409 switch (CurContext->getDeclKind()) {
6410 case Decl::TranslationUnit:
6411 return true;
6412 case Decl::LinkageSpec:
6413 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6414 default:
6415 return false;
6416 }
6417}
6418
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006419namespace {
6420
6421// Callback to only accept typo corrections that are namespaces.
6422class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6423 public:
6424 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6425 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6426 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6427 }
6428 return false;
6429 }
6430};
6431
6432}
6433
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006434static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6435 CXXScopeSpec &SS,
6436 SourceLocation IdentLoc,
6437 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006438 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006439 R.clear();
6440 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006441 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006442 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006443 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6444 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006445 if (DeclContext *DC = S.computeDeclContext(SS, false))
6446 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6447 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006448 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6449 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006450 else
6451 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6452 << Ident << CorrectedQuotedStr
6453 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006454
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006455 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6456 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006457
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006458 R.addDecl(Corrected.getCorrectionDecl());
6459 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006460 }
6461 return false;
6462}
6463
John McCalld226f652010-08-21 09:40:31 +00006464Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006465 SourceLocation UsingLoc,
6466 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006467 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006468 SourceLocation IdentLoc,
6469 IdentifierInfo *NamespcName,
6470 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006471 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6472 assert(NamespcName && "Invalid NamespcName.");
6473 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006474
6475 // This can only happen along a recovery path.
6476 while (S->getFlags() & Scope::TemplateParamScope)
6477 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006478 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006479
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006480 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006481 NestedNameSpecifier *Qualifier = 0;
6482 if (SS.isSet())
6483 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6484
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006485 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006486 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6487 LookupParsedName(R, S, &SS);
6488 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006489 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006490
Douglas Gregor66992202010-06-29 17:53:46 +00006491 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006492 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006493 // Allow "using namespace std;" or "using namespace ::std;" even if
6494 // "std" hasn't been defined yet, for GCC compatibility.
6495 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6496 NamespcName->isStr("std")) {
6497 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006498 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006499 R.resolveKind();
6500 }
6501 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006502 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006503 }
6504
John McCallf36e02d2009-10-09 21:13:30 +00006505 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006506 NamedDecl *Named = R.getFoundDecl();
6507 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6508 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006509 // C++ [namespace.udir]p1:
6510 // A using-directive specifies that the names in the nominated
6511 // namespace can be used in the scope in which the
6512 // using-directive appears after the using-directive. During
6513 // unqualified name lookup (3.4.1), the names appear as if they
6514 // were declared in the nearest enclosing namespace which
6515 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006516 // namespace. [Note: in this context, "contains" means "contains
6517 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006518
6519 // Find enclosing context containing both using-directive and
6520 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006521 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006522 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6523 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6524 CommonAncestor = CommonAncestor->getParent();
6525
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006526 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006527 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006528 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006529
Douglas Gregor9172aa62011-03-26 22:25:30 +00006530 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006531 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006532 Diag(IdentLoc, diag::warn_using_directive_in_header);
6533 }
6534
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006535 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006536 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006537 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006538 }
6539
Richard Smith6b3d3e52013-02-20 19:22:51 +00006540 if (UDir)
6541 ProcessDeclAttributeList(S, UDir, AttrList);
6542
John McCalld226f652010-08-21 09:40:31 +00006543 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006544}
6545
6546void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006547 // If the scope has an associated entity and the using directive is at
6548 // namespace or translation unit scope, add the UsingDirectiveDecl into
6549 // its lookup structure so qualified name lookup can find it.
6550 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6551 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006552 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006553 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006554 // Otherwise, it is at block sope. The using-directives will affect lookup
6555 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006556 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006557}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006558
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006559
John McCalld226f652010-08-21 09:40:31 +00006560Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006561 AccessSpecifier AS,
6562 bool HasUsingKeyword,
6563 SourceLocation UsingLoc,
6564 CXXScopeSpec &SS,
6565 UnqualifiedId &Name,
6566 AttributeList *AttrList,
6567 bool IsTypeName,
6568 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006569 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006570
Douglas Gregor12c118a2009-11-04 16:30:06 +00006571 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006572 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006573 case UnqualifiedId::IK_Identifier:
6574 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006575 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006576 case UnqualifiedId::IK_ConversionFunctionId:
6577 break;
6578
6579 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006580 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006581 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006582 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006583 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006584 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006585 diag::err_using_decl_constructor)
6586 << SS.getRange();
6587
Richard Smith80ad52f2013-01-02 11:42:31 +00006588 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006589
John McCalld226f652010-08-21 09:40:31 +00006590 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006591
6592 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006593 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006594 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006595 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006596
6597 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006598 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006599 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006600 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006601 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006602
6603 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6604 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006605 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006606 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006607
Richard Smith07b0fdc2013-03-18 21:12:30 +00006608 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006609 // TODO: store that the declaration was written without 'using' and
6610 // talk about access decls instead of using decls in the
6611 // diagnostics.
6612 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006613 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006614
6615 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006616 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006617 }
6618
Douglas Gregor56c04582010-12-16 00:46:58 +00006619 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6620 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6621 return 0;
6622
John McCall9488ea12009-11-17 05:59:44 +00006623 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006624 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006625 /* IsInstantiation */ false,
6626 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006627 if (UD)
6628 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006629
John McCalld226f652010-08-21 09:40:31 +00006630 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006631}
6632
Douglas Gregor09acc982010-07-07 23:08:52 +00006633/// \brief Determine whether a using declaration considers the given
6634/// declarations as "equivalent", e.g., if they are redeclarations of
6635/// the same entity or are both typedefs of the same type.
6636static bool
6637IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6638 bool &SuppressRedeclaration) {
6639 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6640 SuppressRedeclaration = false;
6641 return true;
6642 }
6643
Richard Smith162e1c12011-04-15 14:24:37 +00006644 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6645 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006646 SuppressRedeclaration = true;
6647 return Context.hasSameType(TD1->getUnderlyingType(),
6648 TD2->getUnderlyingType());
6649 }
6650
6651 return false;
6652}
6653
6654
John McCall9f54ad42009-12-10 09:41:52 +00006655/// Determines whether to create a using shadow decl for a particular
6656/// decl, given the set of decls existing prior to this using lookup.
6657bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6658 const LookupResult &Previous) {
6659 // Diagnose finding a decl which is not from a base class of the
6660 // current class. We do this now because there are cases where this
6661 // function will silently decide not to build a shadow decl, which
6662 // will pre-empt further diagnostics.
6663 //
6664 // We don't need to do this in C++0x because we do the check once on
6665 // the qualifier.
6666 //
6667 // FIXME: diagnose the following if we care enough:
6668 // struct A { int foo; };
6669 // struct B : A { using A::foo; };
6670 // template <class T> struct C : A {};
6671 // template <class T> struct D : C<T> { using B::foo; } // <---
6672 // This is invalid (during instantiation) in C++03 because B::foo
6673 // resolves to the using decl in B, which is not a base class of D<T>.
6674 // We can't diagnose it immediately because C<T> is an unknown
6675 // specialization. The UsingShadowDecl in D<T> then points directly
6676 // to A::foo, which will look well-formed when we instantiate.
6677 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006678 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006679 DeclContext *OrigDC = Orig->getDeclContext();
6680
6681 // Handle enums and anonymous structs.
6682 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6683 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6684 while (OrigRec->isAnonymousStructOrUnion())
6685 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6686
6687 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6688 if (OrigDC == CurContext) {
6689 Diag(Using->getLocation(),
6690 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006691 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006692 Diag(Orig->getLocation(), diag::note_using_decl_target);
6693 return true;
6694 }
6695
Douglas Gregordc355712011-02-25 00:36:19 +00006696 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006697 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006698 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006699 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006700 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006701 Diag(Orig->getLocation(), diag::note_using_decl_target);
6702 return true;
6703 }
6704 }
6705
6706 if (Previous.empty()) return false;
6707
6708 NamedDecl *Target = Orig;
6709 if (isa<UsingShadowDecl>(Target))
6710 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6711
John McCalld7533ec2009-12-11 02:33:26 +00006712 // If the target happens to be one of the previous declarations, we
6713 // don't have a conflict.
6714 //
6715 // FIXME: but we might be increasing its access, in which case we
6716 // should redeclare it.
6717 NamedDecl *NonTag = 0, *Tag = 0;
6718 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6719 I != E; ++I) {
6720 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006721 bool Result;
6722 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6723 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006724
6725 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6726 }
6727
John McCall9f54ad42009-12-10 09:41:52 +00006728 if (Target->isFunctionOrFunctionTemplate()) {
6729 FunctionDecl *FD;
6730 if (isa<FunctionTemplateDecl>(Target))
6731 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6732 else
6733 FD = cast<FunctionDecl>(Target);
6734
6735 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006736 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006737 case Ovl_Overload:
6738 return false;
6739
6740 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006741 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006742 break;
6743
6744 // We found a decl with the exact signature.
6745 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006746 // If we're in a record, we want to hide the target, so we
6747 // return true (without a diagnostic) to tell the caller not to
6748 // build a shadow decl.
6749 if (CurContext->isRecord())
6750 return true;
6751
6752 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006753 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006754 break;
6755 }
6756
6757 Diag(Target->getLocation(), diag::note_using_decl_target);
6758 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6759 return true;
6760 }
6761
6762 // Target is not a function.
6763
John McCall9f54ad42009-12-10 09:41:52 +00006764 if (isa<TagDecl>(Target)) {
6765 // No conflict between a tag and a non-tag.
6766 if (!Tag) return false;
6767
John McCall41ce66f2009-12-10 19:51:03 +00006768 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006769 Diag(Target->getLocation(), diag::note_using_decl_target);
6770 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6771 return true;
6772 }
6773
6774 // No conflict between a tag and a non-tag.
6775 if (!NonTag) return false;
6776
John McCall41ce66f2009-12-10 19:51:03 +00006777 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006778 Diag(Target->getLocation(), diag::note_using_decl_target);
6779 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6780 return true;
6781}
6782
John McCall9488ea12009-11-17 05:59:44 +00006783/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006784UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006785 UsingDecl *UD,
6786 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006787
6788 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006789 NamedDecl *Target = Orig;
6790 if (isa<UsingShadowDecl>(Target)) {
6791 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6792 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006793 }
6794
6795 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006796 = UsingShadowDecl::Create(Context, CurContext,
6797 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006798 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006799
6800 Shadow->setAccess(UD->getAccess());
6801 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6802 Shadow->setInvalidDecl();
6803
John McCall9488ea12009-11-17 05:59:44 +00006804 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006805 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006806 else
John McCall604e7f12009-12-08 07:46:18 +00006807 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006808
John McCall604e7f12009-12-08 07:46:18 +00006809
John McCall9f54ad42009-12-10 09:41:52 +00006810 return Shadow;
6811}
John McCall604e7f12009-12-08 07:46:18 +00006812
John McCall9f54ad42009-12-10 09:41:52 +00006813/// Hides a using shadow declaration. This is required by the current
6814/// using-decl implementation when a resolvable using declaration in a
6815/// class is followed by a declaration which would hide or override
6816/// one or more of the using decl's targets; for example:
6817///
6818/// struct Base { void foo(int); };
6819/// struct Derived : Base {
6820/// using Base::foo;
6821/// void foo(int);
6822/// };
6823///
6824/// The governing language is C++03 [namespace.udecl]p12:
6825///
6826/// When a using-declaration brings names from a base class into a
6827/// derived class scope, member functions in the derived class
6828/// override and/or hide member functions with the same name and
6829/// parameter types in a base class (rather than conflicting).
6830///
6831/// There are two ways to implement this:
6832/// (1) optimistically create shadow decls when they're not hidden
6833/// by existing declarations, or
6834/// (2) don't create any shadow decls (or at least don't make them
6835/// visible) until we've fully parsed/instantiated the class.
6836/// The problem with (1) is that we might have to retroactively remove
6837/// a shadow decl, which requires several O(n) operations because the
6838/// decl structures are (very reasonably) not designed for removal.
6839/// (2) avoids this but is very fiddly and phase-dependent.
6840void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006841 if (Shadow->getDeclName().getNameKind() ==
6842 DeclarationName::CXXConversionFunctionName)
6843 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6844
John McCall9f54ad42009-12-10 09:41:52 +00006845 // Remove it from the DeclContext...
6846 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006847
John McCall9f54ad42009-12-10 09:41:52 +00006848 // ...and the scope, if applicable...
6849 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006850 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006851 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006852 }
6853
John McCall9f54ad42009-12-10 09:41:52 +00006854 // ...and the using decl.
6855 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6856
6857 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006858 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006859}
6860
John McCall7ba107a2009-11-18 02:36:19 +00006861/// Builds a using declaration.
6862///
6863/// \param IsInstantiation - Whether this call arises from an
6864/// instantiation of an unresolved using declaration. We treat
6865/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006866NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6867 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006868 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006869 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006870 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006871 bool IsInstantiation,
6872 bool IsTypeName,
6873 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006874 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006875 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006876 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006877
Anders Carlsson550b14b2009-08-28 05:49:21 +00006878 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006879
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006880 if (SS.isEmpty()) {
6881 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006882 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006883 }
Mike Stump1eb44332009-09-09 15:08:12 +00006884
John McCall9f54ad42009-12-10 09:41:52 +00006885 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006886 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006887 ForRedeclaration);
6888 Previous.setHideTags(false);
6889 if (S) {
6890 LookupName(Previous, S);
6891
6892 // It is really dumb that we have to do this.
6893 LookupResult::Filter F = Previous.makeFilter();
6894 while (F.hasNext()) {
6895 NamedDecl *D = F.next();
6896 if (!isDeclInScope(D, CurContext, S))
6897 F.erase();
6898 }
6899 F.done();
6900 } else {
6901 assert(IsInstantiation && "no scope in non-instantiation");
6902 assert(CurContext->isRecord() && "scope not record in instantiation");
6903 LookupQualifiedName(Previous, CurContext);
6904 }
6905
John McCall9f54ad42009-12-10 09:41:52 +00006906 // Check for invalid redeclarations.
6907 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6908 return 0;
6909
6910 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006911 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6912 return 0;
6913
John McCallaf8e6ed2009-11-12 03:15:40 +00006914 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006915 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006916 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006917 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006918 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006919 // FIXME: not all declaration name kinds are legal here
6920 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6921 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006922 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006923 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006924 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006925 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6926 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006927 }
John McCalled976492009-12-04 22:46:56 +00006928 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006929 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6930 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006931 }
John McCalled976492009-12-04 22:46:56 +00006932 D->setAccess(AS);
6933 CurContext->addDecl(D);
6934
6935 if (!LookupContext) return D;
6936 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006937
John McCall77bb1aa2010-05-01 00:40:08 +00006938 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006939 UD->setInvalidDecl();
6940 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006941 }
6942
Richard Smithc5a89a12012-04-02 01:30:27 +00006943 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006944 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006945 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006946 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006947 return UD;
6948 }
6949
6950 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006951
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006952 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006953
John McCall604e7f12009-12-08 07:46:18 +00006954 // Unlike most lookups, we don't always want to hide tag
6955 // declarations: tag names are visible through the using declaration
6956 // even if hidden by ordinary names, *except* in a dependent context
6957 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006958 if (!IsInstantiation)
6959 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006960
John McCallb9abd8722012-04-07 03:04:20 +00006961 // For the purposes of this lookup, we have a base object type
6962 // equal to that of the current context.
6963 if (CurContext->isRecord()) {
6964 R.setBaseObjectType(
6965 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6966 }
6967
John McCalla24dc2e2009-11-17 02:14:36 +00006968 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006969
John McCallf36e02d2009-10-09 21:13:30 +00006970 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006971 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006972 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006973 UD->setInvalidDecl();
6974 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006975 }
6976
John McCalled976492009-12-04 22:46:56 +00006977 if (R.isAmbiguous()) {
6978 UD->setInvalidDecl();
6979 return UD;
6980 }
Mike Stump1eb44332009-09-09 15:08:12 +00006981
John McCall7ba107a2009-11-18 02:36:19 +00006982 if (IsTypeName) {
6983 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006984 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006985 Diag(IdentLoc, diag::err_using_typename_non_type);
6986 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6987 Diag((*I)->getUnderlyingDecl()->getLocation(),
6988 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006989 UD->setInvalidDecl();
6990 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006991 }
6992 } else {
6993 // If we asked for a non-typename and we got a type, error out,
6994 // but only if this is an instantiation of an unresolved using
6995 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006996 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006997 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6998 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006999 UD->setInvalidDecl();
7000 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007001 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007002 }
7003
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007004 // C++0x N2914 [namespace.udecl]p6:
7005 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007006 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007007 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7008 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007009 UD->setInvalidDecl();
7010 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007011 }
Mike Stump1eb44332009-09-09 15:08:12 +00007012
John McCall9f54ad42009-12-10 09:41:52 +00007013 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7014 if (!CheckUsingShadowDecl(UD, *I, Previous))
7015 BuildUsingShadowDecl(S, UD, *I);
7016 }
John McCall9488ea12009-11-17 05:59:44 +00007017
7018 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007019}
7020
Sebastian Redlf677ea32011-02-05 19:23:19 +00007021/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007022bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7023 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007024
Douglas Gregordc355712011-02-25 00:36:19 +00007025 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007026 assert(SourceType &&
7027 "Using decl naming constructor doesn't have type in scope spec.");
7028 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7029
7030 // Check whether the named type is a direct base class.
7031 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7032 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7033 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7034 BaseIt != BaseE; ++BaseIt) {
7035 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7036 if (CanonicalSourceType == BaseType)
7037 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007038 if (BaseIt->getType()->isDependentType())
7039 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007040 }
7041
7042 if (BaseIt == BaseE) {
7043 // Did not find SourceType in the bases.
7044 Diag(UD->getUsingLocation(),
7045 diag::err_using_decl_constructor_not_in_direct_base)
7046 << UD->getNameInfo().getSourceRange()
7047 << QualType(SourceType, 0) << TargetClass;
7048 return true;
7049 }
7050
Richard Smithc5a89a12012-04-02 01:30:27 +00007051 if (!CurContext->isDependentContext())
7052 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007053
7054 return false;
7055}
7056
John McCall9f54ad42009-12-10 09:41:52 +00007057/// Checks that the given using declaration is not an invalid
7058/// redeclaration. Note that this is checking only for the using decl
7059/// itself, not for any ill-formedness among the UsingShadowDecls.
7060bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7061 bool isTypeName,
7062 const CXXScopeSpec &SS,
7063 SourceLocation NameLoc,
7064 const LookupResult &Prev) {
7065 // C++03 [namespace.udecl]p8:
7066 // C++0x [namespace.udecl]p10:
7067 // A using-declaration is a declaration and can therefore be used
7068 // repeatedly where (and only where) multiple declarations are
7069 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007070 //
John McCall8a726212010-11-29 18:01:58 +00007071 // That's in non-member contexts.
7072 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007073 return false;
7074
7075 NestedNameSpecifier *Qual
7076 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7077
7078 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7079 NamedDecl *D = *I;
7080
7081 bool DTypename;
7082 NestedNameSpecifier *DQual;
7083 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7084 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007085 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007086 } else if (UnresolvedUsingValueDecl *UD
7087 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7088 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007089 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007090 } else if (UnresolvedUsingTypenameDecl *UD
7091 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7092 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007093 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007094 } else continue;
7095
7096 // using decls differ if one says 'typename' and the other doesn't.
7097 // FIXME: non-dependent using decls?
7098 if (isTypeName != DTypename) continue;
7099
7100 // using decls differ if they name different scopes (but note that
7101 // template instantiation can cause this check to trigger when it
7102 // didn't before instantiation).
7103 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7104 Context.getCanonicalNestedNameSpecifier(DQual))
7105 continue;
7106
7107 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007108 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007109 return true;
7110 }
7111
7112 return false;
7113}
7114
John McCall604e7f12009-12-08 07:46:18 +00007115
John McCalled976492009-12-04 22:46:56 +00007116/// Checks that the given nested-name qualifier used in a using decl
7117/// in the current context is appropriately related to the current
7118/// scope. If an error is found, diagnoses it and returns true.
7119bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7120 const CXXScopeSpec &SS,
7121 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007122 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007123
John McCall604e7f12009-12-08 07:46:18 +00007124 if (!CurContext->isRecord()) {
7125 // C++03 [namespace.udecl]p3:
7126 // C++0x [namespace.udecl]p8:
7127 // A using-declaration for a class member shall be a member-declaration.
7128
7129 // If we weren't able to compute a valid scope, it must be a
7130 // dependent class scope.
7131 if (!NamedContext || NamedContext->isRecord()) {
7132 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7133 << SS.getRange();
7134 return true;
7135 }
7136
7137 // Otherwise, everything is known to be fine.
7138 return false;
7139 }
7140
7141 // The current scope is a record.
7142
7143 // If the named context is dependent, we can't decide much.
7144 if (!NamedContext) {
7145 // FIXME: in C++0x, we can diagnose if we can prove that the
7146 // nested-name-specifier does not refer to a base class, which is
7147 // still possible in some cases.
7148
7149 // Otherwise we have to conservatively report that things might be
7150 // okay.
7151 return false;
7152 }
7153
7154 if (!NamedContext->isRecord()) {
7155 // Ideally this would point at the last name in the specifier,
7156 // but we don't have that level of source info.
7157 Diag(SS.getRange().getBegin(),
7158 diag::err_using_decl_nested_name_specifier_is_not_class)
7159 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7160 return true;
7161 }
7162
Douglas Gregor6fb07292010-12-21 07:41:49 +00007163 if (!NamedContext->isDependentContext() &&
7164 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7165 return true;
7166
Richard Smith80ad52f2013-01-02 11:42:31 +00007167 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007168 // C++0x [namespace.udecl]p3:
7169 // In a using-declaration used as a member-declaration, the
7170 // nested-name-specifier shall name a base class of the class
7171 // being defined.
7172
7173 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7174 cast<CXXRecordDecl>(NamedContext))) {
7175 if (CurContext == NamedContext) {
7176 Diag(NameLoc,
7177 diag::err_using_decl_nested_name_specifier_is_current_class)
7178 << SS.getRange();
7179 return true;
7180 }
7181
7182 Diag(SS.getRange().getBegin(),
7183 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7184 << (NestedNameSpecifier*) SS.getScopeRep()
7185 << cast<CXXRecordDecl>(CurContext)
7186 << SS.getRange();
7187 return true;
7188 }
7189
7190 return false;
7191 }
7192
7193 // C++03 [namespace.udecl]p4:
7194 // A using-declaration used as a member-declaration shall refer
7195 // to a member of a base class of the class being defined [etc.].
7196
7197 // Salient point: SS doesn't have to name a base class as long as
7198 // lookup only finds members from base classes. Therefore we can
7199 // diagnose here only if we can prove that that can't happen,
7200 // i.e. if the class hierarchies provably don't intersect.
7201
7202 // TODO: it would be nice if "definitely valid" results were cached
7203 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7204 // need to be repeated.
7205
7206 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007207 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007208
7209 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7210 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7211 Data->Bases.insert(Base);
7212 return true;
7213 }
7214
7215 bool hasDependentBases(const CXXRecordDecl *Class) {
7216 return !Class->forallBases(collect, this);
7217 }
7218
7219 /// Returns true if the base is dependent or is one of the
7220 /// accumulated base classes.
7221 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7222 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7223 return !Data->Bases.count(Base);
7224 }
7225
7226 bool mightShareBases(const CXXRecordDecl *Class) {
7227 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7228 }
7229 };
7230
7231 UserData Data;
7232
7233 // Returns false if we find a dependent base.
7234 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7235 return false;
7236
7237 // Returns false if the class has a dependent base or if it or one
7238 // of its bases is present in the base set of the current context.
7239 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7240 return false;
7241
7242 Diag(SS.getRange().getBegin(),
7243 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7244 << (NestedNameSpecifier*) SS.getScopeRep()
7245 << cast<CXXRecordDecl>(CurContext)
7246 << SS.getRange();
7247
7248 return true;
John McCalled976492009-12-04 22:46:56 +00007249}
7250
Richard Smith162e1c12011-04-15 14:24:37 +00007251Decl *Sema::ActOnAliasDeclaration(Scope *S,
7252 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007253 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007254 SourceLocation UsingLoc,
7255 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007256 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007257 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007258 // Skip up to the relevant declaration scope.
7259 while (S->getFlags() & Scope::TemplateParamScope)
7260 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007261 assert((S->getFlags() & Scope::DeclScope) &&
7262 "got alias-declaration outside of declaration scope");
7263
7264 if (Type.isInvalid())
7265 return 0;
7266
7267 bool Invalid = false;
7268 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7269 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007270 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007271
7272 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7273 return 0;
7274
7275 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007276 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007277 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007278 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7279 TInfo->getTypeLoc().getBeginLoc());
7280 }
Richard Smith162e1c12011-04-15 14:24:37 +00007281
7282 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7283 LookupName(Previous, S);
7284
7285 // Warn about shadowing the name of a template parameter.
7286 if (Previous.isSingleResult() &&
7287 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007288 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007289 Previous.clear();
7290 }
7291
7292 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7293 "name in alias declaration must be an identifier");
7294 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7295 Name.StartLocation,
7296 Name.Identifier, TInfo);
7297
7298 NewTD->setAccess(AS);
7299
7300 if (Invalid)
7301 NewTD->setInvalidDecl();
7302
Richard Smith6b3d3e52013-02-20 19:22:51 +00007303 ProcessDeclAttributeList(S, NewTD, AttrList);
7304
Richard Smith3e4c6c42011-05-05 21:57:07 +00007305 CheckTypedefForVariablyModifiedType(S, NewTD);
7306 Invalid |= NewTD->isInvalidDecl();
7307
Richard Smith162e1c12011-04-15 14:24:37 +00007308 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007309
7310 NamedDecl *NewND;
7311 if (TemplateParamLists.size()) {
7312 TypeAliasTemplateDecl *OldDecl = 0;
7313 TemplateParameterList *OldTemplateParams = 0;
7314
7315 if (TemplateParamLists.size() != 1) {
7316 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007317 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7318 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007319 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007320 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007321
7322 // Only consider previous declarations in the same scope.
7323 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7324 /*ExplicitInstantiationOrSpecialization*/false);
7325 if (!Previous.empty()) {
7326 Redeclaration = true;
7327
7328 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7329 if (!OldDecl && !Invalid) {
7330 Diag(UsingLoc, diag::err_redefinition_different_kind)
7331 << Name.Identifier;
7332
7333 NamedDecl *OldD = Previous.getRepresentativeDecl();
7334 if (OldD->getLocation().isValid())
7335 Diag(OldD->getLocation(), diag::note_previous_definition);
7336
7337 Invalid = true;
7338 }
7339
7340 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7341 if (TemplateParameterListsAreEqual(TemplateParams,
7342 OldDecl->getTemplateParameters(),
7343 /*Complain=*/true,
7344 TPL_TemplateMatch))
7345 OldTemplateParams = OldDecl->getTemplateParameters();
7346 else
7347 Invalid = true;
7348
7349 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7350 if (!Invalid &&
7351 !Context.hasSameType(OldTD->getUnderlyingType(),
7352 NewTD->getUnderlyingType())) {
7353 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7354 // but we can't reasonably accept it.
7355 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7356 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7357 if (OldTD->getLocation().isValid())
7358 Diag(OldTD->getLocation(), diag::note_previous_definition);
7359 Invalid = true;
7360 }
7361 }
7362 }
7363
7364 // Merge any previous default template arguments into our parameters,
7365 // and check the parameter list.
7366 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7367 TPC_TypeAliasTemplate))
7368 return 0;
7369
7370 TypeAliasTemplateDecl *NewDecl =
7371 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7372 Name.Identifier, TemplateParams,
7373 NewTD);
7374
7375 NewDecl->setAccess(AS);
7376
7377 if (Invalid)
7378 NewDecl->setInvalidDecl();
7379 else if (OldDecl)
7380 NewDecl->setPreviousDeclaration(OldDecl);
7381
7382 NewND = NewDecl;
7383 } else {
7384 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7385 NewND = NewTD;
7386 }
Richard Smith162e1c12011-04-15 14:24:37 +00007387
7388 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007389 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007390
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007391 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007392 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007393}
7394
John McCalld226f652010-08-21 09:40:31 +00007395Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007396 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007397 SourceLocation AliasLoc,
7398 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007399 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007400 SourceLocation IdentLoc,
7401 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007402
Anders Carlsson81c85c42009-03-28 23:53:49 +00007403 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007404 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7405 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007406
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007407 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007408 NamedDecl *PrevDecl
7409 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7410 ForRedeclaration);
7411 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7412 PrevDecl = 0;
7413
7414 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007415 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007416 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007417 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007418 // FIXME: At some point, we'll want to create the (redundant)
7419 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007420 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007421 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007422 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007423 }
Mike Stump1eb44332009-09-09 15:08:12 +00007424
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007425 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7426 diag::err_redefinition_different_kind;
7427 Diag(AliasLoc, DiagID) << Alias;
7428 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007429 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007430 }
7431
John McCalla24dc2e2009-11-17 02:14:36 +00007432 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007433 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007434
John McCallf36e02d2009-10-09 21:13:30 +00007435 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007436 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007437 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007438 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007439 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007440 }
Mike Stump1eb44332009-09-09 15:08:12 +00007441
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007442 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007443 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007444 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007445 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007446
John McCall3dbd3d52010-02-16 06:53:13 +00007447 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007448 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007449}
7450
Sean Hunt001cad92011-05-10 00:49:42 +00007451Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007452Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7453 CXXMethodDecl *MD) {
7454 CXXRecordDecl *ClassDecl = MD->getParent();
7455
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007456 // C++ [except.spec]p14:
7457 // An implicitly declared special member function (Clause 12) shall have an
7458 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007459 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007460 if (ClassDecl->isInvalidDecl())
7461 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007462
Sebastian Redl60618fa2011-03-12 11:50:43 +00007463 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007464 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7465 BEnd = ClassDecl->bases_end();
7466 B != BEnd; ++B) {
7467 if (B->isVirtual()) // Handled below.
7468 continue;
7469
Douglas Gregor18274032010-07-03 00:47:00 +00007470 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7471 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007472 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7473 // If this is a deleted function, add it anyway. This might be conformant
7474 // with the standard. This might not. I'm not sure. It might not matter.
7475 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007476 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007477 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007478 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007479
7480 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007481 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7482 BEnd = ClassDecl->vbases_end();
7483 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007484 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7485 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007486 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7487 // If this is a deleted function, add it anyway. This might be conformant
7488 // with the standard. This might not. I'm not sure. It might not matter.
7489 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007490 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007491 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007492 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007493
7494 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007495 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7496 FEnd = ClassDecl->field_end();
7497 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007498 if (F->hasInClassInitializer()) {
7499 if (Expr *E = F->getInClassInitializer())
7500 ExceptSpec.CalledExpr(E);
7501 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007502 // DR1351:
7503 // If the brace-or-equal-initializer of a non-static data member
7504 // invokes a defaulted default constructor of its class or of an
7505 // enclosing class in a potentially evaluated subexpression, the
7506 // program is ill-formed.
7507 //
7508 // This resolution is unworkable: the exception specification of the
7509 // default constructor can be needed in an unevaluated context, in
7510 // particular, in the operand of a noexcept-expression, and we can be
7511 // unable to compute an exception specification for an enclosed class.
7512 //
7513 // We do not allow an in-class initializer to require the evaluation
7514 // of the exception specification for any in-class initializer whose
7515 // definition is not lexically complete.
7516 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007517 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007518 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007519 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7520 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7521 // If this is a deleted function, add it anyway. This might be conformant
7522 // with the standard. This might not. I'm not sure. It might not matter.
7523 // In particular, the problem is that this function never gets called. It
7524 // might just be ill-formed because this function attempts to refer to
7525 // a deleted function here.
7526 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007527 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007528 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007529 }
John McCalle23cf432010-12-14 08:05:40 +00007530
Sean Hunt001cad92011-05-10 00:49:42 +00007531 return ExceptSpec;
7532}
7533
Richard Smith07b0fdc2013-03-18 21:12:30 +00007534Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007535Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7536 CXXRecordDecl *ClassDecl = CD->getParent();
7537
7538 // C++ [except.spec]p14:
7539 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007540 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007541 if (ClassDecl->isInvalidDecl())
7542 return ExceptSpec;
7543
7544 // Inherited constructor.
7545 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7546 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7547 // FIXME: Copying or moving the parameters could add extra exceptions to the
7548 // set, as could the default arguments for the inherited constructor. This
7549 // will be addressed when we implement the resolution of core issue 1351.
7550 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7551
7552 // Direct base-class constructors.
7553 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7554 BEnd = ClassDecl->bases_end();
7555 B != BEnd; ++B) {
7556 if (B->isVirtual()) // Handled below.
7557 continue;
7558
7559 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7560 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7561 if (BaseClassDecl == InheritedDecl)
7562 continue;
7563 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7564 if (Constructor)
7565 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7566 }
7567 }
7568
7569 // Virtual base-class constructors.
7570 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7571 BEnd = ClassDecl->vbases_end();
7572 B != BEnd; ++B) {
7573 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7574 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7575 if (BaseClassDecl == InheritedDecl)
7576 continue;
7577 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7578 if (Constructor)
7579 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7580 }
7581 }
7582
7583 // Field constructors.
7584 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7585 FEnd = ClassDecl->field_end();
7586 F != FEnd; ++F) {
7587 if (F->hasInClassInitializer()) {
7588 if (Expr *E = F->getInClassInitializer())
7589 ExceptSpec.CalledExpr(E);
7590 else if (!F->isInvalidDecl())
7591 Diag(CD->getLocation(),
7592 diag::err_in_class_initializer_references_def_ctor) << CD;
7593 } else if (const RecordType *RecordTy
7594 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7595 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7596 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7597 if (Constructor)
7598 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7599 }
7600 }
7601
Richard Smith07b0fdc2013-03-18 21:12:30 +00007602 return ExceptSpec;
7603}
7604
Richard Smithafb49182012-11-29 01:34:07 +00007605namespace {
7606/// RAII object to register a special member as being currently declared.
7607struct DeclaringSpecialMember {
7608 Sema &S;
7609 Sema::SpecialMemberDecl D;
7610 bool WasAlreadyBeingDeclared;
7611
7612 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7613 : S(S), D(RD, CSM) {
7614 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7615 if (WasAlreadyBeingDeclared)
7616 // This almost never happens, but if it does, ensure that our cache
7617 // doesn't contain a stale result.
7618 S.SpecialMemberCache.clear();
7619
7620 // FIXME: Register a note to be produced if we encounter an error while
7621 // declaring the special member.
7622 }
7623 ~DeclaringSpecialMember() {
7624 if (!WasAlreadyBeingDeclared)
7625 S.SpecialMembersBeingDeclared.erase(D);
7626 }
7627
7628 /// \brief Are we already trying to declare this special member?
7629 bool isAlreadyBeingDeclared() const {
7630 return WasAlreadyBeingDeclared;
7631 }
7632};
7633}
7634
Sean Hunt001cad92011-05-10 00:49:42 +00007635CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7636 CXXRecordDecl *ClassDecl) {
7637 // C++ [class.ctor]p5:
7638 // A default constructor for a class X is a constructor of class X
7639 // that can be called without an argument. If there is no
7640 // user-declared constructor for class X, a default constructor is
7641 // implicitly declared. An implicitly-declared default constructor
7642 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007643 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007644 "Should not build implicit default constructor!");
7645
Richard Smithafb49182012-11-29 01:34:07 +00007646 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7647 if (DSM.isAlreadyBeingDeclared())
7648 return 0;
7649
Richard Smith7756afa2012-06-10 05:43:50 +00007650 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7651 CXXDefaultConstructor,
7652 false);
7653
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007654 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007655 CanQualType ClassType
7656 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007657 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007658 DeclarationName Name
7659 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007660 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007661 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007662 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007663 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007664 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007665 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007666 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007667 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007668
7669 // Build an exception specification pointing back at this constructor.
7670 FunctionProtoType::ExtProtoInfo EPI;
7671 EPI.ExceptionSpecType = EST_Unevaluated;
7672 EPI.ExceptionSpecDecl = DefaultCon;
Jordan Rosebea522f2013-03-08 21:51:21 +00007673 DefaultCon->setType(Context.getFunctionType(Context.VoidTy,
7674 ArrayRef<QualType>(),
7675 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007676
Richard Smithbc2a35d2012-12-08 08:32:28 +00007677 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7678 // constructors is easy to compute.
7679 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7680
7681 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007682 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007683
Douglas Gregor18274032010-07-03 00:47:00 +00007684 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007685 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007686
Douglas Gregor23c94db2010-07-02 17:43:08 +00007687 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007688 PushOnScopeChains(DefaultCon, S, false);
7689 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007690
Douglas Gregor32df23e2010-07-01 22:02:46 +00007691 return DefaultCon;
7692}
7693
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007694void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7695 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007696 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007697 !Constructor->doesThisDeclarationHaveABody() &&
7698 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007699 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007700
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007701 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007702 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007703
Eli Friedman9a14db32012-10-18 20:14:08 +00007704 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007705 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007706 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007707 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007708 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007709 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007710 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007711 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007712 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007713
7714 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007715 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007716
7717 Constructor->setUsed();
7718 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007719
7720 if (ASTMutationListener *L = getASTMutationListener()) {
7721 L->CompletedImplicitDefinition(Constructor);
7722 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007723}
7724
Richard Smith7a614d82011-06-11 17:19:42 +00007725void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007726 // Check that any explicitly-defaulted methods have exception specifications
7727 // compatible with their implicit exception specifications.
7728 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007729}
7730
Richard Smith4841ca52013-04-10 05:48:59 +00007731namespace {
7732/// Information on inheriting constructors to declare.
7733class InheritingConstructorInfo {
7734public:
7735 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7736 : SemaRef(SemaRef), Derived(Derived) {
7737 // Mark the constructors that we already have in the derived class.
7738 //
7739 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7740 // unless there is a user-declared constructor with the same signature in
7741 // the class where the using-declaration appears.
7742 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7743 }
7744
7745 void inheritAll(CXXRecordDecl *RD) {
7746 visitAll(RD, &InheritingConstructorInfo::inherit);
7747 }
7748
7749private:
7750 /// Information about an inheriting constructor.
7751 struct InheritingConstructor {
7752 InheritingConstructor()
7753 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7754
7755 /// If \c true, a constructor with this signature is already declared
7756 /// in the derived class.
7757 bool DeclaredInDerived;
7758
7759 /// The constructor which is inherited.
7760 const CXXConstructorDecl *BaseCtor;
7761
7762 /// The derived constructor we declared.
7763 CXXConstructorDecl *DerivedCtor;
7764 };
7765
7766 /// Inheriting constructors with a given canonical type. There can be at
7767 /// most one such non-template constructor, and any number of templated
7768 /// constructors.
7769 struct InheritingConstructorsForType {
7770 InheritingConstructor NonTemplate;
7771 llvm::SmallVector<
7772 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7773
7774 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7775 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7776 TemplateParameterList *ParamList = FTD->getTemplateParameters();
7777 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7778 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7779 false, S.TPL_TemplateMatch))
7780 return Templates[I].second;
7781 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7782 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007783 }
Richard Smith4841ca52013-04-10 05:48:59 +00007784
7785 return NonTemplate;
7786 }
7787 };
7788
7789 /// Get or create the inheriting constructor record for a constructor.
7790 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7791 QualType CtorType) {
7792 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7793 .getEntry(SemaRef, Ctor);
7794 }
7795
7796 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7797
7798 /// Process all constructors for a class.
7799 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7800 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7801 CtorE = RD->ctor_end();
7802 CtorIt != CtorE; ++CtorIt)
7803 (this->*Callback)(*CtorIt);
7804 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7805 I(RD->decls_begin()), E(RD->decls_end());
7806 I != E; ++I) {
7807 const FunctionDecl *FD = (*I)->getTemplatedDecl();
7808 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7809 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007810 }
7811 }
Richard Smith4841ca52013-04-10 05:48:59 +00007812
7813 /// Note that a constructor (or constructor template) was declared in Derived.
7814 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7815 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7816 }
7817
7818 /// Inherit a single constructor.
7819 void inherit(const CXXConstructorDecl *Ctor) {
7820 const FunctionProtoType *CtorType =
7821 Ctor->getType()->castAs<FunctionProtoType>();
7822 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7823 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7824
7825 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7826
7827 // Core issue (no number yet): the ellipsis is always discarded.
7828 if (EPI.Variadic) {
7829 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7830 SemaRef.Diag(Ctor->getLocation(),
7831 diag::note_using_decl_constructor_ellipsis);
7832 EPI.Variadic = false;
7833 }
7834
7835 // Declare a constructor for each number of parameters.
7836 //
7837 // C++11 [class.inhctor]p1:
7838 // The candidate set of inherited constructors from the class X named in
7839 // the using-declaration consists of [... modulo defects ...] for each
7840 // constructor or constructor template of X, the set of constructors or
7841 // constructor templates that results from omitting any ellipsis parameter
7842 // specification and successively omitting parameters with a default
7843 // argument from the end of the parameter-type-list
7844 for (unsigned Params = std::max(minParamsToInherit(Ctor),
7845 Ctor->getMinRequiredArguments()),
7846 MaxParams = Ctor->getNumParams();
7847 Params <= MaxParams; ++Params)
7848 declareCtor(UsingLoc, Ctor,
7849 SemaRef.Context.getFunctionType(
7850 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7851 }
7852
7853 /// Find the using-declaration which specified that we should inherit the
7854 /// constructors of \p Base.
7855 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
7856 // No fancy lookup required; just look for the base constructor name
7857 // directly within the derived class.
7858 ASTContext &Context = SemaRef.Context;
7859 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
7860 Context.getCanonicalType(Context.getRecordType(Base)));
7861 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
7862 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
7863 }
7864
7865 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
7866 // C++11 [class.inhctor]p3:
7867 // [F]or each constructor template in the candidate set of inherited
7868 // constructors, a constructor template is implicitly declared
7869 if (Ctor->getDescribedFunctionTemplate())
7870 return 0;
7871
7872 // For each non-template constructor in the candidate set of inherited
7873 // constructors other than a constructor having no parameters or a
7874 // copy/move constructor having a single parameter, a constructor is
7875 // implicitly declared [...]
7876 if (Ctor->getNumParams() == 0)
7877 return 1;
7878 if (Ctor->isCopyOrMoveConstructor())
7879 return 2;
7880
7881 // Per discussion on core reflector, never inherit a constructor which
7882 // would become a default, copy, or move constructor of Derived either.
7883 const ParmVarDecl *PD = Ctor->getParamDecl(0);
7884 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
7885 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
7886 }
7887
7888 /// Declare a single inheriting constructor, inheriting the specified
7889 /// constructor, with the given type.
7890 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
7891 QualType DerivedType) {
7892 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
7893
7894 // C++11 [class.inhctor]p3:
7895 // ... a constructor is implicitly declared with the same constructor
7896 // characteristics unless there is a user-declared constructor with
7897 // the same signature in the class where the using-declaration appears
7898 if (Entry.DeclaredInDerived)
7899 return;
7900
7901 // C++11 [class.inhctor]p7:
7902 // If two using-declarations declare inheriting constructors with the
7903 // same signature, the program is ill-formed
7904 if (Entry.DerivedCtor) {
7905 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
7906 // Only diagnose this once per constructor.
7907 if (Entry.DerivedCtor->isInvalidDecl())
7908 return;
7909 Entry.DerivedCtor->setInvalidDecl();
7910
7911 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7912 SemaRef.Diag(BaseCtor->getLocation(),
7913 diag::note_using_decl_constructor_conflict_current_ctor);
7914 SemaRef.Diag(Entry.BaseCtor->getLocation(),
7915 diag::note_using_decl_constructor_conflict_previous_ctor);
7916 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
7917 diag::note_using_decl_constructor_conflict_previous_using);
7918 } else {
7919 // Core issue (no number): if the same inheriting constructor is
7920 // produced by multiple base class constructors from the same base
7921 // class, the inheriting constructor is defined as deleted.
7922 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
7923 }
7924
7925 return;
7926 }
7927
7928 ASTContext &Context = SemaRef.Context;
7929 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
7930 Context.getCanonicalType(Context.getRecordType(Derived)));
7931 DeclarationNameInfo NameInfo(Name, UsingLoc);
7932
7933 TemplateParameterList *TemplateParams = 0;
7934 if (const FunctionTemplateDecl *FTD =
7935 BaseCtor->getDescribedFunctionTemplate()) {
7936 TemplateParams = FTD->getTemplateParameters();
7937 // We're reusing template parameters from a different DeclContext. This
7938 // is questionable at best, but works out because the template depth in
7939 // both places is guaranteed to be 0.
7940 // FIXME: Rebuild the template parameters in the new context, and
7941 // transform the function type to refer to them.
7942 }
7943
7944 // Build type source info pointing at the using-declaration. This is
7945 // required by template instantiation.
7946 TypeSourceInfo *TInfo =
7947 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
7948 FunctionProtoTypeLoc ProtoLoc =
7949 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
7950
7951 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
7952 Context, Derived, UsingLoc, NameInfo, DerivedType,
7953 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
7954 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
7955
7956 // Build an unevaluated exception specification for this constructor.
7957 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
7958 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7959 EPI.ExceptionSpecType = EST_Unevaluated;
7960 EPI.ExceptionSpecDecl = DerivedCtor;
7961 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
7962 FPT->getArgTypes(), EPI));
7963
7964 // Build the parameter declarations.
7965 SmallVector<ParmVarDecl *, 16> ParamDecls;
7966 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
7967 TypeSourceInfo *TInfo =
7968 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
7969 ParmVarDecl *PD = ParmVarDecl::Create(
7970 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
7971 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
7972 PD->setScopeInfo(0, I);
7973 PD->setImplicit();
7974 ParamDecls.push_back(PD);
7975 ProtoLoc.setArg(I, PD);
7976 }
7977
7978 // Set up the new constructor.
7979 DerivedCtor->setAccess(BaseCtor->getAccess());
7980 DerivedCtor->setParams(ParamDecls);
7981 DerivedCtor->setInheritedConstructor(BaseCtor);
7982 if (BaseCtor->isDeleted())
7983 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
7984
7985 // If this is a constructor template, build the template declaration.
7986 if (TemplateParams) {
7987 FunctionTemplateDecl *DerivedTemplate =
7988 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
7989 TemplateParams, DerivedCtor);
7990 DerivedTemplate->setAccess(BaseCtor->getAccess());
7991 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
7992 Derived->addDecl(DerivedTemplate);
7993 } else {
7994 Derived->addDecl(DerivedCtor);
7995 }
7996
7997 Entry.BaseCtor = BaseCtor;
7998 Entry.DerivedCtor = DerivedCtor;
7999 }
8000
8001 Sema &SemaRef;
8002 CXXRecordDecl *Derived;
8003 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8004 MapType Map;
8005};
8006}
8007
8008void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8009 // Defer declaring the inheriting constructors until the class is
8010 // instantiated.
8011 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008012 return;
8013
Richard Smith4841ca52013-04-10 05:48:59 +00008014 // Find base classes from which we might inherit constructors.
8015 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8016 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8017 BaseE = ClassDecl->bases_end();
8018 BaseIt != BaseE; ++BaseIt)
8019 if (BaseIt->getInheritConstructors())
8020 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008021
Richard Smith4841ca52013-04-10 05:48:59 +00008022 // Go no further if we're not inheriting any constructors.
8023 if (InheritedBases.empty())
8024 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008025
Richard Smith4841ca52013-04-10 05:48:59 +00008026 // Declare the inherited constructors.
8027 InheritingConstructorInfo ICI(*this, ClassDecl);
8028 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8029 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008030}
8031
Richard Smith07b0fdc2013-03-18 21:12:30 +00008032void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8033 CXXConstructorDecl *Constructor) {
8034 CXXRecordDecl *ClassDecl = Constructor->getParent();
8035 assert(Constructor->getInheritedConstructor() &&
8036 !Constructor->doesThisDeclarationHaveABody() &&
8037 !Constructor->isDeleted());
8038
8039 SynthesizedFunctionScope Scope(*this, Constructor);
8040 DiagnosticErrorTrap Trap(Diags);
8041 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8042 Trap.hasErrorOccurred()) {
8043 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8044 << Context.getTagDeclType(ClassDecl);
8045 Constructor->setInvalidDecl();
8046 return;
8047 }
8048
8049 SourceLocation Loc = Constructor->getLocation();
8050 Constructor->setBody(new (Context) CompoundStmt(Loc));
8051
8052 Constructor->setUsed();
8053 MarkVTableUsed(CurrentLocation, ClassDecl);
8054
8055 if (ASTMutationListener *L = getASTMutationListener()) {
8056 L->CompletedImplicitDefinition(Constructor);
8057 }
8058}
8059
8060
Sean Huntcb45a0f2011-05-12 22:46:25 +00008061Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008062Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8063 CXXRecordDecl *ClassDecl = MD->getParent();
8064
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008065 // C++ [except.spec]p14:
8066 // An implicitly declared special member function (Clause 12) shall have
8067 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008068 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008069 if (ClassDecl->isInvalidDecl())
8070 return ExceptSpec;
8071
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008072 // Direct base-class destructors.
8073 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8074 BEnd = ClassDecl->bases_end();
8075 B != BEnd; ++B) {
8076 if (B->isVirtual()) // Handled below.
8077 continue;
8078
8079 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008080 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008081 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008082 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008083
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008084 // Virtual base-class destructors.
8085 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8086 BEnd = ClassDecl->vbases_end();
8087 B != BEnd; ++B) {
8088 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008089 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008090 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008091 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008092
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008093 // Field destructors.
8094 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8095 FEnd = ClassDecl->field_end();
8096 F != FEnd; ++F) {
8097 if (const RecordType *RecordTy
8098 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008099 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008100 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008101 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008102
Sean Huntcb45a0f2011-05-12 22:46:25 +00008103 return ExceptSpec;
8104}
8105
8106CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8107 // C++ [class.dtor]p2:
8108 // If a class has no user-declared destructor, a destructor is
8109 // declared implicitly. An implicitly-declared destructor is an
8110 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008111 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008112
Richard Smithafb49182012-11-29 01:34:07 +00008113 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8114 if (DSM.isAlreadyBeingDeclared())
8115 return 0;
8116
Douglas Gregor4923aa22010-07-02 20:37:36 +00008117 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008118 CanQualType ClassType
8119 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008120 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008121 DeclarationName Name
8122 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008123 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008124 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008125 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8126 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008127 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008128 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008129 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008130 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008131
8132 // Build an exception specification pointing back at this destructor.
8133 FunctionProtoType::ExtProtoInfo EPI;
8134 EPI.ExceptionSpecType = EST_Unevaluated;
8135 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00008136 Destructor->setType(Context.getFunctionType(Context.VoidTy,
8137 ArrayRef<QualType>(),
8138 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008139
Richard Smithbc2a35d2012-12-08 08:32:28 +00008140 AddOverriddenMethods(ClassDecl, Destructor);
8141
8142 // We don't need to use SpecialMemberIsTrivial here; triviality for
8143 // destructors is easy to compute.
8144 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8145
8146 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008147 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008148
Douglas Gregor4923aa22010-07-02 20:37:36 +00008149 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008150 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008151
Douglas Gregor4923aa22010-07-02 20:37:36 +00008152 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008153 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008154 PushOnScopeChains(Destructor, S, false);
8155 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008156
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008157 return Destructor;
8158}
8159
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008160void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008161 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008162 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008163 !Destructor->doesThisDeclarationHaveABody() &&
8164 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008165 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008166 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008167 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008168
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008169 if (Destructor->isInvalidDecl())
8170 return;
8171
Eli Friedman9a14db32012-10-18 20:14:08 +00008172 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008173
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008174 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008175 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8176 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008177
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008178 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008179 Diag(CurrentLocation, diag::note_member_synthesized_at)
8180 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8181
8182 Destructor->setInvalidDecl();
8183 return;
8184 }
8185
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008186 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008187 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008188 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008189 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008190 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008191
8192 if (ASTMutationListener *L = getASTMutationListener()) {
8193 L->CompletedImplicitDefinition(Destructor);
8194 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008195}
8196
Richard Smitha4156b82012-04-21 18:42:51 +00008197/// \brief Perform any semantic analysis which needs to be delayed until all
8198/// pending class member declarations have been parsed.
8199void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008200 // If the context is an invalid C++ class, just suppress these checks.
8201 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8202 if (Record->isInvalidDecl()) {
8203 DelayedDestructorExceptionSpecChecks.clear();
8204 return;
8205 }
8206 }
8207
Richard Smitha4156b82012-04-21 18:42:51 +00008208 // Perform any deferred checking of exception specifications for virtual
8209 // destructors.
8210 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8211 i != e; ++i) {
8212 const CXXDestructorDecl *Dtor =
8213 DelayedDestructorExceptionSpecChecks[i].first;
8214 assert(!Dtor->getParent()->isDependentType() &&
8215 "Should not ever add destructors of templates into the list.");
8216 CheckOverridingFunctionExceptionSpec(Dtor,
8217 DelayedDestructorExceptionSpecChecks[i].second);
8218 }
8219 DelayedDestructorExceptionSpecChecks.clear();
8220}
8221
Richard Smithb9d0b762012-07-27 04:22:15 +00008222void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8223 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008224 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008225 "adjusting dtor exception specs was introduced in c++11");
8226
Sebastian Redl0ee33912011-05-19 05:13:44 +00008227 // C++11 [class.dtor]p3:
8228 // A declaration of a destructor that does not have an exception-
8229 // specification is implicitly considered to have the same exception-
8230 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008231 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008232 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008233 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008234 return;
8235
Chandler Carruth3f224b22011-09-20 04:55:26 +00008236 // Replace the destructor's type, building off the existing one. Fortunately,
8237 // the only thing of interest in the destructor type is its extended info.
8238 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008239 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8240 EPI.ExceptionSpecType = EST_Unevaluated;
8241 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00008242 Destructor->setType(Context.getFunctionType(Context.VoidTy,
8243 ArrayRef<QualType>(),
8244 EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008245
Sebastian Redl0ee33912011-05-19 05:13:44 +00008246 // FIXME: If the destructor has a body that could throw, and the newly created
8247 // spec doesn't allow exceptions, we should emit a warning, because this
8248 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008249 // However, we don't have a body or an exception specification yet, so it
8250 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008251}
8252
Richard Smith8c889532012-11-14 00:50:40 +00008253/// When generating a defaulted copy or move assignment operator, if a field
8254/// should be copied with __builtin_memcpy rather than via explicit assignments,
8255/// do so. This optimization only applies for arrays of scalars, and for arrays
8256/// of class type where the selected copy/move-assignment operator is trivial.
8257static StmtResult
8258buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8259 Expr *To, Expr *From) {
8260 // Compute the size of the memory buffer to be copied.
8261 QualType SizeType = S.Context.getSizeType();
8262 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8263 S.Context.getTypeSizeInChars(T).getQuantity());
8264
8265 // Take the address of the field references for "from" and "to". We
8266 // directly construct UnaryOperators here because semantic analysis
8267 // does not permit us to take the address of an xvalue.
8268 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8269 S.Context.getPointerType(From->getType()),
8270 VK_RValue, OK_Ordinary, Loc);
8271 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8272 S.Context.getPointerType(To->getType()),
8273 VK_RValue, OK_Ordinary, Loc);
8274
8275 const Type *E = T->getBaseElementTypeUnsafe();
8276 bool NeedsCollectableMemCpy =
8277 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8278
8279 // Create a reference to the __builtin_objc_memmove_collectable function
8280 StringRef MemCpyName = NeedsCollectableMemCpy ?
8281 "__builtin_objc_memmove_collectable" :
8282 "__builtin_memcpy";
8283 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8284 Sema::LookupOrdinaryName);
8285 S.LookupName(R, S.TUScope, true);
8286
8287 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8288 if (!MemCpy)
8289 // Something went horribly wrong earlier, and we will have complained
8290 // about it.
8291 return StmtError();
8292
8293 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8294 VK_RValue, Loc, 0);
8295 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8296
8297 Expr *CallArgs[] = {
8298 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8299 };
8300 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8301 Loc, CallArgs, Loc);
8302
8303 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8304 return S.Owned(Call.takeAs<Stmt>());
8305}
8306
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008307/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008308/// \c To.
8309///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008310/// This routine is used to copy/move the members of a class with an
8311/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008312/// copied are arrays, this routine builds for loops to copy them.
8313///
8314/// \param S The Sema object used for type-checking.
8315///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008316/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008317///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008318/// \param T The type of the expressions being copied/moved. Both expressions
8319/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008320///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008321/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008322///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008323/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008324///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008325/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008326/// Otherwise, it's a non-static member subobject.
8327///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008328/// \param Copying Whether we're copying or moving.
8329///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008330/// \param Depth Internal parameter recording the depth of the recursion.
8331///
Richard Smith8c889532012-11-14 00:50:40 +00008332/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8333/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008334static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008335buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8336 Expr *To, Expr *From,
8337 bool CopyingBaseSubobject, bool Copying,
8338 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008339 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008340 // Each subobject is assigned in the manner appropriate to its type:
8341 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008342 // - if the subobject is of class type, as if by a call to operator= with
8343 // the subobject as the object expression and the corresponding
8344 // subobject of x as a single function argument (as if by explicit
8345 // qualification; that is, ignoring any possible virtual overriding
8346 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008347 //
8348 // C++03 [class.copy]p13:
8349 // - if the subobject is of class type, the copy assignment operator for
8350 // the class is used (as if by explicit qualification; that is,
8351 // ignoring any possible virtual overriding functions in more derived
8352 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008353 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8354 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008355
Douglas Gregor06a9f362010-05-01 20:49:11 +00008356 // Look for operator=.
8357 DeclarationName Name
8358 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8359 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8360 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008361
Richard Smith044c8aa2012-11-13 00:54:12 +00008362 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8363 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008364 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008365 LookupResult::Filter F = OpLookup.makeFilter();
8366 while (F.hasNext()) {
8367 NamedDecl *D = F.next();
8368 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8369 if (Method->isCopyAssignmentOperator() ||
8370 (!Copying && Method->isMoveAssignmentOperator()))
8371 continue;
8372
8373 F.erase();
8374 }
8375 F.done();
John McCallb0207482010-03-16 06:11:48 +00008376 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008377
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008378 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008379 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008380 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008381 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008382 // ambiguities), we need to cast "this" to that subobject type; to
8383 // ensure that we don't go through the virtual call mechanism, we need
8384 // to qualify the operator= name with the base class (see below). However,
8385 // this means that if the base class has a protected copy assignment
8386 // operator, the protected member access check will fail. So, we
8387 // rewrite "protected" access to "public" access in this case, since we
8388 // know by construction that we're calling from a derived class.
8389 if (CopyingBaseSubobject) {
8390 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8391 L != LEnd; ++L) {
8392 if (L.getAccess() == AS_protected)
8393 L.setAccess(AS_public);
8394 }
8395 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008396
Douglas Gregor06a9f362010-05-01 20:49:11 +00008397 // Create the nested-name-specifier that will be used to qualify the
8398 // reference to operator=; this is required to suppress the virtual
8399 // call mechanism.
8400 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008401 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008402 SS.MakeTrivial(S.Context,
8403 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008404 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008405 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008406
Douglas Gregor06a9f362010-05-01 20:49:11 +00008407 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008408 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008409 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008410 /*TemplateKWLoc=*/SourceLocation(),
8411 /*FirstQualifierInScope=*/0,
8412 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008413 /*TemplateArgs=*/0,
8414 /*SuppressQualifierCheck=*/true);
8415 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008416 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008417
Douglas Gregor06a9f362010-05-01 20:49:11 +00008418 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008419
Richard Smith044c8aa2012-11-13 00:54:12 +00008420 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008421 OpEqualRef.takeAs<Expr>(),
8422 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008423 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008424 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008425
Richard Smith8c889532012-11-14 00:50:40 +00008426 // If we built a call to a trivial 'operator=' while copying an array,
8427 // bail out. We'll replace the whole shebang with a memcpy.
8428 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8429 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8430 return StmtResult((Stmt*)0);
8431
Richard Smith044c8aa2012-11-13 00:54:12 +00008432 // Convert to an expression-statement, and clean up any produced
8433 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008434 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008435 }
John McCallb0207482010-03-16 06:11:48 +00008436
Richard Smith044c8aa2012-11-13 00:54:12 +00008437 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008438 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008439 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008440 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008441 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008442 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008443 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008444 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008445 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008446
8447 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008448 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008449
Douglas Gregor06a9f362010-05-01 20:49:11 +00008450 // Construct a loop over the array bounds, e.g.,
8451 //
8452 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8453 //
8454 // that will copy each of the array elements.
8455 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008456
Douglas Gregor06a9f362010-05-01 20:49:11 +00008457 // Create the iteration variable.
8458 IdentifierInfo *IterationVarName = 0;
8459 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008460 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008461 llvm::raw_svector_ostream OS(Str);
8462 OS << "__i" << Depth;
8463 IterationVarName = &S.Context.Idents.get(OS.str());
8464 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008465 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008466 IterationVarName, SizeType,
8467 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008468 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008469
Douglas Gregor06a9f362010-05-01 20:49:11 +00008470 // Initialize the iteration variable to zero.
8471 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008472 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008473
8474 // Create a reference to the iteration variable; we'll use this several
8475 // times throughout.
8476 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008477 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008478 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008479 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8480 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8481
Douglas Gregor06a9f362010-05-01 20:49:11 +00008482 // Create the DeclStmt that holds the iteration variable.
8483 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008484
Douglas Gregor06a9f362010-05-01 20:49:11 +00008485 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008486 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008487 IterationVarRefRVal,
8488 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008489 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008490 IterationVarRefRVal,
8491 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008492 if (!Copying) // Cast to rvalue
8493 From = CastForMoving(S, From);
8494
8495 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008496 StmtResult Copy =
8497 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8498 To, From, CopyingBaseSubobject,
8499 Copying, Depth + 1);
8500 // Bail out if copying fails or if we determined that we should use memcpy.
8501 if (Copy.isInvalid() || !Copy.get())
8502 return Copy;
8503
8504 // Create the comparison against the array bound.
8505 llvm::APInt Upper
8506 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8507 Expr *Comparison
8508 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8509 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8510 BO_NE, S.Context.BoolTy,
8511 VK_RValue, OK_Ordinary, Loc, false);
8512
8513 // Create the pre-increment of the iteration variable.
8514 Expr *Increment
8515 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8516 VK_LValue, OK_Ordinary, Loc);
8517
Douglas Gregor06a9f362010-05-01 20:49:11 +00008518 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008519 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008520 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008521 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008522 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008523}
8524
Richard Smith8c889532012-11-14 00:50:40 +00008525static StmtResult
8526buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8527 Expr *To, Expr *From,
8528 bool CopyingBaseSubobject, bool Copying) {
8529 // Maybe we should use a memcpy?
8530 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8531 T.isTriviallyCopyableType(S.Context))
8532 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8533
8534 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8535 CopyingBaseSubobject,
8536 Copying, 0));
8537
8538 // If we ended up picking a trivial assignment operator for an array of a
8539 // non-trivially-copyable class type, just emit a memcpy.
8540 if (!Result.isInvalid() && !Result.get())
8541 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8542
8543 return Result;
8544}
8545
Richard Smithb9d0b762012-07-27 04:22:15 +00008546Sema::ImplicitExceptionSpecification
8547Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8548 CXXRecordDecl *ClassDecl = MD->getParent();
8549
8550 ImplicitExceptionSpecification ExceptSpec(*this);
8551 if (ClassDecl->isInvalidDecl())
8552 return ExceptSpec;
8553
8554 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8555 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8556 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8557
Douglas Gregorb87786f2010-07-01 17:48:08 +00008558 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008559 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008560 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008561
8562 // It is unspecified whether or not an implicit copy assignment operator
8563 // attempts to deduplicate calls to assignment operators of virtual bases are
8564 // made. As such, this exception specification is effectively unspecified.
8565 // Based on a similar decision made for constness in C++0x, we're erring on
8566 // the side of assuming such calls to be made regardless of whether they
8567 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008568 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8569 BaseEnd = ClassDecl->bases_end();
8570 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008571 if (Base->isVirtual())
8572 continue;
8573
Douglas Gregora376d102010-07-02 21:50:04 +00008574 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008575 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008576 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8577 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008578 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008579 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008580
8581 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8582 BaseEnd = ClassDecl->vbases_end();
8583 Base != BaseEnd; ++Base) {
8584 CXXRecordDecl *BaseClassDecl
8585 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8586 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8587 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008588 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008589 }
8590
Douglas Gregorb87786f2010-07-01 17:48:08 +00008591 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8592 FieldEnd = ClassDecl->field_end();
8593 Field != FieldEnd;
8594 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008595 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008596 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8597 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008598 LookupCopyingAssignment(FieldClassDecl,
8599 ArgQuals | FieldType.getCVRQualifiers(),
8600 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008601 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008602 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008603 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008604
Richard Smithb9d0b762012-07-27 04:22:15 +00008605 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008606}
8607
8608CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8609 // Note: The following rules are largely analoguous to the copy
8610 // constructor rules. Note that virtual bases are not taken into account
8611 // for determining the argument type of the operator. Note also that
8612 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008613 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008614
Richard Smithafb49182012-11-29 01:34:07 +00008615 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8616 if (DSM.isAlreadyBeingDeclared())
8617 return 0;
8618
Sean Hunt30de05c2011-05-14 05:23:20 +00008619 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8620 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008621 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008622 ArgType = ArgType.withConst();
8623 ArgType = Context.getLValueReferenceType(ArgType);
8624
Douglas Gregord3c35902010-07-01 16:36:15 +00008625 // An implicitly-declared copy assignment operator is an inline public
8626 // member of its class.
8627 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008628 SourceLocation ClassLoc = ClassDecl->getLocation();
8629 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008630 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008631 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008632 /*TInfo=*/0,
8633 /*StorageClass=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008634 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008635 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008636 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008637 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008638 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008639
8640 // Build an exception specification pointing back at this member.
8641 FunctionProtoType::ExtProtoInfo EPI;
8642 EPI.ExceptionSpecType = EST_Unevaluated;
8643 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008644 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008645
Douglas Gregord3c35902010-07-01 16:36:15 +00008646 // Add the parameter to the operator.
8647 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008648 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008649 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008650 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008651 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008652
Richard Smithbc2a35d2012-12-08 08:32:28 +00008653 AddOverriddenMethods(ClassDecl, CopyAssignment);
8654
8655 CopyAssignment->setTrivial(
8656 ClassDecl->needsOverloadResolutionForCopyAssignment()
8657 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8658 : ClassDecl->hasTrivialCopyAssignment());
8659
Nico Weberafcc96a2012-01-23 03:19:29 +00008660 // C++0x [class.copy]p19:
8661 // .... If the class definition does not explicitly declare a copy
8662 // assignment operator, there is no user-declared move constructor, and
8663 // there is no user-declared move assignment operator, a copy assignment
8664 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008665 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008666 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008667
Richard Smithbc2a35d2012-12-08 08:32:28 +00008668 // Note that we have added this copy-assignment operator.
8669 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8670
8671 if (Scope *S = getScopeForContext(ClassDecl))
8672 PushOnScopeChains(CopyAssignment, S, false);
8673 ClassDecl->addDecl(CopyAssignment);
8674
Douglas Gregord3c35902010-07-01 16:36:15 +00008675 return CopyAssignment;
8676}
8677
Douglas Gregor06a9f362010-05-01 20:49:11 +00008678void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8679 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008680 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008681 CopyAssignOperator->isOverloadedOperator() &&
8682 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008683 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8684 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008685 "DefineImplicitCopyAssignment called for wrong function");
8686
8687 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8688
8689 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8690 CopyAssignOperator->setInvalidDecl();
8691 return;
8692 }
8693
8694 CopyAssignOperator->setUsed();
8695
Eli Friedman9a14db32012-10-18 20:14:08 +00008696 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008697 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008698
8699 // C++0x [class.copy]p30:
8700 // The implicitly-defined or explicitly-defaulted copy assignment operator
8701 // for a non-union class X performs memberwise copy assignment of its
8702 // subobjects. The direct base classes of X are assigned first, in the
8703 // order of their declaration in the base-specifier-list, and then the
8704 // immediate non-static data members of X are assigned, in the order in
8705 // which they were declared in the class definition.
8706
8707 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008708 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008709
8710 // The parameter for the "other" object, which we are copying from.
8711 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8712 Qualifiers OtherQuals = Other->getType().getQualifiers();
8713 QualType OtherRefType = Other->getType();
8714 if (const LValueReferenceType *OtherRef
8715 = OtherRefType->getAs<LValueReferenceType>()) {
8716 OtherRefType = OtherRef->getPointeeType();
8717 OtherQuals = OtherRefType.getQualifiers();
8718 }
8719
8720 // Our location for everything implicitly-generated.
8721 SourceLocation Loc = CopyAssignOperator->getLocation();
8722
8723 // Construct a reference to the "other" object. We'll be using this
8724 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008725 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008726 assert(OtherRef && "Reference to parameter cannot fail!");
8727
8728 // Construct the "this" pointer. We'll be using this throughout the generated
8729 // ASTs.
8730 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8731 assert(This && "Reference to this cannot fail!");
8732
8733 // Assign base classes.
8734 bool Invalid = false;
8735 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8736 E = ClassDecl->bases_end(); Base != E; ++Base) {
8737 // Form the assignment:
8738 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8739 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008740 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008741 Invalid = true;
8742 continue;
8743 }
8744
John McCallf871d0c2010-08-07 06:22:56 +00008745 CXXCastPath BasePath;
8746 BasePath.push_back(Base);
8747
Douglas Gregor06a9f362010-05-01 20:49:11 +00008748 // Construct the "from" expression, which is an implicit cast to the
8749 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008750 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008751 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8752 CK_UncheckedDerivedToBase,
8753 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008754
8755 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008756 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008757
8758 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008759 To = ImpCastExprToType(To.take(),
8760 Context.getCVRQualifiedType(BaseType,
8761 CopyAssignOperator->getTypeQualifiers()),
8762 CK_UncheckedDerivedToBase,
8763 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008764
8765 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008766 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008767 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008768 /*CopyingBaseSubobject=*/true,
8769 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008770 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008771 Diag(CurrentLocation, diag::note_member_synthesized_at)
8772 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8773 CopyAssignOperator->setInvalidDecl();
8774 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008775 }
8776
8777 // Success! Record the copy.
8778 Statements.push_back(Copy.takeAs<Expr>());
8779 }
8780
Douglas Gregor06a9f362010-05-01 20:49:11 +00008781 // Assign non-static members.
8782 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8783 FieldEnd = ClassDecl->field_end();
8784 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008785 if (Field->isUnnamedBitfield())
8786 continue;
8787
Douglas Gregor06a9f362010-05-01 20:49:11 +00008788 // Check for members of reference type; we can't copy those.
8789 if (Field->getType()->isReferenceType()) {
8790 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8791 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8792 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008793 Diag(CurrentLocation, diag::note_member_synthesized_at)
8794 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008795 Invalid = true;
8796 continue;
8797 }
8798
8799 // Check for members of const-qualified, non-class type.
8800 QualType BaseType = Context.getBaseElementType(Field->getType());
8801 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8802 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8803 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8804 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008805 Diag(CurrentLocation, diag::note_member_synthesized_at)
8806 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008807 Invalid = true;
8808 continue;
8809 }
John McCallb77115d2011-06-17 00:18:42 +00008810
8811 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008812 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8813 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008814
8815 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008816 if (FieldType->isIncompleteArrayType()) {
8817 assert(ClassDecl->hasFlexibleArrayMember() &&
8818 "Incomplete array type is not valid");
8819 continue;
8820 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008821
8822 // Build references to the field in the object we're copying from and to.
8823 CXXScopeSpec SS; // Intentionally empty
8824 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8825 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008826 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008827 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008828 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008829 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008830 SS, SourceLocation(), 0,
8831 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008832 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008833 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008834 SS, SourceLocation(), 0,
8835 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008836 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8837 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008838
Douglas Gregor06a9f362010-05-01 20:49:11 +00008839 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008840 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008841 To.get(), From.get(),
8842 /*CopyingBaseSubobject=*/false,
8843 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008844 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008845 Diag(CurrentLocation, diag::note_member_synthesized_at)
8846 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8847 CopyAssignOperator->setInvalidDecl();
8848 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008849 }
8850
8851 // Success! Record the copy.
8852 Statements.push_back(Copy.takeAs<Stmt>());
8853 }
8854
8855 if (!Invalid) {
8856 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008857 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008858
John McCall60d7b3a2010-08-24 06:29:42 +00008859 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008860 if (Return.isInvalid())
8861 Invalid = true;
8862 else {
8863 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008864
8865 if (Trap.hasErrorOccurred()) {
8866 Diag(CurrentLocation, diag::note_member_synthesized_at)
8867 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8868 Invalid = true;
8869 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008870 }
8871 }
8872
8873 if (Invalid) {
8874 CopyAssignOperator->setInvalidDecl();
8875 return;
8876 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008877
8878 StmtResult Body;
8879 {
8880 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008881 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008882 /*isStmtExpr=*/false);
8883 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8884 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008885 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008886
8887 if (ASTMutationListener *L = getASTMutationListener()) {
8888 L->CompletedImplicitDefinition(CopyAssignOperator);
8889 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008890}
8891
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008892Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008893Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8894 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008895
Richard Smithb9d0b762012-07-27 04:22:15 +00008896 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008897 if (ClassDecl->isInvalidDecl())
8898 return ExceptSpec;
8899
8900 // C++0x [except.spec]p14:
8901 // An implicitly declared special member function (Clause 12) shall have an
8902 // exception-specification. [...]
8903
8904 // It is unspecified whether or not an implicit move assignment operator
8905 // attempts to deduplicate calls to assignment operators of virtual bases are
8906 // made. As such, this exception specification is effectively unspecified.
8907 // Based on a similar decision made for constness in C++0x, we're erring on
8908 // the side of assuming such calls to be made regardless of whether they
8909 // actually happen.
8910 // Note that a move constructor is not implicitly declared when there are
8911 // virtual bases, but it can still be user-declared and explicitly defaulted.
8912 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8913 BaseEnd = ClassDecl->bases_end();
8914 Base != BaseEnd; ++Base) {
8915 if (Base->isVirtual())
8916 continue;
8917
8918 CXXRecordDecl *BaseClassDecl
8919 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8920 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008921 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008922 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008923 }
8924
8925 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8926 BaseEnd = ClassDecl->vbases_end();
8927 Base != BaseEnd; ++Base) {
8928 CXXRecordDecl *BaseClassDecl
8929 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8930 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008931 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008932 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008933 }
8934
8935 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8936 FieldEnd = ClassDecl->field_end();
8937 Field != FieldEnd;
8938 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008939 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008940 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008941 if (CXXMethodDecl *MoveAssign =
8942 LookupMovingAssignment(FieldClassDecl,
8943 FieldType.getCVRQualifiers(),
8944 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008945 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008946 }
8947 }
8948
8949 return ExceptSpec;
8950}
8951
Richard Smith1c931be2012-04-02 18:40:40 +00008952/// Determine whether the class type has any direct or indirect virtual base
8953/// classes which have a non-trivial move assignment operator.
8954static bool
8955hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8956 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8957 BaseEnd = ClassDecl->vbases_end();
8958 Base != BaseEnd; ++Base) {
8959 CXXRecordDecl *BaseClass =
8960 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8961
8962 // Try to declare the move assignment. If it would be deleted, then the
8963 // class does not have a non-trivial move assignment.
8964 if (BaseClass->needsImplicitMoveAssignment())
8965 S.DeclareImplicitMoveAssignment(BaseClass);
8966
Richard Smith426391c2012-11-16 00:53:38 +00008967 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008968 return true;
8969 }
8970
8971 return false;
8972}
8973
8974/// Determine whether the given type either has a move constructor or is
8975/// trivially copyable.
8976static bool
8977hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8978 Type = S.Context.getBaseElementType(Type);
8979
8980 // FIXME: Technically, non-trivially-copyable non-class types, such as
8981 // reference types, are supposed to return false here, but that appears
8982 // to be a standard defect.
8983 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008984 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008985 return true;
8986
8987 if (Type.isTriviallyCopyableType(S.Context))
8988 return true;
8989
8990 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008991 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8992 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008993 if (ClassDecl->needsImplicitMoveConstructor())
8994 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008995 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008996 }
8997
Richard Smithe5411b72012-12-01 02:35:44 +00008998 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8999 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009000 if (ClassDecl->needsImplicitMoveAssignment())
9001 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009002 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009003}
9004
9005/// Determine whether all non-static data members and direct or virtual bases
9006/// of class \p ClassDecl have either a move operation, or are trivially
9007/// copyable.
9008static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9009 bool IsConstructor) {
9010 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9011 BaseEnd = ClassDecl->bases_end();
9012 Base != BaseEnd; ++Base) {
9013 if (Base->isVirtual())
9014 continue;
9015
9016 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9017 return false;
9018 }
9019
9020 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9021 BaseEnd = ClassDecl->vbases_end();
9022 Base != BaseEnd; ++Base) {
9023 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9024 return false;
9025 }
9026
9027 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9028 FieldEnd = ClassDecl->field_end();
9029 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009030 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009031 return false;
9032 }
9033
9034 return true;
9035}
9036
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009037CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009038 // C++11 [class.copy]p20:
9039 // If the definition of a class X does not explicitly declare a move
9040 // assignment operator, one will be implicitly declared as defaulted
9041 // if and only if:
9042 //
9043 // - [first 4 bullets]
9044 assert(ClassDecl->needsImplicitMoveAssignment());
9045
Richard Smithafb49182012-11-29 01:34:07 +00009046 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9047 if (DSM.isAlreadyBeingDeclared())
9048 return 0;
9049
Richard Smith1c931be2012-04-02 18:40:40 +00009050 // [Checked after we build the declaration]
9051 // - the move assignment operator would not be implicitly defined as
9052 // deleted,
9053
9054 // [DR1402]:
9055 // - X has no direct or indirect virtual base class with a non-trivial
9056 // move assignment operator, and
9057 // - each of X's non-static data members and direct or virtual base classes
9058 // has a type that either has a move assignment operator or is trivially
9059 // copyable.
9060 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9061 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9062 ClassDecl->setFailedImplicitMoveAssignment();
9063 return 0;
9064 }
9065
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009066 // Note: The following rules are largely analoguous to the move
9067 // constructor rules.
9068
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009069 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9070 QualType RetType = Context.getLValueReferenceType(ArgType);
9071 ArgType = Context.getRValueReferenceType(ArgType);
9072
9073 // An implicitly-declared move assignment operator is an inline public
9074 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009075 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9076 SourceLocation ClassLoc = ClassDecl->getLocation();
9077 DeclarationNameInfo NameInfo(Name, ClassLoc);
9078 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00009079 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009080 /*TInfo=*/0,
9081 /*StorageClass=*/SC_None,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009082 /*isInline=*/true,
9083 /*isConstexpr=*/false,
9084 SourceLocation());
9085 MoveAssignment->setAccess(AS_public);
9086 MoveAssignment->setDefaulted();
9087 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009088
Richard Smithb9d0b762012-07-27 04:22:15 +00009089 // Build an exception specification pointing back at this member.
9090 FunctionProtoType::ExtProtoInfo EPI;
9091 EPI.ExceptionSpecType = EST_Unevaluated;
9092 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009093 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009094
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009095 // Add the parameter to the operator.
9096 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9097 ClassLoc, ClassLoc, /*Id=*/0,
9098 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009099 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009100 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009101
Richard Smithbc2a35d2012-12-08 08:32:28 +00009102 AddOverriddenMethods(ClassDecl, MoveAssignment);
9103
9104 MoveAssignment->setTrivial(
9105 ClassDecl->needsOverloadResolutionForMoveAssignment()
9106 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9107 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009108
9109 // C++0x [class.copy]p9:
9110 // If the definition of a class X does not explicitly declare a move
9111 // assignment operator, one will be implicitly declared as defaulted if and
9112 // only if:
9113 // [...]
9114 // - the move assignment operator would not be implicitly defined as
9115 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009116 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009117 // Cache this result so that we don't try to generate this over and over
9118 // on every lookup, leaking memory and wasting time.
9119 ClassDecl->setFailedImplicitMoveAssignment();
9120 return 0;
9121 }
9122
Richard Smithbc2a35d2012-12-08 08:32:28 +00009123 // Note that we have added this copy-assignment operator.
9124 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9125
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009126 if (Scope *S = getScopeForContext(ClassDecl))
9127 PushOnScopeChains(MoveAssignment, S, false);
9128 ClassDecl->addDecl(MoveAssignment);
9129
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009130 return MoveAssignment;
9131}
9132
9133void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9134 CXXMethodDecl *MoveAssignOperator) {
9135 assert((MoveAssignOperator->isDefaulted() &&
9136 MoveAssignOperator->isOverloadedOperator() &&
9137 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009138 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9139 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009140 "DefineImplicitMoveAssignment called for wrong function");
9141
9142 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9143
9144 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9145 MoveAssignOperator->setInvalidDecl();
9146 return;
9147 }
9148
9149 MoveAssignOperator->setUsed();
9150
Eli Friedman9a14db32012-10-18 20:14:08 +00009151 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009152 DiagnosticErrorTrap Trap(Diags);
9153
9154 // C++0x [class.copy]p28:
9155 // The implicitly-defined or move assignment operator for a non-union class
9156 // X performs memberwise move assignment of its subobjects. The direct base
9157 // classes of X are assigned first, in the order of their declaration in the
9158 // base-specifier-list, and then the immediate non-static data members of X
9159 // are assigned, in the order in which they were declared in the class
9160 // definition.
9161
9162 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009163 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009164
9165 // The parameter for the "other" object, which we are move from.
9166 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9167 QualType OtherRefType = Other->getType()->
9168 getAs<RValueReferenceType>()->getPointeeType();
9169 assert(OtherRefType.getQualifiers() == 0 &&
9170 "Bad argument type of defaulted move assignment");
9171
9172 // Our location for everything implicitly-generated.
9173 SourceLocation Loc = MoveAssignOperator->getLocation();
9174
9175 // Construct a reference to the "other" object. We'll be using this
9176 // throughout the generated ASTs.
9177 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9178 assert(OtherRef && "Reference to parameter cannot fail!");
9179 // Cast to rvalue.
9180 OtherRef = CastForMoving(*this, OtherRef);
9181
9182 // Construct the "this" pointer. We'll be using this throughout the generated
9183 // ASTs.
9184 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9185 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009186
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009187 // Assign base classes.
9188 bool Invalid = false;
9189 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9190 E = ClassDecl->bases_end(); Base != E; ++Base) {
9191 // Form the assignment:
9192 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9193 QualType BaseType = Base->getType().getUnqualifiedType();
9194 if (!BaseType->isRecordType()) {
9195 Invalid = true;
9196 continue;
9197 }
9198
9199 CXXCastPath BasePath;
9200 BasePath.push_back(Base);
9201
9202 // Construct the "from" expression, which is an implicit cast to the
9203 // appropriately-qualified base type.
9204 Expr *From = OtherRef;
9205 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009206 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009207
9208 // Dereference "this".
9209 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9210
9211 // Implicitly cast "this" to the appropriately-qualified base type.
9212 To = ImpCastExprToType(To.take(),
9213 Context.getCVRQualifiedType(BaseType,
9214 MoveAssignOperator->getTypeQualifiers()),
9215 CK_UncheckedDerivedToBase,
9216 VK_LValue, &BasePath);
9217
9218 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009219 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009220 To.get(), From,
9221 /*CopyingBaseSubobject=*/true,
9222 /*Copying=*/false);
9223 if (Move.isInvalid()) {
9224 Diag(CurrentLocation, diag::note_member_synthesized_at)
9225 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9226 MoveAssignOperator->setInvalidDecl();
9227 return;
9228 }
9229
9230 // Success! Record the move.
9231 Statements.push_back(Move.takeAs<Expr>());
9232 }
9233
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009234 // Assign non-static members.
9235 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9236 FieldEnd = ClassDecl->field_end();
9237 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009238 if (Field->isUnnamedBitfield())
9239 continue;
9240
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009241 // Check for members of reference type; we can't move those.
9242 if (Field->getType()->isReferenceType()) {
9243 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9244 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9245 Diag(Field->getLocation(), diag::note_declared_at);
9246 Diag(CurrentLocation, diag::note_member_synthesized_at)
9247 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9248 Invalid = true;
9249 continue;
9250 }
9251
9252 // Check for members of const-qualified, non-class type.
9253 QualType BaseType = Context.getBaseElementType(Field->getType());
9254 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9255 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9256 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9257 Diag(Field->getLocation(), diag::note_declared_at);
9258 Diag(CurrentLocation, diag::note_member_synthesized_at)
9259 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9260 Invalid = true;
9261 continue;
9262 }
9263
9264 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009265 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9266 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009267
9268 QualType FieldType = Field->getType().getNonReferenceType();
9269 if (FieldType->isIncompleteArrayType()) {
9270 assert(ClassDecl->hasFlexibleArrayMember() &&
9271 "Incomplete array type is not valid");
9272 continue;
9273 }
9274
9275 // Build references to the field in the object we're copying from and to.
9276 CXXScopeSpec SS; // Intentionally empty
9277 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9278 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009279 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009280 MemberLookup.resolveKind();
9281 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9282 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009283 SS, SourceLocation(), 0,
9284 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009285 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9286 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009287 SS, SourceLocation(), 0,
9288 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009289 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9290 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9291
9292 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9293 "Member reference with rvalue base must be rvalue except for reference "
9294 "members, which aren't allowed for move assignment.");
9295
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009296 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009297 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009298 To.get(), From.get(),
9299 /*CopyingBaseSubobject=*/false,
9300 /*Copying=*/false);
9301 if (Move.isInvalid()) {
9302 Diag(CurrentLocation, diag::note_member_synthesized_at)
9303 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9304 MoveAssignOperator->setInvalidDecl();
9305 return;
9306 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009307
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009308 // Success! Record the copy.
9309 Statements.push_back(Move.takeAs<Stmt>());
9310 }
9311
9312 if (!Invalid) {
9313 // Add a "return *this;"
9314 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9315
9316 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9317 if (Return.isInvalid())
9318 Invalid = true;
9319 else {
9320 Statements.push_back(Return.takeAs<Stmt>());
9321
9322 if (Trap.hasErrorOccurred()) {
9323 Diag(CurrentLocation, diag::note_member_synthesized_at)
9324 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9325 Invalid = true;
9326 }
9327 }
9328 }
9329
9330 if (Invalid) {
9331 MoveAssignOperator->setInvalidDecl();
9332 return;
9333 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009334
9335 StmtResult Body;
9336 {
9337 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009338 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009339 /*isStmtExpr=*/false);
9340 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9341 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009342 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9343
9344 if (ASTMutationListener *L = getASTMutationListener()) {
9345 L->CompletedImplicitDefinition(MoveAssignOperator);
9346 }
9347}
9348
Richard Smithb9d0b762012-07-27 04:22:15 +00009349Sema::ImplicitExceptionSpecification
9350Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9351 CXXRecordDecl *ClassDecl = MD->getParent();
9352
9353 ImplicitExceptionSpecification ExceptSpec(*this);
9354 if (ClassDecl->isInvalidDecl())
9355 return ExceptSpec;
9356
9357 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9358 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9359 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9360
Douglas Gregor0d405db2010-07-01 20:59:04 +00009361 // C++ [except.spec]p14:
9362 // An implicitly declared special member function (Clause 12) shall have an
9363 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009364 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9365 BaseEnd = ClassDecl->bases_end();
9366 Base != BaseEnd;
9367 ++Base) {
9368 // Virtual bases are handled below.
9369 if (Base->isVirtual())
9370 continue;
9371
Douglas Gregor22584312010-07-02 23:41:54 +00009372 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009373 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009374 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009375 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009376 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009377 }
9378 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9379 BaseEnd = ClassDecl->vbases_end();
9380 Base != BaseEnd;
9381 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009382 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009383 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009384 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009385 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009386 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009387 }
9388 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9389 FieldEnd = ClassDecl->field_end();
9390 Field != FieldEnd;
9391 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009392 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009393 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9394 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009395 LookupCopyingConstructor(FieldClassDecl,
9396 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009397 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009398 }
9399 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009400
Richard Smithb9d0b762012-07-27 04:22:15 +00009401 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009402}
9403
9404CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9405 CXXRecordDecl *ClassDecl) {
9406 // C++ [class.copy]p4:
9407 // If the class definition does not explicitly declare a copy
9408 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009409 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009410
Richard Smithafb49182012-11-29 01:34:07 +00009411 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9412 if (DSM.isAlreadyBeingDeclared())
9413 return 0;
9414
Sean Hunt49634cf2011-05-13 06:10:58 +00009415 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9416 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009417 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009418 if (Const)
9419 ArgType = ArgType.withConst();
9420 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009421
Richard Smith7756afa2012-06-10 05:43:50 +00009422 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9423 CXXCopyConstructor,
9424 Const);
9425
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009426 DeclarationName Name
9427 = Context.DeclarationNames.getCXXConstructorName(
9428 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009429 SourceLocation ClassLoc = ClassDecl->getLocation();
9430 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009431
9432 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009433 // member of its class.
9434 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009435 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009436 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009437 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009438 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009439 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009440
Richard Smithb9d0b762012-07-27 04:22:15 +00009441 // Build an exception specification pointing back at this member.
9442 FunctionProtoType::ExtProtoInfo EPI;
9443 EPI.ExceptionSpecType = EST_Unevaluated;
9444 EPI.ExceptionSpecDecl = CopyConstructor;
9445 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009446 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009447
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009448 // Add the parameter to the constructor.
9449 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009450 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009451 /*IdentifierInfo=*/0,
9452 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009453 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009454 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009455
Richard Smithbc2a35d2012-12-08 08:32:28 +00009456 CopyConstructor->setTrivial(
9457 ClassDecl->needsOverloadResolutionForCopyConstructor()
9458 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9459 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009460
Nico Weberafcc96a2012-01-23 03:19:29 +00009461 // C++11 [class.copy]p8:
9462 // ... If the class definition does not explicitly declare a copy
9463 // constructor, there is no user-declared move constructor, and there is no
9464 // user-declared move assignment operator, a copy constructor is implicitly
9465 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009466 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009467 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009468
Richard Smithbc2a35d2012-12-08 08:32:28 +00009469 // Note that we have declared this constructor.
9470 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9471
9472 if (Scope *S = getScopeForContext(ClassDecl))
9473 PushOnScopeChains(CopyConstructor, S, false);
9474 ClassDecl->addDecl(CopyConstructor);
9475
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009476 return CopyConstructor;
9477}
9478
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009479void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009480 CXXConstructorDecl *CopyConstructor) {
9481 assert((CopyConstructor->isDefaulted() &&
9482 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009483 !CopyConstructor->doesThisDeclarationHaveABody() &&
9484 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009485 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009486
Anders Carlsson63010a72010-04-23 16:24:12 +00009487 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009488 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009489
Eli Friedman9a14db32012-10-18 20:14:08 +00009490 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009491 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009492
David Blaikie93c86172013-01-17 05:26:25 +00009493 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009494 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009495 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009496 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009497 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009498 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009499 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009500 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9501 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009502 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009503 /*isStmtExpr=*/false)
9504 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009505 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009506 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009507
9508 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009509 if (ASTMutationListener *L = getASTMutationListener()) {
9510 L->CompletedImplicitDefinition(CopyConstructor);
9511 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009512}
9513
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009514Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009515Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9516 CXXRecordDecl *ClassDecl = MD->getParent();
9517
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009518 // C++ [except.spec]p14:
9519 // An implicitly declared special member function (Clause 12) shall have an
9520 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009521 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009522 if (ClassDecl->isInvalidDecl())
9523 return ExceptSpec;
9524
9525 // Direct base-class constructors.
9526 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9527 BEnd = ClassDecl->bases_end();
9528 B != BEnd; ++B) {
9529 if (B->isVirtual()) // Handled below.
9530 continue;
9531
9532 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9533 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009534 CXXConstructorDecl *Constructor =
9535 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009536 // If this is a deleted function, add it anyway. This might be conformant
9537 // with the standard. This might not. I'm not sure. It might not matter.
9538 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009539 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009540 }
9541 }
9542
9543 // Virtual base-class constructors.
9544 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9545 BEnd = ClassDecl->vbases_end();
9546 B != BEnd; ++B) {
9547 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9548 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009549 CXXConstructorDecl *Constructor =
9550 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009551 // If this is a deleted function, add it anyway. This might be conformant
9552 // with the standard. This might not. I'm not sure. It might not matter.
9553 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009554 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009555 }
9556 }
9557
9558 // Field constructors.
9559 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9560 FEnd = ClassDecl->field_end();
9561 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009562 QualType FieldType = Context.getBaseElementType(F->getType());
9563 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9564 CXXConstructorDecl *Constructor =
9565 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009566 // If this is a deleted function, add it anyway. This might be conformant
9567 // with the standard. This might not. I'm not sure. It might not matter.
9568 // In particular, the problem is that this function never gets called. It
9569 // might just be ill-formed because this function attempts to refer to
9570 // a deleted function here.
9571 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009572 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009573 }
9574 }
9575
9576 return ExceptSpec;
9577}
9578
9579CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9580 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009581 // C++11 [class.copy]p9:
9582 // If the definition of a class X does not explicitly declare a move
9583 // constructor, one will be implicitly declared as defaulted if and only if:
9584 //
9585 // - [first 4 bullets]
9586 assert(ClassDecl->needsImplicitMoveConstructor());
9587
Richard Smithafb49182012-11-29 01:34:07 +00009588 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9589 if (DSM.isAlreadyBeingDeclared())
9590 return 0;
9591
Richard Smith1c931be2012-04-02 18:40:40 +00009592 // [Checked after we build the declaration]
9593 // - the move assignment operator would not be implicitly defined as
9594 // deleted,
9595
9596 // [DR1402]:
9597 // - each of X's non-static data members and direct or virtual base classes
9598 // has a type that either has a move constructor or is trivially copyable.
9599 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9600 ClassDecl->setFailedImplicitMoveConstructor();
9601 return 0;
9602 }
9603
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009604 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9605 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009606
Richard Smith7756afa2012-06-10 05:43:50 +00009607 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9608 CXXMoveConstructor,
9609 false);
9610
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009611 DeclarationName Name
9612 = Context.DeclarationNames.getCXXConstructorName(
9613 Context.getCanonicalType(ClassType));
9614 SourceLocation ClassLoc = ClassDecl->getLocation();
9615 DeclarationNameInfo NameInfo(Name, ClassLoc);
9616
9617 // C++0x [class.copy]p11:
9618 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009619 // member of its class.
9620 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009621 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009622 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009623 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009624 MoveConstructor->setAccess(AS_public);
9625 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009626
Richard Smithb9d0b762012-07-27 04:22:15 +00009627 // Build an exception specification pointing back at this member.
9628 FunctionProtoType::ExtProtoInfo EPI;
9629 EPI.ExceptionSpecType = EST_Unevaluated;
9630 EPI.ExceptionSpecDecl = MoveConstructor;
9631 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009632 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009633
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009634 // Add the parameter to the constructor.
9635 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9636 ClassLoc, ClassLoc,
9637 /*IdentifierInfo=*/0,
9638 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009639 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009640 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009641
Richard Smithbc2a35d2012-12-08 08:32:28 +00009642 MoveConstructor->setTrivial(
9643 ClassDecl->needsOverloadResolutionForMoveConstructor()
9644 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9645 : ClassDecl->hasTrivialMoveConstructor());
9646
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009647 // C++0x [class.copy]p9:
9648 // If the definition of a class X does not explicitly declare a move
9649 // constructor, one will be implicitly declared as defaulted if and only if:
9650 // [...]
9651 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009652 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009653 // Cache this result so that we don't try to generate this over and over
9654 // on every lookup, leaking memory and wasting time.
9655 ClassDecl->setFailedImplicitMoveConstructor();
9656 return 0;
9657 }
9658
9659 // Note that we have declared this constructor.
9660 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9661
9662 if (Scope *S = getScopeForContext(ClassDecl))
9663 PushOnScopeChains(MoveConstructor, S, false);
9664 ClassDecl->addDecl(MoveConstructor);
9665
9666 return MoveConstructor;
9667}
9668
9669void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9670 CXXConstructorDecl *MoveConstructor) {
9671 assert((MoveConstructor->isDefaulted() &&
9672 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009673 !MoveConstructor->doesThisDeclarationHaveABody() &&
9674 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009675 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9676
9677 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9678 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9679
Eli Friedman9a14db32012-10-18 20:14:08 +00009680 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009681 DiagnosticErrorTrap Trap(Diags);
9682
David Blaikie93c86172013-01-17 05:26:25 +00009683 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009684 Trap.hasErrorOccurred()) {
9685 Diag(CurrentLocation, diag::note_member_synthesized_at)
9686 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9687 MoveConstructor->setInvalidDecl();
9688 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009689 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009690 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9691 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009692 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009693 /*isStmtExpr=*/false)
9694 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009695 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009696 }
9697
9698 MoveConstructor->setUsed();
9699
9700 if (ASTMutationListener *L = getASTMutationListener()) {
9701 L->CompletedImplicitDefinition(MoveConstructor);
9702 }
9703}
9704
Douglas Gregore4e68d42012-02-15 19:33:52 +00009705bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9706 return FD->isDeleted() &&
9707 (FD->isDefaulted() || FD->isImplicit()) &&
9708 isa<CXXMethodDecl>(FD);
9709}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009710
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009711/// \brief Mark the call operator of the given lambda closure type as "used".
9712static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9713 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009714 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009715 Lambda->lookup(
9716 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009717 CallOperator->setReferenced();
9718 CallOperator->setUsed();
9719}
9720
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009721void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9722 SourceLocation CurrentLocation,
9723 CXXConversionDecl *Conv)
9724{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009725 CXXRecordDecl *Lambda = Conv->getParent();
9726
9727 // Make sure that the lambda call operator is marked used.
9728 markLambdaCallOperatorUsed(*this, Lambda);
9729
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009730 Conv->setUsed();
9731
Eli Friedman9a14db32012-10-18 20:14:08 +00009732 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009733 DiagnosticErrorTrap Trap(Diags);
9734
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009735 // Return the address of the __invoke function.
9736 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9737 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009738 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009739 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9740 VK_LValue, Conv->getLocation()).take();
9741 assert(FunctionRef && "Can't refer to __invoke function?");
9742 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009743 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009744 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009745 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009746
9747 // Fill in the __invoke function with a dummy implementation. IR generation
9748 // will fill in the actual details.
9749 Invoke->setUsed();
9750 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009751 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009752
9753 if (ASTMutationListener *L = getASTMutationListener()) {
9754 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009755 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009756 }
9757}
9758
9759void Sema::DefineImplicitLambdaToBlockPointerConversion(
9760 SourceLocation CurrentLocation,
9761 CXXConversionDecl *Conv)
9762{
9763 Conv->setUsed();
9764
Eli Friedman9a14db32012-10-18 20:14:08 +00009765 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009766 DiagnosticErrorTrap Trap(Diags);
9767
Douglas Gregorac1303e2012-02-22 05:02:47 +00009768 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009769 Expr *This = ActOnCXXThis(CurrentLocation).take();
9770 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009771
Eli Friedman23f02672012-03-01 04:01:32 +00009772 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9773 Conv->getLocation(),
9774 Conv, DerefThis);
9775
9776 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9777 // behavior. Note that only the general conversion function does this
9778 // (since it's unusable otherwise); in the case where we inline the
9779 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009780 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009781 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9782 CK_CopyAndAutoreleaseBlockObject,
9783 BuildBlock.get(), 0, VK_RValue);
9784
9785 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009786 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009787 Conv->setInvalidDecl();
9788 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009789 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009790
Douglas Gregorac1303e2012-02-22 05:02:47 +00009791 // Create the return statement that returns the block from the conversion
9792 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009793 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009794 if (Return.isInvalid()) {
9795 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9796 Conv->setInvalidDecl();
9797 return;
9798 }
9799
9800 // Set the body of the conversion function.
9801 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009802 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009803 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009804 Conv->getLocation()));
9805
Douglas Gregorac1303e2012-02-22 05:02:47 +00009806 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009807 if (ASTMutationListener *L = getASTMutationListener()) {
9808 L->CompletedImplicitDefinition(Conv);
9809 }
9810}
9811
Douglas Gregorf52757d2012-03-10 06:53:13 +00009812/// \brief Determine whether the given list arguments contains exactly one
9813/// "real" (non-default) argument.
9814static bool hasOneRealArgument(MultiExprArg Args) {
9815 switch (Args.size()) {
9816 case 0:
9817 return false;
9818
9819 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009820 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009821 return false;
9822
9823 // fall through
9824 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009825 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009826 }
9827
9828 return false;
9829}
9830
John McCall60d7b3a2010-08-24 06:29:42 +00009831ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009832Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009833 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009834 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009835 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009836 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009837 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009838 unsigned ConstructKind,
9839 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009840 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009841
Douglas Gregor2f599792010-04-02 18:24:57 +00009842 // C++0x [class.copy]p34:
9843 // When certain criteria are met, an implementation is allowed to
9844 // omit the copy/move construction of a class object, even if the
9845 // copy/move constructor and/or destructor for the object have
9846 // side effects. [...]
9847 // - when a temporary class object that has not been bound to a
9848 // reference (12.2) would be copied/moved to a class object
9849 // with the same cv-unqualified type, the copy/move operation
9850 // can be omitted by constructing the temporary object
9851 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009852 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009853 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009854 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009855 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009856 }
Mike Stump1eb44332009-09-09 15:08:12 +00009857
9858 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009859 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009860 IsListInitialization, RequiresZeroInit,
9861 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009862}
9863
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009864/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9865/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009866ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009867Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9868 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009869 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009870 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009871 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009872 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009873 unsigned ConstructKind,
9874 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009875 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009876 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009877 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +00009878 HadMultipleCandidates,
9879 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009880 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9881 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009882}
9883
John McCall68c6c9a2010-02-02 09:10:11 +00009884void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009885 if (VD->isInvalidDecl()) return;
9886
John McCall68c6c9a2010-02-02 09:10:11 +00009887 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009888 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009889 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009890 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009891
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009892 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009893 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009894 CheckDestructorAccess(VD->getLocation(), Destructor,
9895 PDiag(diag::err_access_dtor_var)
9896 << VD->getDeclName()
9897 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009898 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009899
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009900 if (!VD->hasGlobalStorage()) return;
9901
9902 // Emit warning for non-trivial dtor in global scope (a real global,
9903 // class-static, function-static).
9904 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9905
9906 // TODO: this should be re-enabled for static locals by !CXAAtExit
9907 if (!VD->isStaticLocal())
9908 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009909}
9910
Douglas Gregor39da0b82009-09-09 23:08:42 +00009911/// \brief Given a constructor and the set of arguments provided for the
9912/// constructor, convert the arguments and add any required default arguments
9913/// to form a proper call to this constructor.
9914///
9915/// \returns true if an error occurred, false otherwise.
9916bool
9917Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9918 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009919 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009920 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009921 bool AllowExplicit,
9922 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009923 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9924 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009925 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009926
9927 const FunctionProtoType *Proto
9928 = Constructor->getType()->getAs<FunctionProtoType>();
9929 assert(Proto && "Constructor without a prototype?");
9930 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009931
9932 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009933 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009934 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009935 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009936 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009937
9938 VariadicCallType CallType =
9939 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009940 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009941 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9942 Proto, 0, Args, NumArgs, AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009943 CallType, AllowExplicit,
9944 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009945 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009946
9947 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9948
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00009949 CheckConstructorCall(Constructor,
9950 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9951 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +00009952 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009953
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009954 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009955}
9956
Anders Carlsson20d45d22009-12-12 00:32:00 +00009957static inline bool
9958CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9959 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009960 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009961 if (isa<NamespaceDecl>(DC)) {
9962 return SemaRef.Diag(FnDecl->getLocation(),
9963 diag::err_operator_new_delete_declared_in_namespace)
9964 << FnDecl->getDeclName();
9965 }
9966
9967 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009968 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009969 return SemaRef.Diag(FnDecl->getLocation(),
9970 diag::err_operator_new_delete_declared_static)
9971 << FnDecl->getDeclName();
9972 }
9973
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009974 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009975}
9976
Anders Carlsson156c78e2009-12-13 17:53:43 +00009977static inline bool
9978CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9979 CanQualType ExpectedResultType,
9980 CanQualType ExpectedFirstParamType,
9981 unsigned DependentParamTypeDiag,
9982 unsigned InvalidParamTypeDiag) {
9983 QualType ResultType =
9984 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9985
9986 // Check that the result type is not dependent.
9987 if (ResultType->isDependentType())
9988 return SemaRef.Diag(FnDecl->getLocation(),
9989 diag::err_operator_new_delete_dependent_result_type)
9990 << FnDecl->getDeclName() << ExpectedResultType;
9991
9992 // Check that the result type is what we expect.
9993 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9994 return SemaRef.Diag(FnDecl->getLocation(),
9995 diag::err_operator_new_delete_invalid_result_type)
9996 << FnDecl->getDeclName() << ExpectedResultType;
9997
9998 // A function template must have at least 2 parameters.
9999 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10000 return SemaRef.Diag(FnDecl->getLocation(),
10001 diag::err_operator_new_delete_template_too_few_parameters)
10002 << FnDecl->getDeclName();
10003
10004 // The function decl must have at least 1 parameter.
10005 if (FnDecl->getNumParams() == 0)
10006 return SemaRef.Diag(FnDecl->getLocation(),
10007 diag::err_operator_new_delete_too_few_parameters)
10008 << FnDecl->getDeclName();
10009
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010010 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010011 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10012 if (FirstParamType->isDependentType())
10013 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10014 << FnDecl->getDeclName() << ExpectedFirstParamType;
10015
10016 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010017 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010018 ExpectedFirstParamType)
10019 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10020 << FnDecl->getDeclName() << ExpectedFirstParamType;
10021
10022 return false;
10023}
10024
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010025static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010026CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010027 // C++ [basic.stc.dynamic.allocation]p1:
10028 // A program is ill-formed if an allocation function is declared in a
10029 // namespace scope other than global scope or declared static in global
10030 // scope.
10031 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10032 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010033
10034 CanQualType SizeTy =
10035 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10036
10037 // C++ [basic.stc.dynamic.allocation]p1:
10038 // The return type shall be void*. The first parameter shall have type
10039 // std::size_t.
10040 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10041 SizeTy,
10042 diag::err_operator_new_dependent_param_type,
10043 diag::err_operator_new_param_type))
10044 return true;
10045
10046 // C++ [basic.stc.dynamic.allocation]p1:
10047 // The first parameter shall not have an associated default argument.
10048 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010049 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010050 diag::err_operator_new_default_arg)
10051 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10052
10053 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010054}
10055
10056static bool
Richard Smith444d3842012-10-20 08:26:51 +000010057CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010058 // C++ [basic.stc.dynamic.deallocation]p1:
10059 // A program is ill-formed if deallocation functions are declared in a
10060 // namespace scope other than global scope or declared static in global
10061 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010062 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10063 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010064
10065 // C++ [basic.stc.dynamic.deallocation]p2:
10066 // Each deallocation function shall return void and its first parameter
10067 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010068 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10069 SemaRef.Context.VoidPtrTy,
10070 diag::err_operator_delete_dependent_param_type,
10071 diag::err_operator_delete_param_type))
10072 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010073
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010074 return false;
10075}
10076
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010077/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10078/// of this overloaded operator is well-formed. If so, returns false;
10079/// otherwise, emits appropriate diagnostics and returns true.
10080bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010081 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010082 "Expected an overloaded operator declaration");
10083
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010084 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10085
Mike Stump1eb44332009-09-09 15:08:12 +000010086 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010087 // The allocation and deallocation functions, operator new,
10088 // operator new[], operator delete and operator delete[], are
10089 // described completely in 3.7.3. The attributes and restrictions
10090 // found in the rest of this subclause do not apply to them unless
10091 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010092 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010093 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010094
Anders Carlssona3ccda52009-12-12 00:26:23 +000010095 if (Op == OO_New || Op == OO_Array_New)
10096 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010097
10098 // C++ [over.oper]p6:
10099 // An operator function shall either be a non-static member
10100 // function or be a non-member function and have at least one
10101 // parameter whose type is a class, a reference to a class, an
10102 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010103 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10104 if (MethodDecl->isStatic())
10105 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010106 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010107 } else {
10108 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010109 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10110 ParamEnd = FnDecl->param_end();
10111 Param != ParamEnd; ++Param) {
10112 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010113 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10114 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010115 ClassOrEnumParam = true;
10116 break;
10117 }
10118 }
10119
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010120 if (!ClassOrEnumParam)
10121 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010122 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010123 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010124 }
10125
10126 // C++ [over.oper]p8:
10127 // An operator function cannot have default arguments (8.3.6),
10128 // except where explicitly stated below.
10129 //
Mike Stump1eb44332009-09-09 15:08:12 +000010130 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010131 // (C++ [over.call]p1).
10132 if (Op != OO_Call) {
10133 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10134 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010135 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010136 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010137 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010138 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010139 }
10140 }
10141
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010142 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10143 { false, false, false }
10144#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10145 , { Unary, Binary, MemberOnly }
10146#include "clang/Basic/OperatorKinds.def"
10147 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010148
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010149 bool CanBeUnaryOperator = OperatorUses[Op][0];
10150 bool CanBeBinaryOperator = OperatorUses[Op][1];
10151 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010152
10153 // C++ [over.oper]p8:
10154 // [...] Operator functions cannot have more or fewer parameters
10155 // than the number required for the corresponding operator, as
10156 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010157 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010158 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010159 if (Op != OO_Call &&
10160 ((NumParams == 1 && !CanBeUnaryOperator) ||
10161 (NumParams == 2 && !CanBeBinaryOperator) ||
10162 (NumParams < 1) || (NumParams > 2))) {
10163 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010164 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010165 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010166 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010167 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010168 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010169 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010170 assert(CanBeBinaryOperator &&
10171 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010172 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010173 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010174
Chris Lattner416e46f2008-11-21 07:57:12 +000010175 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010176 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010177 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010178
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010179 // Overloaded operators other than operator() cannot be variadic.
10180 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010181 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010182 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010183 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010184 }
10185
10186 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010187 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10188 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010189 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010190 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010191 }
10192
10193 // C++ [over.inc]p1:
10194 // The user-defined function called operator++ implements the
10195 // prefix and postfix ++ operator. If this function is a member
10196 // function with no parameters, or a non-member function with one
10197 // parameter of class or enumeration type, it defines the prefix
10198 // increment operator ++ for objects of that type. If the function
10199 // is a member function with one parameter (which shall be of type
10200 // int) or a non-member function with two parameters (the second
10201 // of which shall be of type int), it defines the postfix
10202 // increment operator ++ for objects of that type.
10203 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10204 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10205 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010206 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010207 ParamIsInt = BT->getKind() == BuiltinType::Int;
10208
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010209 if (!ParamIsInt)
10210 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010211 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010212 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010213 }
10214
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010215 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010216}
Chris Lattner5a003a42008-12-17 07:09:26 +000010217
Sean Hunta6c058d2010-01-13 09:01:02 +000010218/// CheckLiteralOperatorDeclaration - Check whether the declaration
10219/// of this literal operator function is well-formed. If so, returns
10220/// false; otherwise, emits appropriate diagnostics and returns true.
10221bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010222 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010223 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10224 << FnDecl->getDeclName();
10225 return true;
10226 }
10227
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010228 if (FnDecl->isExternC()) {
10229 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10230 return true;
10231 }
10232
Sean Hunta6c058d2010-01-13 09:01:02 +000010233 bool Valid = false;
10234
Richard Smith36f5cfe2012-03-09 08:00:36 +000010235 // This might be the definition of a literal operator template.
10236 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10237 // This might be a specialization of a literal operator template.
10238 if (!TpDecl)
10239 TpDecl = FnDecl->getPrimaryTemplate();
10240
Sean Hunt216c2782010-04-07 23:11:06 +000010241 // template <char...> type operator "" name() is the only valid template
10242 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010243 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010244 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010245 // Must have only one template parameter
10246 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10247 if (Params->size() == 1) {
10248 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010249 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010250
Sean Hunt216c2782010-04-07 23:11:06 +000010251 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010252 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10253 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10254 Valid = true;
10255 }
10256 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010257 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010258 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010259 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10260
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010261 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010262
Sean Hunt30019c02010-04-07 22:57:35 +000010263 // unsigned long long int, long double, and any character type are allowed
10264 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010265 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10266 Context.hasSameType(T, Context.LongDoubleTy) ||
10267 Context.hasSameType(T, Context.CharTy) ||
10268 Context.hasSameType(T, Context.WCharTy) ||
10269 Context.hasSameType(T, Context.Char16Ty) ||
10270 Context.hasSameType(T, Context.Char32Ty)) {
10271 if (++Param == FnDecl->param_end())
10272 Valid = true;
10273 goto FinishedParams;
10274 }
10275
Sean Hunt30019c02010-04-07 22:57:35 +000010276 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010277 const PointerType *PT = T->getAs<PointerType>();
10278 if (!PT)
10279 goto FinishedParams;
10280 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010281 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010282 goto FinishedParams;
10283 T = T.getUnqualifiedType();
10284
10285 // Move on to the second parameter;
10286 ++Param;
10287
10288 // If there is no second parameter, the first must be a const char *
10289 if (Param == FnDecl->param_end()) {
10290 if (Context.hasSameType(T, Context.CharTy))
10291 Valid = true;
10292 goto FinishedParams;
10293 }
10294
10295 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10296 // are allowed as the first parameter to a two-parameter function
10297 if (!(Context.hasSameType(T, Context.CharTy) ||
10298 Context.hasSameType(T, Context.WCharTy) ||
10299 Context.hasSameType(T, Context.Char16Ty) ||
10300 Context.hasSameType(T, Context.Char32Ty)))
10301 goto FinishedParams;
10302
10303 // The second and final parameter must be an std::size_t
10304 T = (*Param)->getType().getUnqualifiedType();
10305 if (Context.hasSameType(T, Context.getSizeType()) &&
10306 ++Param == FnDecl->param_end())
10307 Valid = true;
10308 }
10309
10310 // FIXME: This diagnostic is absolutely terrible.
10311FinishedParams:
10312 if (!Valid) {
10313 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10314 << FnDecl->getDeclName();
10315 return true;
10316 }
10317
Richard Smitha9e88b22012-03-09 08:16:22 +000010318 // A parameter-declaration-clause containing a default argument is not
10319 // equivalent to any of the permitted forms.
10320 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10321 ParamEnd = FnDecl->param_end();
10322 Param != ParamEnd; ++Param) {
10323 if ((*Param)->hasDefaultArg()) {
10324 Diag((*Param)->getDefaultArgRange().getBegin(),
10325 diag::err_literal_operator_default_argument)
10326 << (*Param)->getDefaultArgRange();
10327 break;
10328 }
10329 }
10330
Richard Smith2fb4ae32012-03-08 02:39:21 +000010331 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010332 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10333 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010334 // C++11 [usrlit.suffix]p1:
10335 // Literal suffix identifiers that do not start with an underscore
10336 // are reserved for future standardization.
10337 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010338 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010339
Sean Hunta6c058d2010-01-13 09:01:02 +000010340 return false;
10341}
10342
Douglas Gregor074149e2009-01-05 19:45:36 +000010343/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10344/// linkage specification, including the language and (if present)
10345/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10346/// the location of the language string literal, which is provided
10347/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10348/// the '{' brace. Otherwise, this linkage specification does not
10349/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010350Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10351 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010352 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010353 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010354 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010355 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010356 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010357 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010358 Language = LinkageSpecDecl::lang_cxx;
10359 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010360 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010361 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010362 }
Mike Stump1eb44332009-09-09 15:08:12 +000010363
Chris Lattnercc98eac2008-12-17 07:13:27 +000010364 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010365
Douglas Gregor074149e2009-01-05 19:45:36 +000010366 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010367 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010368 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010369 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010370 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010371}
10372
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010373/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010374/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10375/// valid, it's the position of the closing '}' brace in a linkage
10376/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010377Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010378 Decl *LinkageSpec,
10379 SourceLocation RBraceLoc) {
10380 if (LinkageSpec) {
10381 if (RBraceLoc.isValid()) {
10382 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10383 LSDecl->setRBraceLoc(RBraceLoc);
10384 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010385 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010386 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010387 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010388}
10389
Michael Han684aa732013-02-22 17:15:32 +000010390Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10391 AttributeList *AttrList,
10392 SourceLocation SemiLoc) {
10393 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10394 // Attribute declarations appertain to empty declaration so we handle
10395 // them here.
10396 if (AttrList)
10397 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010398
Michael Han684aa732013-02-22 17:15:32 +000010399 CurContext->addDecl(ED);
10400 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010401}
10402
Douglas Gregord308e622009-05-18 20:51:54 +000010403/// \brief Perform semantic analysis for the variable declaration that
10404/// occurs within a C++ catch clause, returning the newly-created
10405/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010406VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010407 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010408 SourceLocation StartLoc,
10409 SourceLocation Loc,
10410 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010411 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010412 QualType ExDeclType = TInfo->getType();
10413
Sebastian Redl4b07b292008-12-22 19:15:10 +000010414 // Arrays and functions decay.
10415 if (ExDeclType->isArrayType())
10416 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10417 else if (ExDeclType->isFunctionType())
10418 ExDeclType = Context.getPointerType(ExDeclType);
10419
10420 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10421 // The exception-declaration shall not denote a pointer or reference to an
10422 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010423 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010424 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010425 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010426 Invalid = true;
10427 }
Douglas Gregord308e622009-05-18 20:51:54 +000010428
Sebastian Redl4b07b292008-12-22 19:15:10 +000010429 QualType BaseType = ExDeclType;
10430 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010431 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010432 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010433 BaseType = Ptr->getPointeeType();
10434 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010435 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010436 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010437 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010438 BaseType = Ref->getPointeeType();
10439 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010440 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010441 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010442 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010443 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010444 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010445
Mike Stump1eb44332009-09-09 15:08:12 +000010446 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010447 RequireNonAbstractType(Loc, ExDeclType,
10448 diag::err_abstract_type_in_decl,
10449 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010450 Invalid = true;
10451
John McCall5a180392010-07-24 00:37:23 +000010452 // Only the non-fragile NeXT runtime currently supports C++ catches
10453 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010454 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010455 QualType T = ExDeclType;
10456 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10457 T = RT->getPointeeType();
10458
10459 if (T->isObjCObjectType()) {
10460 Diag(Loc, diag::err_objc_object_catch);
10461 Invalid = true;
10462 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010463 // FIXME: should this be a test for macosx-fragile specifically?
10464 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010465 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010466 }
10467 }
10468
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010469 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010470 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010471 ExDecl->setExceptionVariable(true);
10472
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010473 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010474 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010475 Invalid = true;
10476
Douglas Gregorc41b8782011-07-06 18:14:43 +000010477 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010478 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010479 // Insulate this from anything else we might currently be parsing.
10480 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10481
Douglas Gregor6d182892010-03-05 23:38:39 +000010482 // C++ [except.handle]p16:
10483 // The object declared in an exception-declaration or, if the
10484 // exception-declaration does not specify a name, a temporary (12.2) is
10485 // copy-initialized (8.5) from the exception object. [...]
10486 // The object is destroyed when the handler exits, after the destruction
10487 // of any automatic objects initialized within the handler.
10488 //
10489 // We just pretend to initialize the object with itself, then make sure
10490 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010491 QualType initType = ExDeclType;
10492
10493 InitializedEntity entity =
10494 InitializedEntity::InitializeVariable(ExDecl);
10495 InitializationKind initKind =
10496 InitializationKind::CreateCopy(Loc, SourceLocation());
10497
10498 Expr *opaqueValue =
10499 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10500 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10501 ExprResult result = sequence.Perform(*this, entity, initKind,
10502 MultiExprArg(&opaqueValue, 1));
10503 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010504 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010505 else {
10506 // If the constructor used was non-trivial, set this as the
10507 // "initializer".
10508 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10509 if (!construct->getConstructor()->isTrivial()) {
10510 Expr *init = MaybeCreateExprWithCleanups(construct);
10511 ExDecl->setInit(init);
10512 }
10513
10514 // And make sure it's destructable.
10515 FinalizeVarWithDestructor(ExDecl, recordType);
10516 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010517 }
10518 }
10519
Douglas Gregord308e622009-05-18 20:51:54 +000010520 if (Invalid)
10521 ExDecl->setInvalidDecl();
10522
10523 return ExDecl;
10524}
10525
10526/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10527/// handler.
John McCalld226f652010-08-21 09:40:31 +000010528Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010529 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010530 bool Invalid = D.isInvalidType();
10531
10532 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010533 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10534 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010535 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10536 D.getIdentifierLoc());
10537 Invalid = true;
10538 }
10539
Sebastian Redl4b07b292008-12-22 19:15:10 +000010540 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010541 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010542 LookupOrdinaryName,
10543 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010544 // The scope should be freshly made just for us. There is just no way
10545 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010546 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010547 if (PrevDecl->isTemplateParameter()) {
10548 // Maybe we will complain about the shadowed template parameter.
10549 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010550 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010551 }
10552 }
10553
Chris Lattnereaaebc72009-04-25 08:06:05 +000010554 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010555 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10556 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010557 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010558 }
10559
Douglas Gregor83cb9422010-09-09 17:09:21 +000010560 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010561 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010562 D.getIdentifierLoc(),
10563 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010564 if (Invalid)
10565 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010566
Sebastian Redl4b07b292008-12-22 19:15:10 +000010567 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010568 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010569 PushOnScopeChains(ExDecl, S);
10570 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010571 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010572
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010573 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010574 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010575}
Anders Carlssonfb311762009-03-14 00:25:26 +000010576
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010577Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010578 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010579 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010580 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010581 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010582
Richard Smithe3f470a2012-07-11 22:37:56 +000010583 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10584 return 0;
10585
10586 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10587 AssertMessage, RParenLoc, false);
10588}
10589
10590Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10591 Expr *AssertExpr,
10592 StringLiteral *AssertMessage,
10593 SourceLocation RParenLoc,
10594 bool Failed) {
10595 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10596 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010597 // In a static_assert-declaration, the constant-expression shall be a
10598 // constant expression that can be contextually converted to bool.
10599 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10600 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010601 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010602
Richard Smithdaaefc52011-12-14 23:32:26 +000010603 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010604 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010605 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010606 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010607 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010608
Richard Smithe3f470a2012-07-11 22:37:56 +000010609 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010610 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010611 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010612 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010613 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010614 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010615 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010616 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010617 }
Mike Stump1eb44332009-09-09 15:08:12 +000010618
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010619 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010620 AssertExpr, AssertMessage, RParenLoc,
10621 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010622
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010623 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010624 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010625}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010626
Douglas Gregor1d869352010-04-07 16:53:43 +000010627/// \brief Perform semantic analysis of the given friend type declaration.
10628///
10629/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010630FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010631 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010632 TypeSourceInfo *TSInfo) {
10633 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10634
10635 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010636 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010637
Richard Smith6b130222011-10-18 21:39:00 +000010638 // C++03 [class.friend]p2:
10639 // An elaborated-type-specifier shall be used in a friend declaration
10640 // for a class.*
10641 //
10642 // * The class-key of the elaborated-type-specifier is required.
10643 if (!ActiveTemplateInstantiations.empty()) {
10644 // Do not complain about the form of friend template types during
10645 // template instantiation; we will already have complained when the
10646 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010647 } else {
10648 if (!T->isElaboratedTypeSpecifier()) {
10649 // If we evaluated the type to a record type, suggest putting
10650 // a tag in front.
10651 if (const RecordType *RT = T->getAs<RecordType>()) {
10652 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010653
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010654 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010655
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010656 Diag(TypeRange.getBegin(),
10657 getLangOpts().CPlusPlus11 ?
10658 diag::warn_cxx98_compat_unelaborated_friend_type :
10659 diag::ext_unelaborated_friend_type)
10660 << (unsigned) RD->getTagKind()
10661 << T
10662 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10663 InsertionText);
10664 } else {
10665 Diag(FriendLoc,
10666 getLangOpts().CPlusPlus11 ?
10667 diag::warn_cxx98_compat_nonclass_type_friend :
10668 diag::ext_nonclass_type_friend)
10669 << T
10670 << TypeRange;
10671 }
10672 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010673 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010674 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010675 diag::warn_cxx98_compat_enum_friend :
10676 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010677 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010678 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010679 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010680
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010681 // C++11 [class.friend]p3:
10682 // A friend declaration that does not declare a function shall have one
10683 // of the following forms:
10684 // friend elaborated-type-specifier ;
10685 // friend simple-type-specifier ;
10686 // friend typename-specifier ;
10687 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10688 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10689 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010690
Douglas Gregor06245bf2010-04-07 17:57:12 +000010691 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010692 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010693 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010694 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010695}
10696
John McCall9a34edb2010-10-19 01:40:49 +000010697/// Handle a friend tag declaration where the scope specifier was
10698/// templated.
10699Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10700 unsigned TagSpec, SourceLocation TagLoc,
10701 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010702 IdentifierInfo *Name,
10703 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010704 AttributeList *Attr,
10705 MultiTemplateParamsArg TempParamLists) {
10706 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10707
10708 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010709 bool Invalid = false;
10710
10711 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010712 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010713 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010714 TempParamLists.size(),
10715 /*friend*/ true,
10716 isExplicitSpecialization,
10717 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010718 if (TemplateParams->size() > 0) {
10719 // This is a declaration of a class template.
10720 if (Invalid)
10721 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010722
Eric Christopher4110e132011-07-21 05:34:24 +000010723 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10724 SS, Name, NameLoc, Attr,
10725 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010726 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010727 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010728 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010729 } else {
10730 // The "template<>" header is extraneous.
10731 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10732 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10733 isExplicitSpecialization = true;
10734 }
10735 }
10736
10737 if (Invalid) return 0;
10738
John McCall9a34edb2010-10-19 01:40:49 +000010739 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010740 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010741 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010742 isAllExplicitSpecializations = false;
10743 break;
10744 }
10745 }
10746
10747 // FIXME: don't ignore attributes.
10748
10749 // If it's explicit specializations all the way down, just forget
10750 // about the template header and build an appropriate non-templated
10751 // friend. TODO: for source fidelity, remember the headers.
10752 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010753 if (SS.isEmpty()) {
10754 bool Owned = false;
10755 bool IsDependent = false;
10756 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10757 Attr, AS_public,
10758 /*ModulePrivateLoc=*/SourceLocation(),
10759 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010760 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010761 /*ScopedEnumUsesClassTag=*/false,
10762 /*UnderlyingType=*/TypeResult());
10763 }
10764
Douglas Gregor2494dd02011-03-01 01:34:45 +000010765 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010766 ElaboratedTypeKeyword Keyword
10767 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010768 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010769 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010770 if (T.isNull())
10771 return 0;
10772
10773 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10774 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010775 DependentNameTypeLoc TL =
10776 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010777 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010778 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010779 TL.setNameLoc(NameLoc);
10780 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010781 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010782 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010783 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010784 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010785 }
10786
10787 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010788 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010789 Friend->setAccess(AS_public);
10790 CurContext->addDecl(Friend);
10791 return Friend;
10792 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010793
10794 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10795
10796
John McCall9a34edb2010-10-19 01:40:49 +000010797
10798 // Handle the case of a templated-scope friend class. e.g.
10799 // template <class T> class A<T>::B;
10800 // FIXME: we don't support these right now.
10801 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10802 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10803 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000010804 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010805 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010806 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010807 TL.setNameLoc(NameLoc);
10808
10809 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010810 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010811 Friend->setAccess(AS_public);
10812 Friend->setUnsupportedFriend(true);
10813 CurContext->addDecl(Friend);
10814 return Friend;
10815}
10816
10817
John McCalldd4a3b02009-09-16 22:47:08 +000010818/// Handle a friend type declaration. This works in tandem with
10819/// ActOnTag.
10820///
10821/// Notes on friend class templates:
10822///
10823/// We generally treat friend class declarations as if they were
10824/// declaring a class. So, for example, the elaborated type specifier
10825/// in a friend declaration is required to obey the restrictions of a
10826/// class-head (i.e. no typedefs in the scope chain), template
10827/// parameters are required to match up with simple template-ids, &c.
10828/// However, unlike when declaring a template specialization, it's
10829/// okay to refer to a template specialization without an empty
10830/// template parameter declaration, e.g.
10831/// friend class A<T>::B<unsigned>;
10832/// We permit this as a special case; if there are any template
10833/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010834/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010835Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010836 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010837 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010838
10839 assert(DS.isFriendSpecified());
10840 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10841
John McCalldd4a3b02009-09-16 22:47:08 +000010842 // Try to convert the decl specifier to a type. This works for
10843 // friend templates because ActOnTag never produces a ClassTemplateDecl
10844 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010845 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010846 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10847 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010848 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010849 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010850
Douglas Gregor6ccab972010-12-16 01:14:37 +000010851 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10852 return 0;
10853
John McCalldd4a3b02009-09-16 22:47:08 +000010854 // This is definitely an error in C++98. It's probably meant to
10855 // be forbidden in C++0x, too, but the specification is just
10856 // poorly written.
10857 //
10858 // The problem is with declarations like the following:
10859 // template <T> friend A<T>::foo;
10860 // where deciding whether a class C is a friend or not now hinges
10861 // on whether there exists an instantiation of A that causes
10862 // 'foo' to equal C. There are restrictions on class-heads
10863 // (which we declare (by fiat) elaborated friend declarations to
10864 // be) that makes this tractable.
10865 //
10866 // FIXME: handle "template <> friend class A<T>;", which
10867 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010868 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010869 Diag(Loc, diag::err_tagless_friend_type_template)
10870 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010871 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010872 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010873
John McCall02cace72009-08-28 07:59:38 +000010874 // C++98 [class.friend]p1: A friend of a class is a function
10875 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010876 // This is fixed in DR77, which just barely didn't make the C++03
10877 // deadline. It's also a very silly restriction that seriously
10878 // affects inner classes and which nobody else seems to implement;
10879 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010880 //
10881 // But note that we could warn about it: it's always useless to
10882 // friend one of your own members (it's not, however, worthless to
10883 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010884
John McCalldd4a3b02009-09-16 22:47:08 +000010885 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010886 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010887 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010888 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010889 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010890 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010891 DS.getFriendSpecLoc());
10892 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010893 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010894
10895 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010896 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010897
John McCalldd4a3b02009-09-16 22:47:08 +000010898 D->setAccess(AS_public);
10899 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010900
John McCalld226f652010-08-21 09:40:31 +000010901 return D;
John McCall02cace72009-08-28 07:59:38 +000010902}
10903
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000010904NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10905 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010906 const DeclSpec &DS = D.getDeclSpec();
10907
10908 assert(DS.isFriendSpecified());
10909 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10910
10911 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010912 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010913
10914 // C++ [class.friend]p1
10915 // A friend of a class is a function or class....
10916 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010917 // It *doesn't* see through dependent types, which is correct
10918 // according to [temp.arg.type]p3:
10919 // If a declaration acquires a function type through a
10920 // type dependent on a template-parameter and this causes
10921 // a declaration that does not use the syntactic form of a
10922 // function declarator to have a function type, the program
10923 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010924 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010925 Diag(Loc, diag::err_unexpected_friend);
10926
10927 // It might be worthwhile to try to recover by creating an
10928 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010929 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010930 }
10931
10932 // C++ [namespace.memdef]p3
10933 // - If a friend declaration in a non-local class first declares a
10934 // class or function, the friend class or function is a member
10935 // of the innermost enclosing namespace.
10936 // - The name of the friend is not found by simple name lookup
10937 // until a matching declaration is provided in that namespace
10938 // scope (either before or after the class declaration granting
10939 // friendship).
10940 // - If a friend function is called, its name may be found by the
10941 // name lookup that considers functions from namespaces and
10942 // classes associated with the types of the function arguments.
10943 // - When looking for a prior declaration of a class or a function
10944 // declared as a friend, scopes outside the innermost enclosing
10945 // namespace scope are not considered.
10946
John McCall337ec3d2010-10-12 23:13:28 +000010947 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010948 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10949 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010950 assert(Name);
10951
Douglas Gregor6ccab972010-12-16 01:14:37 +000010952 // Check for unexpanded parameter packs.
10953 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10954 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10955 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10956 return 0;
10957
John McCall67d1a672009-08-06 02:15:43 +000010958 // The context we found the declaration in, or in which we should
10959 // create the declaration.
10960 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010961 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010962 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010963 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010964
John McCall337ec3d2010-10-12 23:13:28 +000010965 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010966
John McCall337ec3d2010-10-12 23:13:28 +000010967 // There are four cases here.
10968 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010969 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010970 // there as appropriate.
10971 // Recover from invalid scope qualifiers as if they just weren't there.
10972 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010973 // C++0x [namespace.memdef]p3:
10974 // If the name in a friend declaration is neither qualified nor
10975 // a template-id and the declaration is a function or an
10976 // elaborated-type-specifier, the lookup to determine whether
10977 // the entity has been previously declared shall not consider
10978 // any scopes outside the innermost enclosing namespace.
10979 // C++0x [class.friend]p11:
10980 // If a friend declaration appears in a local class and the name
10981 // specified is an unqualified name, a prior declaration is
10982 // looked up without considering scopes that are outside the
10983 // innermost enclosing non-class scope. For a friend function
10984 // declaration, if there is no prior declaration, the program is
10985 // ill-formed.
10986 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010987 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010988
John McCall29ae6e52010-10-13 05:45:15 +000010989 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010990 DC = CurContext;
10991 while (true) {
10992 // Skip class contexts. If someone can cite chapter and verse
10993 // for this behavior, that would be nice --- it's what GCC and
10994 // EDG do, and it seems like a reasonable intent, but the spec
10995 // really only says that checks for unqualified existing
10996 // declarations should stop at the nearest enclosing namespace,
10997 // not that they should only consider the nearest enclosing
10998 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010999 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000011000 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011001
John McCall68263142009-11-18 22:49:29 +000011002 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000011003
11004 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000011005 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000011006 break;
John McCall29ae6e52010-10-13 05:45:15 +000011007
John McCall8a407372010-10-14 22:22:28 +000011008 if (isTemplateId) {
11009 if (isa<TranslationUnitDecl>(DC)) break;
11010 } else {
11011 if (DC->isFileContext()) break;
11012 }
John McCall67d1a672009-08-06 02:15:43 +000011013 DC = DC->getParent();
11014 }
11015
John McCall380aaa42010-10-13 06:22:15 +000011016 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011017
Douglas Gregor883af832011-10-10 01:11:59 +000011018 // C++ [class.friend]p6:
11019 // A function can be defined in a friend declaration of a class if and
11020 // only if the class is a non-local class (9.8), the function name is
11021 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011022 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011023 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11024 }
11025
John McCall337ec3d2010-10-12 23:13:28 +000011026 // - There's a non-dependent scope specifier, in which case we
11027 // compute it and do a previous lookup there for a function
11028 // or function template.
11029 } else if (!SS.getScopeRep()->isDependent()) {
11030 DC = computeDeclContext(SS);
11031 if (!DC) return 0;
11032
11033 if (RequireCompleteDeclContext(SS, DC)) return 0;
11034
11035 LookupQualifiedName(Previous, DC);
11036
11037 // Ignore things found implicitly in the wrong scope.
11038 // TODO: better diagnostics for this case. Suggesting the right
11039 // qualified scope would be nice...
11040 LookupResult::Filter F = Previous.makeFilter();
11041 while (F.hasNext()) {
11042 NamedDecl *D = F.next();
11043 if (!DC->InEnclosingNamespaceSetOf(
11044 D->getDeclContext()->getRedeclContext()))
11045 F.erase();
11046 }
11047 F.done();
11048
11049 if (Previous.empty()) {
11050 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011051 Diag(Loc, diag::err_qualified_friend_not_found)
11052 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011053 return 0;
11054 }
11055
11056 // C++ [class.friend]p1: A friend of a class is a function or
11057 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011058 if (DC->Equals(CurContext))
11059 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011060 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011061 diag::warn_cxx98_compat_friend_is_member :
11062 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011063
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011064 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011065 // C++ [class.friend]p6:
11066 // A function can be defined in a friend declaration of a class if and
11067 // only if the class is a non-local class (9.8), the function name is
11068 // unqualified, and the function has namespace scope.
11069 SemaDiagnosticBuilder DB
11070 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11071
11072 DB << SS.getScopeRep();
11073 if (DC->isFileContext())
11074 DB << FixItHint::CreateRemoval(SS.getRange());
11075 SS.clear();
11076 }
John McCall337ec3d2010-10-12 23:13:28 +000011077
11078 // - There's a scope specifier that does not match any template
11079 // parameter lists, in which case we use some arbitrary context,
11080 // create a method or method template, and wait for instantiation.
11081 // - There's a scope specifier that does match some template
11082 // parameter lists, which we don't handle right now.
11083 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011084 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011085 // C++ [class.friend]p6:
11086 // A function can be defined in a friend declaration of a class if and
11087 // only if the class is a non-local class (9.8), the function name is
11088 // unqualified, and the function has namespace scope.
11089 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11090 << SS.getScopeRep();
11091 }
11092
John McCall337ec3d2010-10-12 23:13:28 +000011093 DC = CurContext;
11094 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011095 }
Douglas Gregor883af832011-10-10 01:11:59 +000011096
John McCall29ae6e52010-10-13 05:45:15 +000011097 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011098 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011099 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11100 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11101 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011102 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011103 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11104 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011105 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011106 }
John McCall67d1a672009-08-06 02:15:43 +000011107 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011108
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011109 // FIXME: This is an egregious hack to cope with cases where the scope stack
11110 // does not contain the declaration context, i.e., in an out-of-line
11111 // definition of a class.
11112 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11113 if (!DCScope) {
11114 FakeDCScope.setEntity(DC);
11115 DCScope = &FakeDCScope;
11116 }
11117
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011118 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011119 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011120 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011121 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011122
Douglas Gregor182ddf02009-09-28 00:08:27 +000011123 assert(ND->getDeclContext() == DC);
11124 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011125
John McCallab88d972009-08-31 22:39:49 +000011126 // Add the function declaration to the appropriate lookup tables,
11127 // adjusting the redeclarations list as necessary. We don't
11128 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011129 //
John McCallab88d972009-08-31 22:39:49 +000011130 // Also update the scope-based lookup if the target context's
11131 // lookup context is in lexical scope.
11132 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011133 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011134 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011135 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011136 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011137 }
John McCall02cace72009-08-28 07:59:38 +000011138
11139 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011140 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011141 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011142 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011143 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011144
John McCall1f2e1a92012-08-10 03:15:35 +000011145 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011146 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011147 } else {
11148 if (DC->isRecord()) CheckFriendAccess(ND);
11149
John McCall6102ca12010-10-16 06:59:13 +000011150 FunctionDecl *FD;
11151 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11152 FD = FTD->getTemplatedDecl();
11153 else
11154 FD = cast<FunctionDecl>(ND);
11155
11156 // Mark templated-scope function declarations as unsupported.
11157 if (FD->getNumTemplateParameterLists())
11158 FrD->setUnsupportedFriend(true);
11159 }
John McCall337ec3d2010-10-12 23:13:28 +000011160
John McCalld226f652010-08-21 09:40:31 +000011161 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011162}
11163
John McCalld226f652010-08-21 09:40:31 +000011164void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11165 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011166
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011167 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011168 if (!Fn) {
11169 Diag(DelLoc, diag::err_deleted_non_function);
11170 return;
11171 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011172
Douglas Gregoref96ee02012-01-14 16:38:05 +000011173 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011174 // Don't consider the implicit declaration we generate for explicit
11175 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011176 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11177 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011178 Diag(DelLoc, diag::err_deleted_decl_not_first);
11179 Diag(Prev->getLocation(), diag::note_previous_declaration);
11180 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011181 // If the declaration wasn't the first, we delete the function anyway for
11182 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011183 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011184 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011185
11186 if (Fn->isDeleted())
11187 return;
11188
11189 // See if we're deleting a function which is already known to override a
11190 // non-deleted virtual function.
11191 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11192 bool IssuedDiagnostic = false;
11193 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11194 E = MD->end_overridden_methods();
11195 I != E; ++I) {
11196 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11197 if (!IssuedDiagnostic) {
11198 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11199 IssuedDiagnostic = true;
11200 }
11201 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11202 }
11203 }
11204 }
11205
Sean Hunt10620eb2011-05-06 20:44:56 +000011206 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011207}
Sebastian Redl13e88542009-04-27 21:33:24 +000011208
Sean Hunte4246a62011-05-12 06:15:49 +000011209void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011210 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011211
11212 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011213 if (MD->getParent()->isDependentType()) {
11214 MD->setDefaulted();
11215 MD->setExplicitlyDefaulted();
11216 return;
11217 }
11218
Sean Hunte4246a62011-05-12 06:15:49 +000011219 CXXSpecialMember Member = getSpecialMember(MD);
11220 if (Member == CXXInvalid) {
11221 Diag(DefaultLoc, diag::err_default_special_members);
11222 return;
11223 }
11224
11225 MD->setDefaulted();
11226 MD->setExplicitlyDefaulted();
11227
Sean Huntcd10dec2011-05-23 23:14:04 +000011228 // If this definition appears within the record, do the checking when
11229 // the record is complete.
11230 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011231 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011232 // Find the uninstantiated declaration that actually had the '= default'
11233 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011234 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011235
Richard Smith12fef492013-03-27 00:22:47 +000011236 // If the method was defaulted on its first declaration, we will have
11237 // already performed the checking in CheckCompletedCXXClass. Such a
11238 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011239 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011240 return;
11241
Richard Smithb9d0b762012-07-27 04:22:15 +000011242 CheckExplicitlyDefaultedSpecialMember(MD);
11243
Richard Smith1d28caf2012-12-11 01:14:52 +000011244 // The exception specification is needed because we are defining the
11245 // function.
11246 ResolveExceptionSpec(DefaultLoc,
11247 MD->getType()->castAs<FunctionProtoType>());
11248
Sean Hunte4246a62011-05-12 06:15:49 +000011249 switch (Member) {
11250 case CXXDefaultConstructor: {
11251 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011252 if (!CD->isInvalidDecl())
11253 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11254 break;
11255 }
11256
11257 case CXXCopyConstructor: {
11258 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011259 if (!CD->isInvalidDecl())
11260 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011261 break;
11262 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011263
Sean Hunt2b188082011-05-14 05:23:28 +000011264 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011265 if (!MD->isInvalidDecl())
11266 DefineImplicitCopyAssignment(DefaultLoc, MD);
11267 break;
11268 }
11269
Sean Huntcb45a0f2011-05-12 22:46:25 +000011270 case CXXDestructor: {
11271 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011272 if (!DD->isInvalidDecl())
11273 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011274 break;
11275 }
11276
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011277 case CXXMoveConstructor: {
11278 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011279 if (!CD->isInvalidDecl())
11280 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011281 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011282 }
Sean Hunt82713172011-05-25 23:16:36 +000011283
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011284 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011285 if (!MD->isInvalidDecl())
11286 DefineImplicitMoveAssignment(DefaultLoc, MD);
11287 break;
11288 }
11289
11290 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011291 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011292 }
11293 } else {
11294 Diag(DefaultLoc, diag::err_default_special_members);
11295 }
11296}
11297
Sebastian Redl13e88542009-04-27 21:33:24 +000011298static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011299 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011300 Stmt *SubStmt = *CI;
11301 if (!SubStmt)
11302 continue;
11303 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011304 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011305 diag::err_return_in_constructor_handler);
11306 if (!isa<Expr>(SubStmt))
11307 SearchForReturnInStmt(Self, SubStmt);
11308 }
11309}
11310
11311void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11312 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11313 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11314 SearchForReturnInStmt(*this, Handler);
11315 }
11316}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011317
David Blaikie299adab2013-01-18 23:03:15 +000011318bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011319 const CXXMethodDecl *Old) {
11320 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11321 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11322
11323 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11324
11325 // If the calling conventions match, everything is fine
11326 if (NewCC == OldCC)
11327 return false;
11328
11329 // If either of the calling conventions are set to "default", we need to pick
11330 // something more sensible based on the target. This supports code where the
11331 // one method explicitly sets thiscall, and another has no explicit calling
11332 // convention.
11333 CallingConv Default =
11334 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11335 if (NewCC == CC_Default)
11336 NewCC = Default;
11337 if (OldCC == CC_Default)
11338 OldCC = Default;
11339
11340 // If the calling conventions still don't match, then report the error
11341 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011342 Diag(New->getLocation(),
11343 diag::err_conflicting_overriding_cc_attributes)
11344 << New->getDeclName() << New->getType() << Old->getType();
11345 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11346 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011347 }
11348
11349 return false;
11350}
11351
Mike Stump1eb44332009-09-09 15:08:12 +000011352bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011353 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011354 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11355 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011356
Chandler Carruth73857792010-02-15 11:53:20 +000011357 if (Context.hasSameType(NewTy, OldTy) ||
11358 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011359 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011360
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011361 // Check if the return types are covariant
11362 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011363
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011364 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011365 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11366 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011367 NewClassTy = NewPT->getPointeeType();
11368 OldClassTy = OldPT->getPointeeType();
11369 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011370 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11371 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11372 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11373 NewClassTy = NewRT->getPointeeType();
11374 OldClassTy = OldRT->getPointeeType();
11375 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011376 }
11377 }
Mike Stump1eb44332009-09-09 15:08:12 +000011378
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011379 // The return types aren't either both pointers or references to a class type.
11380 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011381 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011382 diag::err_different_return_type_for_overriding_virtual_function)
11383 << New->getDeclName() << NewTy << OldTy;
11384 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011385
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011386 return true;
11387 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011388
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011389 // C++ [class.virtual]p6:
11390 // If the return type of D::f differs from the return type of B::f, the
11391 // class type in the return type of D::f shall be complete at the point of
11392 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011393 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11394 if (!RT->isBeingDefined() &&
11395 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011396 diag::err_covariant_return_incomplete,
11397 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011398 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011399 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011400
Douglas Gregora4923eb2009-11-16 21:35:15 +000011401 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011402 // Check if the new class derives from the old class.
11403 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11404 Diag(New->getLocation(),
11405 diag::err_covariant_return_not_derived)
11406 << New->getDeclName() << NewTy << OldTy;
11407 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11408 return true;
11409 }
Mike Stump1eb44332009-09-09 15:08:12 +000011410
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011411 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011412 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011413 diag::err_covariant_return_inaccessible_base,
11414 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11415 // FIXME: Should this point to the return type?
11416 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011417 // FIXME: this note won't trigger for delayed access control
11418 // diagnostics, and it's impossible to get an undelayed error
11419 // here from access control during the original parse because
11420 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011421 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11422 return true;
11423 }
11424 }
Mike Stump1eb44332009-09-09 15:08:12 +000011425
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011426 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011427 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011428 Diag(New->getLocation(),
11429 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011430 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011431 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11432 return true;
11433 };
Mike Stump1eb44332009-09-09 15:08:12 +000011434
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011435
11436 // The new class type must have the same or less qualifiers as the old type.
11437 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11438 Diag(New->getLocation(),
11439 diag::err_covariant_return_type_class_type_more_qualified)
11440 << New->getDeclName() << NewTy << OldTy;
11441 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11442 return true;
11443 };
Mike Stump1eb44332009-09-09 15:08:12 +000011444
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011445 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011446}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011447
Douglas Gregor4ba31362009-12-01 17:24:26 +000011448/// \brief Mark the given method pure.
11449///
11450/// \param Method the method to be marked pure.
11451///
11452/// \param InitRange the source range that covers the "0" initializer.
11453bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011454 SourceLocation EndLoc = InitRange.getEnd();
11455 if (EndLoc.isValid())
11456 Method->setRangeEnd(EndLoc);
11457
Douglas Gregor4ba31362009-12-01 17:24:26 +000011458 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11459 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011460 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011461 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011462
11463 if (!Method->isInvalidDecl())
11464 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11465 << Method->getDeclName() << InitRange;
11466 return true;
11467}
11468
Douglas Gregor552e2992012-02-21 02:22:07 +000011469/// \brief Determine whether the given declaration is a static data member.
11470static bool isStaticDataMember(Decl *D) {
11471 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11472 if (!Var)
11473 return false;
11474
11475 return Var->isStaticDataMember();
11476}
John McCall731ad842009-12-19 09:28:58 +000011477/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11478/// an initializer for the out-of-line declaration 'Dcl'. The scope
11479/// is a fresh scope pushed for just this purpose.
11480///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011481/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11482/// static data member of class X, names should be looked up in the scope of
11483/// class X.
John McCalld226f652010-08-21 09:40:31 +000011484void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011485 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011486 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011487
John McCall731ad842009-12-19 09:28:58 +000011488 // We should only get called for declarations with scope specifiers, like:
11489 // int foo::bar;
11490 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011491 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011492
11493 // If we are parsing the initializer for a static data member, push a
11494 // new expression evaluation context that is associated with this static
11495 // data member.
11496 if (isStaticDataMember(D))
11497 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011498}
11499
11500/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011501/// initializer for the out-of-line declaration 'D'.
11502void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011503 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011504 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011505
Douglas Gregor552e2992012-02-21 02:22:07 +000011506 if (isStaticDataMember(D))
11507 PopExpressionEvaluationContext();
11508
John McCall731ad842009-12-19 09:28:58 +000011509 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011510 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011511}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011512
11513/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11514/// C++ if/switch/while/for statement.
11515/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011516DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011517 // C++ 6.4p2:
11518 // The declarator shall not specify a function or an array.
11519 // The type-specifier-seq shall not contain typedef and shall not declare a
11520 // new class or enumeration.
11521 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11522 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011523
11524 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011525 if (!Dcl)
11526 return true;
11527
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011528 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11529 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011530 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011531 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011532 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011533
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011534 return Dcl;
11535}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011536
Douglas Gregordfe65432011-07-28 19:11:31 +000011537void Sema::LoadExternalVTableUses() {
11538 if (!ExternalSource)
11539 return;
11540
11541 SmallVector<ExternalVTableUse, 4> VTables;
11542 ExternalSource->ReadUsedVTables(VTables);
11543 SmallVector<VTableUse, 4> NewUses;
11544 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11545 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11546 = VTablesUsed.find(VTables[I].Record);
11547 // Even if a definition wasn't required before, it may be required now.
11548 if (Pos != VTablesUsed.end()) {
11549 if (!Pos->second && VTables[I].DefinitionRequired)
11550 Pos->second = true;
11551 continue;
11552 }
11553
11554 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11555 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11556 }
11557
11558 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11559}
11560
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011561void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11562 bool DefinitionRequired) {
11563 // Ignore any vtable uses in unevaluated operands or for classes that do
11564 // not have a vtable.
11565 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11566 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011567 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011568 return;
11569
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011570 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011571 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011572 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11573 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11574 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11575 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011576 // If we already had an entry, check to see if we are promoting this vtable
11577 // to required a definition. If so, we need to reappend to the VTableUses
11578 // list, since we may have already processed the first entry.
11579 if (DefinitionRequired && !Pos.first->second) {
11580 Pos.first->second = true;
11581 } else {
11582 // Otherwise, we can early exit.
11583 return;
11584 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011585 }
11586
11587 // Local classes need to have their virtual members marked
11588 // immediately. For all other classes, we mark their virtual members
11589 // at the end of the translation unit.
11590 if (Class->isLocalClass())
11591 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011592 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011593 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011594}
11595
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011596bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011597 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011598 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011599 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011600
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011601 // Note: The VTableUses vector could grow as a result of marking
11602 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011603 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011604 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011605 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011606 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011607 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011608 if (!Class)
11609 continue;
11610
11611 SourceLocation Loc = VTableUses[I].second;
11612
Richard Smithb9d0b762012-07-27 04:22:15 +000011613 bool DefineVTable = true;
11614
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011615 // If this class has a key function, but that key function is
11616 // defined in another translation unit, we don't need to emit the
11617 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011618 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011619 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011620 switch (KeyFunction->getTemplateSpecializationKind()) {
11621 case TSK_Undeclared:
11622 case TSK_ExplicitSpecialization:
11623 case TSK_ExplicitInstantiationDeclaration:
11624 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011625 DefineVTable = false;
11626 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011627
11628 case TSK_ExplicitInstantiationDefinition:
11629 case TSK_ImplicitInstantiation:
11630 // We will be instantiating the key function.
11631 break;
11632 }
11633 } else if (!KeyFunction) {
11634 // If we have a class with no key function that is the subject
11635 // of an explicit instantiation declaration, suppress the
11636 // vtable; it will live with the explicit instantiation
11637 // definition.
11638 bool IsExplicitInstantiationDeclaration
11639 = Class->getTemplateSpecializationKind()
11640 == TSK_ExplicitInstantiationDeclaration;
11641 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11642 REnd = Class->redecls_end();
11643 R != REnd; ++R) {
11644 TemplateSpecializationKind TSK
11645 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11646 if (TSK == TSK_ExplicitInstantiationDeclaration)
11647 IsExplicitInstantiationDeclaration = true;
11648 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11649 IsExplicitInstantiationDeclaration = false;
11650 break;
11651 }
11652 }
11653
11654 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011655 DefineVTable = false;
11656 }
11657
11658 // The exception specifications for all virtual members may be needed even
11659 // if we are not providing an authoritative form of the vtable in this TU.
11660 // We may choose to emit it available_externally anyway.
11661 if (!DefineVTable) {
11662 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11663 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011664 }
11665
11666 // Mark all of the virtual members of this class as referenced, so
11667 // that we can build a vtable. Then, tell the AST consumer that a
11668 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011669 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011670 MarkVirtualMembersReferenced(Loc, Class);
11671 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11672 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11673
11674 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola531db822013-03-07 02:00:27 +000011675 if (Class->hasExternalLinkage() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011676 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011677 const FunctionDecl *KeyFunctionDef = 0;
11678 if (!KeyFunction ||
11679 (KeyFunction->hasBody(KeyFunctionDef) &&
11680 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011681 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11682 TSK_ExplicitInstantiationDefinition
11683 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11684 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011685 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011686 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011687 VTableUses.clear();
11688
Douglas Gregor78844032011-04-22 22:25:37 +000011689 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011690}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011691
Richard Smithb9d0b762012-07-27 04:22:15 +000011692void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11693 const CXXRecordDecl *RD) {
11694 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11695 E = RD->method_end(); I != E; ++I)
11696 if ((*I)->isVirtual() && !(*I)->isPure())
11697 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11698}
11699
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011700void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11701 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011702 // Mark all functions which will appear in RD's vtable as used.
11703 CXXFinalOverriderMap FinalOverriders;
11704 RD->getFinalOverriders(FinalOverriders);
11705 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11706 E = FinalOverriders.end();
11707 I != E; ++I) {
11708 for (OverridingMethods::const_iterator OI = I->second.begin(),
11709 OE = I->second.end();
11710 OI != OE; ++OI) {
11711 assert(OI->second.size() > 0 && "no final overrider");
11712 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011713
Richard Smithff817f72012-07-07 06:59:51 +000011714 // C++ [basic.def.odr]p2:
11715 // [...] A virtual member function is used if it is not pure. [...]
11716 if (!Overrider->isPure())
11717 MarkFunctionReferenced(Loc, Overrider);
11718 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011719 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011720
11721 // Only classes that have virtual bases need a VTT.
11722 if (RD->getNumVBases() == 0)
11723 return;
11724
11725 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11726 e = RD->bases_end(); i != e; ++i) {
11727 const CXXRecordDecl *Base =
11728 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011729 if (Base->getNumVBases() == 0)
11730 continue;
11731 MarkVirtualMembersReferenced(Loc, Base);
11732 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011733}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011734
11735/// SetIvarInitializers - This routine builds initialization ASTs for the
11736/// Objective-C implementation whose ivars need be initialized.
11737void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011738 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011739 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011740 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011741 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011742 CollectIvarsToConstructOrDestruct(OID, ivars);
11743 if (ivars.empty())
11744 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011745 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011746 for (unsigned i = 0; i < ivars.size(); i++) {
11747 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011748 if (Field->isInvalidDecl())
11749 continue;
11750
Sean Huntcbb67482011-01-08 20:30:50 +000011751 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011752 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11753 InitializationKind InitKind =
11754 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11755
11756 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011757 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011758 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011759 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011760 // Note, MemberInit could actually come back empty if no initialization
11761 // is required (e.g., because it would call a trivial default constructor)
11762 if (!MemberInit.get() || MemberInit.isInvalid())
11763 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011764
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011765 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011766 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11767 SourceLocation(),
11768 MemberInit.takeAs<Expr>(),
11769 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011770 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011771
11772 // Be sure that the destructor is accessible and is marked as referenced.
11773 if (const RecordType *RecordTy
11774 = Context.getBaseElementType(Field->getType())
11775 ->getAs<RecordType>()) {
11776 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011777 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011778 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011779 CheckDestructorAccess(Field->getLocation(), Destructor,
11780 PDiag(diag::err_access_dtor_ivar)
11781 << Context.getBaseElementType(Field->getType()));
11782 }
11783 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011784 }
11785 ObjCImplementation->setIvarInitializers(Context,
11786 AllToInit.data(), AllToInit.size());
11787 }
11788}
Sean Huntfe57eef2011-05-04 05:57:24 +000011789
Sean Huntebcbe1d2011-05-04 23:29:54 +000011790static
11791void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11792 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11793 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11794 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11795 Sema &S) {
11796 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11797 CE = Current.end();
11798 if (Ctor->isInvalidDecl())
11799 return;
11800
Richard Smitha8eaf002012-08-23 06:16:52 +000011801 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11802
11803 // Target may not be determinable yet, for instance if this is a dependent
11804 // call in an uninstantiated template.
11805 if (Target) {
11806 const FunctionDecl *FNTarget = 0;
11807 (void)Target->hasBody(FNTarget);
11808 Target = const_cast<CXXConstructorDecl*>(
11809 cast_or_null<CXXConstructorDecl>(FNTarget));
11810 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011811
11812 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11813 // Avoid dereferencing a null pointer here.
11814 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11815
11816 if (!Current.insert(Canonical))
11817 return;
11818
11819 // We know that beyond here, we aren't chaining into a cycle.
11820 if (!Target || !Target->isDelegatingConstructor() ||
11821 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11822 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11823 Valid.insert(*CI);
11824 Current.clear();
11825 // We've hit a cycle.
11826 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11827 Current.count(TCanonical)) {
11828 // If we haven't diagnosed this cycle yet, do so now.
11829 if (!Invalid.count(TCanonical)) {
11830 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011831 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011832 << Ctor;
11833
Richard Smitha8eaf002012-08-23 06:16:52 +000011834 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011835 if (TCanonical != Canonical)
11836 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11837
11838 CXXConstructorDecl *C = Target;
11839 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011840 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011841 (void)C->getTargetConstructor()->hasBody(FNTarget);
11842 assert(FNTarget && "Ctor cycle through bodiless function");
11843
Richard Smitha8eaf002012-08-23 06:16:52 +000011844 C = const_cast<CXXConstructorDecl*>(
11845 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011846 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11847 }
11848 }
11849
11850 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11851 Invalid.insert(*CI);
11852 Current.clear();
11853 } else {
11854 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11855 }
11856}
11857
11858
Sean Huntfe57eef2011-05-04 05:57:24 +000011859void Sema::CheckDelegatingCtorCycles() {
11860 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11861
Sean Huntebcbe1d2011-05-04 23:29:54 +000011862 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11863 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011864
Douglas Gregor0129b562011-07-27 21:57:17 +000011865 for (DelegatingCtorDeclsType::iterator
11866 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011867 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011868 I != E; ++I)
11869 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011870
11871 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11872 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011873}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011874
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011875namespace {
11876 /// \brief AST visitor that finds references to the 'this' expression.
11877 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11878 Sema &S;
11879
11880 public:
11881 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11882
11883 bool VisitCXXThisExpr(CXXThisExpr *E) {
11884 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11885 << E->isImplicit();
11886 return false;
11887 }
11888 };
11889}
11890
11891bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11892 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11893 if (!TSInfo)
11894 return false;
11895
11896 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011897 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011898 if (!ProtoTL)
11899 return false;
11900
11901 // C++11 [expr.prim.general]p3:
11902 // [The expression this] shall not appear before the optional
11903 // cv-qualifier-seq and it shall not appear within the declaration of a
11904 // static member function (although its type and value category are defined
11905 // within a static member function as they are within a non-static member
11906 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011907 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000011908 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011909 FindCXXThisExpr Finder(*this);
11910
11911 // If the return type came after the cv-qualifier-seq, check it now.
11912 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000011913 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011914 return true;
11915
11916 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011917 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11918 return true;
11919
11920 return checkThisInStaticMemberFunctionAttributes(Method);
11921}
11922
11923bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11924 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11925 if (!TSInfo)
11926 return false;
11927
11928 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011929 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011930 if (!ProtoTL)
11931 return false;
11932
David Blaikie39e6ab42013-02-18 22:06:02 +000011933 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011934 FindCXXThisExpr Finder(*this);
11935
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011936 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011937 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011938 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011939 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011940 case EST_DynamicNone:
11941 case EST_MSAny:
11942 case EST_None:
11943 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011944
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011945 case EST_ComputedNoexcept:
11946 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11947 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011948
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011949 case EST_Dynamic:
11950 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011951 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011952 E != EEnd; ++E) {
11953 if (!Finder.TraverseType(*E))
11954 return true;
11955 }
11956 break;
11957 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011958
11959 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011960}
11961
11962bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11963 FindCXXThisExpr Finder(*this);
11964
11965 // Check attributes.
11966 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11967 A != AEnd; ++A) {
11968 // FIXME: This should be emitted by tblgen.
11969 Expr *Arg = 0;
11970 ArrayRef<Expr *> Args;
11971 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11972 Arg = G->getArg();
11973 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11974 Arg = G->getArg();
11975 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11976 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11977 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11978 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11979 else if (ExclusiveLockFunctionAttr *ELF
11980 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11981 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11982 else if (SharedLockFunctionAttr *SLF
11983 = dyn_cast<SharedLockFunctionAttr>(*A))
11984 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11985 else if (ExclusiveTrylockFunctionAttr *ETLF
11986 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11987 Arg = ETLF->getSuccessValue();
11988 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11989 } else if (SharedTrylockFunctionAttr *STLF
11990 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11991 Arg = STLF->getSuccessValue();
11992 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11993 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11994 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11995 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11996 Arg = LR->getArg();
11997 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11998 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11999 else if (ExclusiveLocksRequiredAttr *ELR
12000 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12001 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12002 else if (SharedLocksRequiredAttr *SLR
12003 = dyn_cast<SharedLocksRequiredAttr>(*A))
12004 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12005
12006 if (Arg && !Finder.TraverseStmt(Arg))
12007 return true;
12008
12009 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12010 if (!Finder.TraverseStmt(Args[I]))
12011 return true;
12012 }
12013 }
12014
12015 return false;
12016}
12017
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012018void
12019Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12020 ArrayRef<ParsedType> DynamicExceptions,
12021 ArrayRef<SourceRange> DynamicExceptionRanges,
12022 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012023 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012024 FunctionProtoType::ExtProtoInfo &EPI) {
12025 Exceptions.clear();
12026 EPI.ExceptionSpecType = EST;
12027 if (EST == EST_Dynamic) {
12028 Exceptions.reserve(DynamicExceptions.size());
12029 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12030 // FIXME: Preserve type source info.
12031 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12032
12033 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12034 collectUnexpandedParameterPacks(ET, Unexpanded);
12035 if (!Unexpanded.empty()) {
12036 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12037 UPPC_ExceptionType,
12038 Unexpanded);
12039 continue;
12040 }
12041
12042 // Check that the type is valid for an exception spec, and
12043 // drop it if not.
12044 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12045 Exceptions.push_back(ET);
12046 }
12047 EPI.NumExceptions = Exceptions.size();
12048 EPI.Exceptions = Exceptions.data();
12049 return;
12050 }
12051
12052 if (EST == EST_ComputedNoexcept) {
12053 // If an error occurred, there's no expression here.
12054 if (NoexceptExpr) {
12055 assert((NoexceptExpr->isTypeDependent() ||
12056 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12057 Context.BoolTy) &&
12058 "Parser should have made sure that the expression is boolean");
12059 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12060 EPI.ExceptionSpecType = EST_BasicNoexcept;
12061 return;
12062 }
12063
12064 if (!NoexceptExpr->isValueDependent())
12065 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012066 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012067 /*AllowFold*/ false).take();
12068 EPI.NoexceptExpr = NoexceptExpr;
12069 }
12070 return;
12071 }
12072}
12073
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012074/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12075Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12076 // Implicitly declared functions (e.g. copy constructors) are
12077 // __host__ __device__
12078 if (D->isImplicit())
12079 return CFT_HostDevice;
12080
12081 if (D->hasAttr<CUDAGlobalAttr>())
12082 return CFT_Global;
12083
12084 if (D->hasAttr<CUDADeviceAttr>()) {
12085 if (D->hasAttr<CUDAHostAttr>())
12086 return CFT_HostDevice;
12087 else
12088 return CFT_Device;
12089 }
12090
12091 return CFT_Host;
12092}
12093
12094bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12095 CUDAFunctionTarget CalleeTarget) {
12096 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12097 // Callable from the device only."
12098 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12099 return true;
12100
12101 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12102 // Callable from the host only."
12103 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12104 // Callable from the host only."
12105 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12106 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12107 return true;
12108
12109 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12110 return true;
12111
12112 return false;
12113}
John McCall76da55d2013-04-16 07:28:30 +000012114
12115/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12116///
12117MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12118 SourceLocation DeclStart,
12119 Declarator &D, Expr *BitWidth,
12120 InClassInitStyle InitStyle,
12121 AccessSpecifier AS,
12122 AttributeList *MSPropertyAttr) {
12123 IdentifierInfo *II = D.getIdentifier();
12124 if (!II) {
12125 Diag(DeclStart, diag::err_anonymous_property);
12126 return NULL;
12127 }
12128 SourceLocation Loc = D.getIdentifierLoc();
12129
12130 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12131 QualType T = TInfo->getType();
12132 if (getLangOpts().CPlusPlus) {
12133 CheckExtraCXXDefaultArguments(D);
12134
12135 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12136 UPPC_DataMemberType)) {
12137 D.setInvalidType();
12138 T = Context.IntTy;
12139 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12140 }
12141 }
12142
12143 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12144
12145 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12146 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12147 diag::err_invalid_thread)
12148 << DeclSpec::getSpecifierName(TSCS);
12149
12150 // Check to see if this name was declared as a member previously
12151 NamedDecl *PrevDecl = 0;
12152 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12153 LookupName(Previous, S);
12154 switch (Previous.getResultKind()) {
12155 case LookupResult::Found:
12156 case LookupResult::FoundUnresolvedValue:
12157 PrevDecl = Previous.getAsSingle<NamedDecl>();
12158 break;
12159
12160 case LookupResult::FoundOverloaded:
12161 PrevDecl = Previous.getRepresentativeDecl();
12162 break;
12163
12164 case LookupResult::NotFound:
12165 case LookupResult::NotFoundInCurrentInstantiation:
12166 case LookupResult::Ambiguous:
12167 break;
12168 }
12169
12170 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12171 // Maybe we will complain about the shadowed template parameter.
12172 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12173 // Just pretend that we didn't see the previous declaration.
12174 PrevDecl = 0;
12175 }
12176
12177 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12178 PrevDecl = 0;
12179
12180 SourceLocation TSSL = D.getLocStart();
12181 MSPropertyDecl *NewPD;
12182 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12183 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12184 II, T, TInfo, TSSL,
12185 Data.GetterId, Data.SetterId);
12186 ProcessDeclAttributes(TUScope, NewPD, D);
12187 NewPD->setAccess(AS);
12188
12189 if (NewPD->isInvalidDecl())
12190 Record->setInvalidDecl();
12191
12192 if (D.getDeclSpec().isModulePrivateSpecified())
12193 NewPD->setModulePrivate();
12194
12195 if (NewPD->isInvalidDecl() && PrevDecl) {
12196 // Don't introduce NewFD into scope; there's already something
12197 // with the same name in the same scope.
12198 } else if (II) {
12199 PushOnScopeChains(NewPD, S);
12200 } else
12201 Record->addDecl(NewPD);
12202
12203 return NewPD;
12204}