blob: 8e8ea013958d7e926443fd1506688704011c95cf [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
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001606/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1607/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001608/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001609/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1610/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001611NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001612Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001613 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001614 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001615 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001616 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001617 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1618 DeclarationName Name = NameInfo.getName();
1619 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001620
1621 // For anonymous bitfields, the location should point to the type.
1622 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001623 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001624
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001625 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001626
John McCall4bde1e12010-06-04 08:34:12 +00001627 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001628 assert(!DS.isFriendSpecified());
1629
Richard Smith1ab0d902011-06-25 02:28:38 +00001630 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001631
John McCalle402e722012-09-25 07:32:39 +00001632 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1633 // The Microsoft extension __interface only permits public member functions
1634 // and prohibits constructors, destructors, operators, non-public member
1635 // functions, static methods and data members.
1636 unsigned InvalidDecl;
1637 bool ShowDeclName = true;
1638 if (!isFunc)
1639 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1640 else if (AS != AS_public)
1641 InvalidDecl = 2;
1642 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1643 InvalidDecl = 3;
1644 else switch (Name.getNameKind()) {
1645 case DeclarationName::CXXConstructorName:
1646 InvalidDecl = 4;
1647 ShowDeclName = false;
1648 break;
1649
1650 case DeclarationName::CXXDestructorName:
1651 InvalidDecl = 5;
1652 ShowDeclName = false;
1653 break;
1654
1655 case DeclarationName::CXXOperatorName:
1656 case DeclarationName::CXXConversionFunctionName:
1657 InvalidDecl = 6;
1658 break;
1659
1660 default:
1661 InvalidDecl = 0;
1662 break;
1663 }
1664
1665 if (InvalidDecl) {
1666 if (ShowDeclName)
1667 Diag(Loc, diag::err_invalid_member_in_interface)
1668 << (InvalidDecl-1) << Name;
1669 else
1670 Diag(Loc, diag::err_invalid_member_in_interface)
1671 << (InvalidDecl-1) << "";
1672 return 0;
1673 }
1674 }
1675
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001676 // C++ 9.2p6: A member shall not be declared to have automatic storage
1677 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001678 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1679 // data members and cannot be applied to names declared const or static,
1680 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001681 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001682 case DeclSpec::SCS_unspecified:
1683 case DeclSpec::SCS_typedef:
1684 case DeclSpec::SCS_static:
1685 break;
1686 case DeclSpec::SCS_mutable:
1687 if (isFunc) {
1688 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001689
Richard Smithec642442013-04-12 22:46:28 +00001690 // FIXME: It would be nicer if the keyword was ignored only for this
1691 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001692 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001693 }
1694 break;
1695 default:
1696 Diag(DS.getStorageClassSpecLoc(),
1697 diag::err_storageclass_invalid_for_member);
1698 D.getMutableDeclSpec().ClearStorageClassSpecs();
1699 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001700 }
1701
Sebastian Redl669d5d72008-11-14 23:42:31 +00001702 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1703 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001704 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001705
David Blaikie1d87fba2013-01-30 01:22:18 +00001706 if (DS.isConstexprSpecified() && isInstField) {
1707 SemaDiagnosticBuilder B =
1708 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1709 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1710 if (InitStyle == ICIS_NoInit) {
1711 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1712 D.getMutableDeclSpec().ClearConstexprSpec();
1713 const char *PrevSpec;
1714 unsigned DiagID;
1715 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1716 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001717 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001718 assert(!Failed && "Making a constexpr member const shouldn't fail");
1719 } else {
1720 B << 1;
1721 const char *PrevSpec;
1722 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001723 if (D.getMutableDeclSpec().SetStorageClassSpec(
1724 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001725 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001726 "This is the only DeclSpec that should fail to be applied");
1727 B << 1;
1728 } else {
1729 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1730 isInstField = false;
1731 }
1732 }
1733 }
1734
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001735 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001736 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001737 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001738
1739 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001740 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001741 Diag(Loc, diag::err_bad_variable_name)
1742 << Name;
1743 return 0;
1744 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001745
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001746 IdentifierInfo *II = Name.getAsIdentifierInfo();
1747
Douglas Gregorf2503652011-09-21 14:40:46 +00001748 // Member field could not be with "template" keyword.
1749 // So TemplateParameterLists should be empty in this case.
1750 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001751 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001752 if (TemplateParams->size()) {
1753 // There is no such thing as a member field template.
1754 Diag(D.getIdentifierLoc(), diag::err_template_member)
1755 << II
1756 << SourceRange(TemplateParams->getTemplateLoc(),
1757 TemplateParams->getRAngleLoc());
1758 } else {
1759 // There is an extraneous 'template<>' for this member.
1760 Diag(TemplateParams->getTemplateLoc(),
1761 diag::err_template_member_noparams)
1762 << II
1763 << SourceRange(TemplateParams->getTemplateLoc(),
1764 TemplateParams->getRAngleLoc());
1765 }
1766 return 0;
1767 }
1768
Douglas Gregor922fff22010-10-13 22:19:53 +00001769 if (SS.isSet() && !SS.isInvalid()) {
1770 // The user provided a superfluous scope specifier inside a class
1771 // definition:
1772 //
1773 // class X {
1774 // int X::member;
1775 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001776 if (DeclContext *DC = computeDeclContext(SS, false))
1777 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001778 else
1779 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1780 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001781
Douglas Gregor922fff22010-10-13 22:19:53 +00001782 SS.clear();
1783 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001784
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001785 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001786 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001787 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001788 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001789 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001790
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001791 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001792 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001793 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001794 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001795
1796 // Non-instance-fields can't have a bitfield.
1797 if (BitWidth) {
1798 if (Member->isInvalidDecl()) {
1799 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001800 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001801 // C++ 9.6p3: A bit-field shall not be a static member.
1802 // "static member 'A' cannot be a bit-field"
1803 Diag(Loc, diag::err_static_not_bitfield)
1804 << Name << BitWidth->getSourceRange();
1805 } else if (isa<TypedefDecl>(Member)) {
1806 // "typedef member 'x' cannot be a bit-field"
1807 Diag(Loc, diag::err_typedef_not_bitfield)
1808 << Name << BitWidth->getSourceRange();
1809 } else {
1810 // A function typedef ("typedef int f(); f a;").
1811 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1812 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001813 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001814 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001815 }
Mike Stump1eb44332009-09-09 15:08:12 +00001816
Chris Lattner8b963ef2009-03-05 23:01:03 +00001817 BitWidth = 0;
1818 Member->setInvalidDecl();
1819 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001820
1821 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Douglas Gregor37b372b2009-08-20 22:52:58 +00001823 // If we have declared a member function template, set the access of the
1824 // templated declaration as well.
1825 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1826 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001827 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001828
Richard Smitha4b39652012-08-06 03:25:17 +00001829 if (VS.isOverrideSpecified())
1830 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1831 if (VS.isFinalSpecified())
1832 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001833
Douglas Gregorf5251602011-03-08 17:10:18 +00001834 if (VS.getLastLocation().isValid()) {
1835 // Update the end location of a method that has a virt-specifiers.
1836 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1837 MD->setRangeEnd(VS.getLastLocation());
1838 }
Richard Smitha4b39652012-08-06 03:25:17 +00001839
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001840 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001841
Douglas Gregor10bd3682008-11-17 22:58:34 +00001842 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001843
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001844 if (isInstField) {
1845 FieldDecl *FD = cast<FieldDecl>(Member);
1846 FieldCollector->Add(FD);
1847
1848 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1849 FD->getLocation())
1850 != DiagnosticsEngine::Ignored) {
1851 // Remember all explicit private FieldDecls that have a name, no side
1852 // effects and are not part of a dependent type declaration.
1853 if (!FD->isImplicit() && FD->getDeclName() &&
1854 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001855 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001856 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001857 !InitializationHasSideEffects(*FD))
1858 UnusedPrivateFields.insert(FD);
1859 }
1860 }
1861
John McCalld226f652010-08-21 09:40:31 +00001862 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001863}
1864
Hans Wennborg471f9852012-09-18 15:58:06 +00001865namespace {
1866 class UninitializedFieldVisitor
1867 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1868 Sema &S;
1869 ValueDecl *VD;
1870 public:
1871 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1872 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001873 S(S) {
1874 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1875 this->VD = IFD->getAnonField();
1876 else
1877 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001878 }
1879
1880 void HandleExpr(Expr *E) {
1881 if (!E) return;
1882
1883 // Expressions like x(x) sometimes lack the surrounding expressions
1884 // but need to be checked anyways.
1885 HandleValue(E);
1886 Visit(E);
1887 }
1888
1889 void HandleValue(Expr *E) {
1890 E = E->IgnoreParens();
1891
1892 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1893 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001894 return;
1895
1896 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1897 // or union.
1898 MemberExpr *FieldME = ME;
1899
Hans Wennborg471f9852012-09-18 15:58:06 +00001900 Expr *Base = E;
1901 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001902 ME = cast<MemberExpr>(Base);
1903
1904 if (isa<VarDecl>(ME->getMemberDecl()))
1905 return;
1906
1907 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1908 if (!FD->isAnonymousStructOrUnion())
1909 FieldME = ME;
1910
Hans Wennborg471f9852012-09-18 15:58:06 +00001911 Base = ME->getBase();
1912 }
1913
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001914 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00001915 unsigned diag = VD->getType()->isReferenceType()
1916 ? diag::warn_reference_field_is_uninit
1917 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001918 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001919 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001920 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00001921 }
1922
1923 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1924 HandleValue(CO->getTrueExpr());
1925 HandleValue(CO->getFalseExpr());
1926 return;
1927 }
1928
1929 if (BinaryConditionalOperator *BCO =
1930 dyn_cast<BinaryConditionalOperator>(E)) {
1931 HandleValue(BCO->getCommon());
1932 HandleValue(BCO->getFalseExpr());
1933 return;
1934 }
1935
1936 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1937 switch (BO->getOpcode()) {
1938 default:
1939 return;
1940 case(BO_PtrMemD):
1941 case(BO_PtrMemI):
1942 HandleValue(BO->getLHS());
1943 return;
1944 case(BO_Comma):
1945 HandleValue(BO->getRHS());
1946 return;
1947 }
1948 }
1949 }
1950
1951 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1952 if (E->getCastKind() == CK_LValueToRValue)
1953 HandleValue(E->getSubExpr());
1954
1955 Inherited::VisitImplicitCastExpr(E);
1956 }
1957
1958 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1959 Expr *Callee = E->getCallee();
1960 if (isa<MemberExpr>(Callee))
1961 HandleValue(Callee);
1962
1963 Inherited::VisitCXXMemberCallExpr(E);
1964 }
1965 };
1966 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1967 ValueDecl *VD) {
1968 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1969 }
1970} // namespace
1971
Richard Smith7a614d82011-06-11 17:19:42 +00001972/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001973/// in-class initializer for a non-static C++ class member, and after
1974/// instantiating an in-class initializer in a class template. Such actions
1975/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001976void
Richard Smithca523302012-06-10 03:12:00 +00001977Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001978 Expr *InitExpr) {
1979 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001980 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1981 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001982
1983 if (!InitExpr) {
1984 FD->setInvalidDecl();
1985 FD->removeInClassInitializer();
1986 return;
1987 }
1988
Peter Collingbournefef21892011-10-23 18:59:44 +00001989 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1990 FD->setInvalidDecl();
1991 FD->removeInClassInitializer();
1992 return;
1993 }
1994
Hans Wennborg471f9852012-09-18 15:58:06 +00001995 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1996 != DiagnosticsEngine::Ignored) {
1997 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1998 }
1999
Richard Smith7a614d82011-06-11 17:19:42 +00002000 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002001 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00002002 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002003 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00002004 << /*at end of ctor*/1 << InitExpr->getSourceRange();
2005 }
Sebastian Redl33deb352012-02-22 10:50:08 +00002006 Expr **Inits = &InitExpr;
2007 unsigned NumInits = 1;
2008 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002009 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002010 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002011 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00002012 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
2013 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00002014 if (Init.isInvalid()) {
2015 FD->setInvalidDecl();
2016 return;
2017 }
Richard Smith7a614d82011-06-11 17:19:42 +00002018 }
2019
Richard Smith41956372013-01-14 22:39:08 +00002020 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002021 // The initialization of each base and member constitutes a
2022 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002023 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002024 if (Init.isInvalid()) {
2025 FD->setInvalidDecl();
2026 return;
2027 }
2028
2029 InitExpr = Init.release();
2030
2031 FD->setInClassInitializer(InitExpr);
2032}
2033
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002034/// \brief Find the direct and/or virtual base specifiers that
2035/// correspond to the given base type, for use in base initialization
2036/// within a constructor.
2037static bool FindBaseInitializer(Sema &SemaRef,
2038 CXXRecordDecl *ClassDecl,
2039 QualType BaseType,
2040 const CXXBaseSpecifier *&DirectBaseSpec,
2041 const CXXBaseSpecifier *&VirtualBaseSpec) {
2042 // First, check for a direct base class.
2043 DirectBaseSpec = 0;
2044 for (CXXRecordDecl::base_class_const_iterator Base
2045 = ClassDecl->bases_begin();
2046 Base != ClassDecl->bases_end(); ++Base) {
2047 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2048 // We found a direct base of this type. That's what we're
2049 // initializing.
2050 DirectBaseSpec = &*Base;
2051 break;
2052 }
2053 }
2054
2055 // Check for a virtual base class.
2056 // FIXME: We might be able to short-circuit this if we know in advance that
2057 // there are no virtual bases.
2058 VirtualBaseSpec = 0;
2059 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2060 // We haven't found a base yet; search the class hierarchy for a
2061 // virtual base class.
2062 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2063 /*DetectVirtual=*/false);
2064 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2065 BaseType, Paths)) {
2066 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2067 Path != Paths.end(); ++Path) {
2068 if (Path->back().Base->isVirtual()) {
2069 VirtualBaseSpec = Path->back().Base;
2070 break;
2071 }
2072 }
2073 }
2074 }
2075
2076 return DirectBaseSpec || VirtualBaseSpec;
2077}
2078
Sebastian Redl6df65482011-09-24 17:48:25 +00002079/// \brief Handle a C++ member initializer using braced-init-list syntax.
2080MemInitResult
2081Sema::ActOnMemInitializer(Decl *ConstructorD,
2082 Scope *S,
2083 CXXScopeSpec &SS,
2084 IdentifierInfo *MemberOrBase,
2085 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002086 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002087 SourceLocation IdLoc,
2088 Expr *InitList,
2089 SourceLocation EllipsisLoc) {
2090 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002091 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002092 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002093}
2094
2095/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002096MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002097Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002098 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002099 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002100 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002101 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002102 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002103 SourceLocation IdLoc,
2104 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002105 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002106 SourceLocation RParenLoc,
2107 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002108 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2109 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002110 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002111 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002112 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002113}
2114
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002115namespace {
2116
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002117// Callback to only accept typo corrections that can be a valid C++ member
2118// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002119class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2120 public:
2121 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2122 : ClassDecl(ClassDecl) {}
2123
2124 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2125 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2126 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2127 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2128 else
2129 return isa<TypeDecl>(ND);
2130 }
2131 return false;
2132 }
2133
2134 private:
2135 CXXRecordDecl *ClassDecl;
2136};
2137
2138}
2139
Sebastian Redl6df65482011-09-24 17:48:25 +00002140/// \brief Handle a C++ member initializer.
2141MemInitResult
2142Sema::BuildMemInitializer(Decl *ConstructorD,
2143 Scope *S,
2144 CXXScopeSpec &SS,
2145 IdentifierInfo *MemberOrBase,
2146 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002147 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002148 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002149 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002150 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002151 if (!ConstructorD)
2152 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002153
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002154 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002155
2156 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002157 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002158 if (!Constructor) {
2159 // The user wrote a constructor initializer on a function that is
2160 // not a C++ constructor. Ignore the error for now, because we may
2161 // have more member initializers coming; we'll diagnose it just
2162 // once in ActOnMemInitializers.
2163 return true;
2164 }
2165
2166 CXXRecordDecl *ClassDecl = Constructor->getParent();
2167
2168 // C++ [class.base.init]p2:
2169 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002170 // constructor's class and, if not found in that scope, are looked
2171 // up in the scope containing the constructor's definition.
2172 // [Note: if the constructor's class contains a member with the
2173 // same name as a direct or virtual base class of the class, a
2174 // mem-initializer-id naming the member or base class and composed
2175 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002176 // mem-initializer-id for the hidden base class may be specified
2177 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002178 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002179 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002180 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002181 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002182 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002183 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002184 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2185 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002186 if (EllipsisLoc.isValid())
2187 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002188 << MemberOrBase
2189 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002190
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002191 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002192 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002193 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002194 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002195 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002196 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002197 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002198
2199 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002200 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002201 } else if (DS.getTypeSpecType() == TST_decltype) {
2202 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002203 } else {
2204 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2205 LookupParsedName(R, S, &SS);
2206
2207 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2208 if (!TyD) {
2209 if (R.isAmbiguous()) return true;
2210
John McCallfd225442010-04-09 19:01:14 +00002211 // We don't want access-control diagnostics here.
2212 R.suppressDiagnostics();
2213
Douglas Gregor7a886e12010-01-19 06:46:48 +00002214 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2215 bool NotUnknownSpecialization = false;
2216 DeclContext *DC = computeDeclContext(SS, false);
2217 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2218 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2219
2220 if (!NotUnknownSpecialization) {
2221 // When the scope specifier can refer to a member of an unknown
2222 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002223 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2224 SS.getWithLocInContext(Context),
2225 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002226 if (BaseType.isNull())
2227 return true;
2228
Douglas Gregor7a886e12010-01-19 06:46:48 +00002229 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002230 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002231 }
2232 }
2233
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002234 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002235 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002236 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002237 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002238 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002239 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002240 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2241 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002242 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002243 // We have found a non-static data member with a similar
2244 // name to what was typed; complain and initialize that
2245 // member.
2246 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2247 << MemberOrBase << true << CorrectedQuotedStr
2248 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2249 Diag(Member->getLocation(), diag::note_previous_decl)
2250 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002251
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002252 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002253 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002254 const CXXBaseSpecifier *DirectBaseSpec;
2255 const CXXBaseSpecifier *VirtualBaseSpec;
2256 if (FindBaseInitializer(*this, ClassDecl,
2257 Context.getTypeDeclType(Type),
2258 DirectBaseSpec, VirtualBaseSpec)) {
2259 // We have found a direct or virtual base class with a
2260 // similar name to what was typed; complain and initialize
2261 // that base class.
2262 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002263 << MemberOrBase << false << CorrectedQuotedStr
2264 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002265
2266 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2267 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002268 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002269 diag::note_base_class_specified_here)
2270 << BaseSpec->getType()
2271 << BaseSpec->getSourceRange();
2272
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002273 TyD = Type;
2274 }
2275 }
2276 }
2277
Douglas Gregor7a886e12010-01-19 06:46:48 +00002278 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002279 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002280 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002281 return true;
2282 }
John McCall2b194412009-12-21 10:41:20 +00002283 }
2284
Douglas Gregor7a886e12010-01-19 06:46:48 +00002285 if (BaseType.isNull()) {
2286 BaseType = Context.getTypeDeclType(TyD);
2287 if (SS.isSet()) {
2288 NestedNameSpecifier *Qualifier =
2289 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002290
Douglas Gregor7a886e12010-01-19 06:46:48 +00002291 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002292 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002293 }
John McCall2b194412009-12-21 10:41:20 +00002294 }
2295 }
Mike Stump1eb44332009-09-09 15:08:12 +00002296
John McCalla93c9342009-12-07 02:54:59 +00002297 if (!TInfo)
2298 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002299
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002300 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002301}
2302
Chandler Carruth81c64772011-09-03 01:14:15 +00002303/// Checks a member initializer expression for cases where reference (or
2304/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002305static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2306 Expr *Init,
2307 SourceLocation IdLoc) {
2308 QualType MemberTy = Member->getType();
2309
2310 // We only handle pointers and references currently.
2311 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2312 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2313 return;
2314
2315 const bool IsPointer = MemberTy->isPointerType();
2316 if (IsPointer) {
2317 if (const UnaryOperator *Op
2318 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2319 // The only case we're worried about with pointers requires taking the
2320 // address.
2321 if (Op->getOpcode() != UO_AddrOf)
2322 return;
2323
2324 Init = Op->getSubExpr();
2325 } else {
2326 // We only handle address-of expression initializers for pointers.
2327 return;
2328 }
2329 }
2330
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002331 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2332 // Taking the address of a temporary will be diagnosed as a hard error.
2333 if (IsPointer)
2334 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002335
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002336 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2337 << Member << Init->getSourceRange();
2338 } else if (const DeclRefExpr *DRE
2339 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2340 // We only warn when referring to a non-reference parameter declaration.
2341 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2342 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002343 return;
2344
2345 S.Diag(Init->getExprLoc(),
2346 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2347 : diag::warn_bind_ref_member_to_parameter)
2348 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002349 } else {
2350 // Other initializers are fine.
2351 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002352 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002353
2354 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2355 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002356}
2357
John McCallf312b1e2010-08-26 23:41:50 +00002358MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002359Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002360 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002361 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2362 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2363 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002364 "Member must be a FieldDecl or IndirectFieldDecl");
2365
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002366 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002367 return true;
2368
Douglas Gregor464b2f02010-11-05 22:21:31 +00002369 if (Member->isInvalidDecl())
2370 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002371
John McCallb4190042009-11-04 23:02:40 +00002372 // Diagnose value-uses of fields to initialize themselves, e.g.
2373 // foo(foo)
2374 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002375 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002376 Expr **Args;
2377 unsigned NumArgs;
2378 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2379 Args = ParenList->getExprs();
2380 NumArgs = ParenList->getNumExprs();
Richard Smithc83c2302012-12-19 01:39:02 +00002381 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002382 Args = InitList->getInits();
2383 NumArgs = InitList->getNumInits();
Richard Smithc83c2302012-12-19 01:39:02 +00002384 } else {
2385 // Template instantiation doesn't reconstruct ParenListExprs for us.
2386 Args = &Init;
2387 NumArgs = 1;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002388 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002389
Richard Trieude5e75c2012-06-14 23:11:34 +00002390 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2391 != DiagnosticsEngine::Ignored)
2392 for (unsigned i = 0; i < NumArgs; ++i)
2393 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002394 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002395 // initializing the i'th field, throw a warning if any of the >= i'th
2396 // fields are used, as they are not yet initialized.
2397 // Right now we are only handling the case where the i'th field uses
2398 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002399 // Also need to take into account that some fields may be initialized by
2400 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002401 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002402
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002403 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002404
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002405 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002406 // Can't check initialization for a member of dependent type or when
2407 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002408 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002409 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002410 bool InitList = false;
2411 if (isa<InitListExpr>(Init)) {
2412 InitList = true;
2413 Args = &Init;
2414 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002415
2416 if (isStdInitializerList(Member->getType(), 0)) {
2417 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2418 << /*at end of ctor*/1 << InitRange;
2419 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002420 }
2421
Chandler Carruth894aed92010-12-06 09:23:57 +00002422 // Initialize the member.
2423 InitializedEntity MemberEntity =
2424 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2425 : InitializedEntity::InitializeMember(IndirectMember, 0);
2426 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002427 InitList ? InitializationKind::CreateDirectList(IdLoc)
2428 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2429 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002430
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002431 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2432 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002433 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002434 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002435 if (MemberInit.isInvalid())
2436 return true;
2437
Richard Smith41956372013-01-14 22:39:08 +00002438 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002439 // The initialization of each base and member constitutes a
2440 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002441 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002442 if (MemberInit.isInvalid())
2443 return true;
2444
Richard Smithc83c2302012-12-19 01:39:02 +00002445 Init = MemberInit.get();
2446 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002447 }
2448
Chandler Carruth894aed92010-12-06 09:23:57 +00002449 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002450 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2451 InitRange.getBegin(), Init,
2452 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002453 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002454 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2455 InitRange.getBegin(), Init,
2456 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002457 }
Eli Friedman59c04372009-07-29 19:44:27 +00002458}
2459
John McCallf312b1e2010-08-26 23:41:50 +00002460MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002461Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002462 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002463 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002464 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002465 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002466 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002467 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002468
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002469 bool InitList = true;
2470 Expr **Args = &Init;
2471 unsigned NumArgs = 1;
2472 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2473 InitList = false;
2474 Args = ParenList->getExprs();
2475 NumArgs = ParenList->getNumExprs();
2476 }
2477
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002478 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002479 // Initialize the object.
2480 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2481 QualType(ClassDecl->getTypeForDecl(), 0));
2482 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002483 InitList ? InitializationKind::CreateDirectList(NameLoc)
2484 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2485 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002486 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2487 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002488 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002489 0);
Sean Hunt41717662011-02-26 19:13:13 +00002490 if (DelegationInit.isInvalid())
2491 return true;
2492
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002493 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2494 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002495
Richard Smith41956372013-01-14 22:39:08 +00002496 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002497 // The initialization of each base and member constitutes a
2498 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002499 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2500 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002501 if (DelegationInit.isInvalid())
2502 return true;
2503
Eli Friedmand21016f2012-05-19 23:35:23 +00002504 // If we are in a dependent context, template instantiation will
2505 // perform this type-checking again. Just save the arguments that we
2506 // received in a ParenListExpr.
2507 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2508 // of the information that we have about the base
2509 // initializer. However, deconstructing the ASTs is a dicey process,
2510 // and this approach is far more likely to get the corner cases right.
2511 if (CurContext->isDependentContext())
2512 DelegationInit = Owned(Init);
2513
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002514 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002515 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002516 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002517}
2518
2519MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002520Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002521 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002522 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002523 SourceLocation BaseLoc
2524 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002525
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002526 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2527 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2528 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2529
2530 // C++ [class.base.init]p2:
2531 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002532 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002533 // of that class, the mem-initializer is ill-formed. A
2534 // mem-initializer-list can initialize a base class using any
2535 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002536 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002537
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002538 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002539 if (EllipsisLoc.isValid()) {
2540 // This is a pack expansion.
2541 if (!BaseType->containsUnexpandedParameterPack()) {
2542 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002543 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002544
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002545 EllipsisLoc = SourceLocation();
2546 }
2547 } else {
2548 // Check for any unexpanded parameter packs.
2549 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2550 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002551
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002552 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002553 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002554 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002555
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002556 // Check for direct and virtual base classes.
2557 const CXXBaseSpecifier *DirectBaseSpec = 0;
2558 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2559 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002560 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2561 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002562 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002563
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002564 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2565 VirtualBaseSpec);
2566
2567 // C++ [base.class.init]p2:
2568 // Unless the mem-initializer-id names a nonstatic data member of the
2569 // constructor's class or a direct or virtual base of that class, the
2570 // mem-initializer is ill-formed.
2571 if (!DirectBaseSpec && !VirtualBaseSpec) {
2572 // If the class has any dependent bases, then it's possible that
2573 // one of those types will resolve to the same type as
2574 // BaseType. Therefore, just treat this as a dependent base
2575 // class initialization. FIXME: Should we try to check the
2576 // initialization anyway? It seems odd.
2577 if (ClassDecl->hasAnyDependentBases())
2578 Dependent = true;
2579 else
2580 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2581 << BaseType << Context.getTypeDeclType(ClassDecl)
2582 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2583 }
2584 }
2585
2586 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002587 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002588
Sebastian Redl6df65482011-09-24 17:48:25 +00002589 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2590 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002591 InitRange.getBegin(), Init,
2592 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002593 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002594
2595 // C++ [base.class.init]p2:
2596 // If a mem-initializer-id is ambiguous because it designates both
2597 // a direct non-virtual base class and an inherited virtual base
2598 // class, the mem-initializer is ill-formed.
2599 if (DirectBaseSpec && VirtualBaseSpec)
2600 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002601 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002602
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002603 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002604 if (!BaseSpec)
2605 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2606
2607 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002608 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002609 Expr **Args = &Init;
2610 unsigned NumArgs = 1;
2611 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002612 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002613 Args = ParenList->getExprs();
2614 NumArgs = ParenList->getNumExprs();
2615 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002616
2617 InitializedEntity BaseEntity =
2618 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2619 InitializationKind Kind =
2620 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2621 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2622 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002623 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2624 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002625 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002626 if (BaseInit.isInvalid())
2627 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002628
Richard Smith41956372013-01-14 22:39:08 +00002629 // C++11 [class.base.init]p7:
2630 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002631 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002632 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002633 if (BaseInit.isInvalid())
2634 return true;
2635
2636 // If we are in a dependent context, template instantiation will
2637 // perform this type-checking again. Just save the arguments that we
2638 // received in a ParenListExpr.
2639 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2640 // of the information that we have about the base
2641 // initializer. However, deconstructing the ASTs is a dicey process,
2642 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002643 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002644 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002645
Sean Huntcbb67482011-01-08 20:30:50 +00002646 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002647 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002648 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002649 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002650 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002651}
2652
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002653// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002654static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2655 if (T.isNull()) T = E->getType();
2656 QualType TargetType = SemaRef.BuildReferenceType(
2657 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002658 SourceLocation ExprLoc = E->getLocStart();
2659 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2660 TargetType, ExprLoc);
2661
2662 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2663 SourceRange(ExprLoc, ExprLoc),
2664 E->getSourceRange()).take();
2665}
2666
Anders Carlssone5ef7402010-04-23 03:10:23 +00002667/// ImplicitInitializerKind - How an implicit base or member initializer should
2668/// initialize its base or member.
2669enum ImplicitInitializerKind {
2670 IIK_Default,
2671 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002672 IIK_Move,
2673 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002674};
2675
Anders Carlssondefefd22010-04-23 02:00:02 +00002676static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002677BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002678 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002679 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002680 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002681 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002682 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002683 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2684 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002685
John McCall60d7b3a2010-08-24 06:29:42 +00002686 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002687
2688 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002689 case IIK_Inherit: {
2690 const CXXRecordDecl *Inherited =
2691 Constructor->getInheritedConstructor()->getParent();
2692 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2693 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2694 // C++11 [class.inhctor]p8:
2695 // Each expression in the expression-list is of the form
2696 // static_cast<T&&>(p), where p is the name of the corresponding
2697 // constructor parameter and T is the declared type of p.
2698 SmallVector<Expr*, 16> Args;
2699 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2700 ParmVarDecl *PD = Constructor->getParamDecl(I);
2701 ExprResult ArgExpr =
2702 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2703 VK_LValue, SourceLocation());
2704 if (ArgExpr.isInvalid())
2705 return true;
2706 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2707 }
2708
2709 InitializationKind InitKind = InitializationKind::CreateDirect(
2710 Constructor->getLocation(), SourceLocation(), SourceLocation());
2711 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2712 Args.data(), Args.size());
2713 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2714 break;
2715 }
2716 }
2717 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002718 case IIK_Default: {
2719 InitializationKind InitKind
2720 = InitializationKind::CreateDefault(Constructor->getLocation());
2721 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002722 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002723 break;
2724 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002725
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002726 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002727 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002728 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002729 ParmVarDecl *Param = Constructor->getParamDecl(0);
2730 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002731
Anders Carlssone5ef7402010-04-23 03:10:23 +00002732 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002733 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002734 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002735 Constructor->getLocation(), ParamType,
2736 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002737
Eli Friedman5f2987c2012-02-02 03:46:19 +00002738 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2739
Anders Carlssonc7957502010-04-24 22:02:54 +00002740 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002741 QualType ArgTy =
2742 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2743 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002744
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002745 if (Moving) {
2746 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2747 }
2748
John McCallf871d0c2010-08-07 06:22:56 +00002749 CXXCastPath BasePath;
2750 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002751 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2752 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002753 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002754 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002755
Anders Carlssone5ef7402010-04-23 03:10:23 +00002756 InitializationKind InitKind
2757 = InitializationKind::CreateDirect(Constructor->getLocation(),
2758 SourceLocation(), SourceLocation());
2759 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2760 &CopyCtorArg, 1);
2761 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002762 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002763 break;
2764 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002765 }
John McCall9ae2f072010-08-23 23:25:46 +00002766
Douglas Gregor53c374f2010-12-07 00:41:46 +00002767 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002768 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002769 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002770
Anders Carlssondefefd22010-04-23 02:00:02 +00002771 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002772 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002773 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2774 SourceLocation()),
2775 BaseSpec->isVirtual(),
2776 SourceLocation(),
2777 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002778 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002779 SourceLocation());
2780
Anders Carlssondefefd22010-04-23 02:00:02 +00002781 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002782}
2783
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002784static bool RefersToRValueRef(Expr *MemRef) {
2785 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2786 return Referenced->getType()->isRValueReferenceType();
2787}
2788
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002789static bool
2790BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002791 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002792 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002793 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002794 if (Field->isInvalidDecl())
2795 return true;
2796
Chandler Carruthf186b542010-06-29 23:50:44 +00002797 SourceLocation Loc = Constructor->getLocation();
2798
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002799 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2800 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002801 ParmVarDecl *Param = Constructor->getParamDecl(0);
2802 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002803
2804 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002805 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2806 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002807
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002808 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002809 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002810 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002811 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002812
Eli Friedman5f2987c2012-02-02 03:46:19 +00002813 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2814
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002815 if (Moving) {
2816 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2817 }
2818
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002819 // Build a reference to this field within the parameter.
2820 CXXScopeSpec SS;
2821 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2822 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002823 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2824 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002825 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002826 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002827 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002828 ParamType, Loc,
2829 /*IsArrow=*/false,
2830 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002831 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002832 /*FirstQualifierInScope=*/0,
2833 MemberLookup,
2834 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002835 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002836 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002837
2838 // C++11 [class.copy]p15:
2839 // - if a member m has rvalue reference type T&&, it is direct-initialized
2840 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002841 if (RefersToRValueRef(CtorArg.get())) {
2842 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002843 }
2844
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002845 // When the field we are copying is an array, create index variables for
2846 // each dimension of the array. We use these index variables to subscript
2847 // the source array, and other clients (e.g., CodeGen) will perform the
2848 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002849 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002850 QualType BaseType = Field->getType();
2851 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002852 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002853 while (const ConstantArrayType *Array
2854 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002855 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002856 // Create the iteration variable for this array index.
2857 IdentifierInfo *IterationVarName = 0;
2858 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002859 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002860 llvm::raw_svector_ostream OS(Str);
2861 OS << "__i" << IndexVariables.size();
2862 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2863 }
2864 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002865 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002866 IterationVarName, SizeType,
2867 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002868 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002869 IndexVariables.push_back(IterationVar);
2870
2871 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002872 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002873 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002874 assert(!IterationVarRef.isInvalid() &&
2875 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002876 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2877 assert(!IterationVarRef.isInvalid() &&
2878 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002879
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002880 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002881 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002882 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002883 Loc);
2884 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002885 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002886
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002887 BaseType = Array->getElementType();
2888 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002889
2890 // The array subscript expression is an lvalue, which is wrong for moving.
2891 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002892 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002893
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002894 // Construct the entity that we will be initializing. For an array, this
2895 // will be first element in the array, which may require several levels
2896 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002897 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002898 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002899 if (Indirect)
2900 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2901 else
2902 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002903 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2904 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2905 0,
2906 Entities.back()));
2907
2908 // Direct-initialize to use the copy constructor.
2909 InitializationKind InitKind =
2910 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2911
Sebastian Redl74e611a2011-09-04 18:14:28 +00002912 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002913 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002914 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002915
John McCall60d7b3a2010-08-24 06:29:42 +00002916 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002917 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002918 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002919 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002920 if (MemberInit.isInvalid())
2921 return true;
2922
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002923 if (Indirect) {
2924 assert(IndexVariables.size() == 0 &&
2925 "Indirect field improperly initialized");
2926 CXXMemberInit
2927 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2928 Loc, Loc,
2929 MemberInit.takeAs<Expr>(),
2930 Loc);
2931 } else
2932 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2933 Loc, MemberInit.takeAs<Expr>(),
2934 Loc,
2935 IndexVariables.data(),
2936 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002937 return false;
2938 }
2939
Richard Smith07b0fdc2013-03-18 21:12:30 +00002940 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
2941 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002942
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002943 QualType FieldBaseElementType =
2944 SemaRef.Context.getBaseElementType(Field->getType());
2945
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002946 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002947 InitializedEntity InitEntity
2948 = Indirect? InitializedEntity::InitializeMember(Indirect)
2949 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002950 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002951 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002952
2953 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002954 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002955 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002956
Douglas Gregor53c374f2010-12-07 00:41:46 +00002957 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002958 if (MemberInit.isInvalid())
2959 return true;
2960
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002961 if (Indirect)
2962 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2963 Indirect, Loc,
2964 Loc,
2965 MemberInit.get(),
2966 Loc);
2967 else
2968 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2969 Field, Loc, Loc,
2970 MemberInit.get(),
2971 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002972 return false;
2973 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002974
Sean Hunt1f2f3842011-05-17 00:19:05 +00002975 if (!Field->getParent()->isUnion()) {
2976 if (FieldBaseElementType->isReferenceType()) {
2977 SemaRef.Diag(Constructor->getLocation(),
2978 diag::err_uninitialized_member_in_ctor)
2979 << (int)Constructor->isImplicit()
2980 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2981 << 0 << Field->getDeclName();
2982 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2983 return true;
2984 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002985
Sean Hunt1f2f3842011-05-17 00:19:05 +00002986 if (FieldBaseElementType.isConstQualified()) {
2987 SemaRef.Diag(Constructor->getLocation(),
2988 diag::err_uninitialized_member_in_ctor)
2989 << (int)Constructor->isImplicit()
2990 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2991 << 1 << Field->getDeclName();
2992 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2993 return true;
2994 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002995 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002996
David Blaikie4e4d0842012-03-11 07:00:24 +00002997 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002998 FieldBaseElementType->isObjCRetainableType() &&
2999 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3000 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003001 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003002 // Default-initialize Objective-C pointers to NULL.
3003 CXXMemberInit
3004 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3005 Loc, Loc,
3006 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3007 Loc);
3008 return false;
3009 }
3010
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003011 // Nothing to initialize.
3012 CXXMemberInit = 0;
3013 return false;
3014}
John McCallf1860e52010-05-20 23:23:51 +00003015
3016namespace {
3017struct BaseAndFieldInfo {
3018 Sema &S;
3019 CXXConstructorDecl *Ctor;
3020 bool AnyErrorsInInits;
3021 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003022 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003023 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003024
3025 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3026 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003027 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3028 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003029 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003030 else if (Generated && Ctor->isMoveConstructor())
3031 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003032 else if (Ctor->getInheritedConstructor())
3033 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003034 else
3035 IIK = IIK_Default;
3036 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003037
3038 bool isImplicitCopyOrMove() const {
3039 switch (IIK) {
3040 case IIK_Copy:
3041 case IIK_Move:
3042 return true;
3043
3044 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003045 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003046 return false;
3047 }
David Blaikie30263482012-01-20 21:50:17 +00003048
3049 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003050 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003051
3052 bool addFieldInitializer(CXXCtorInitializer *Init) {
3053 AllToInit.push_back(Init);
3054
3055 // Check whether this initializer makes the field "used".
3056 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
3057 S.UnusedPrivateFields.remove(Init->getAnyMember());
3058
3059 return false;
3060 }
John McCallf1860e52010-05-20 23:23:51 +00003061};
3062}
3063
Richard Smitha4950662011-09-19 13:34:43 +00003064/// \brief Determine whether the given indirect field declaration is somewhere
3065/// within an anonymous union.
3066static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3067 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3068 CEnd = F->chain_end();
3069 C != CEnd; ++C)
3070 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3071 if (Record->isUnion())
3072 return true;
3073
3074 return false;
3075}
3076
Douglas Gregorddb21472011-11-02 23:04:16 +00003077/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3078/// array type.
3079static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3080 if (T->isIncompleteArrayType())
3081 return true;
3082
3083 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3084 if (!ArrayT->getSize())
3085 return true;
3086
3087 T = ArrayT->getElementType();
3088 }
3089
3090 return false;
3091}
3092
Richard Smith7a614d82011-06-11 17:19:42 +00003093static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003094 FieldDecl *Field,
3095 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003096
Chandler Carruthe861c602010-06-30 02:59:29 +00003097 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003098 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3099 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003100
Richard Smith0b8220a2012-08-07 21:30:42 +00003101 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003102 // has a brace-or-equal-initializer, the entity is initialized as specified
3103 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003104 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003105 CXXCtorInitializer *Init;
3106 if (Indirect)
3107 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3108 SourceLocation(),
3109 SourceLocation(), 0,
3110 SourceLocation());
3111 else
3112 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3113 SourceLocation(),
3114 SourceLocation(), 0,
3115 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003116 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003117 }
3118
Richard Smithc115f632011-09-18 11:14:50 +00003119 // Don't build an implicit initializer for union members if none was
3120 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003121 if (Field->getParent()->isUnion() ||
3122 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003123 return false;
3124
Douglas Gregorddb21472011-11-02 23:04:16 +00003125 // Don't initialize incomplete or zero-length arrays.
3126 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3127 return false;
3128
John McCallf1860e52010-05-20 23:23:51 +00003129 // Don't try to build an implicit initializer if there were semantic
3130 // errors in any of the initializers (and therefore we might be
3131 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003132 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003133 return false;
3134
Sean Huntcbb67482011-01-08 20:30:50 +00003135 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003136 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3137 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003138 return true;
John McCallf1860e52010-05-20 23:23:51 +00003139
Richard Smith0b8220a2012-08-07 21:30:42 +00003140 if (!Init)
3141 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003142
Richard Smith0b8220a2012-08-07 21:30:42 +00003143 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003144}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003145
3146bool
3147Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3148 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003149 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003150 Constructor->setNumCtorInitializers(1);
3151 CXXCtorInitializer **initializer =
3152 new (Context) CXXCtorInitializer*[1];
3153 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3154 Constructor->setCtorInitializers(initializer);
3155
Sean Huntb76af9c2011-05-03 23:05:34 +00003156 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003157 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003158 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3159 }
3160
Sean Huntc1598702011-05-05 00:05:47 +00003161 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003162
Sean Hunt059ce0d2011-05-01 07:04:31 +00003163 return false;
3164}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003165
David Blaikie93c86172013-01-17 05:26:25 +00003166bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3167 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003168 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003169 // Just store the initializers as written, they will be checked during
3170 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003171 if (!Initializers.empty()) {
3172 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003173 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003174 new (Context) CXXCtorInitializer*[Initializers.size()];
3175 memcpy(baseOrMemberInitializers, Initializers.data(),
3176 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003177 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003178 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003179
3180 // Let template instantiation know whether we had errors.
3181 if (AnyErrors)
3182 Constructor->setInvalidDecl();
3183
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003184 return false;
3185 }
3186
John McCallf1860e52010-05-20 23:23:51 +00003187 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003188
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003189 // We need to build the initializer AST according to order of construction
3190 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003191 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003192 if (!ClassDecl)
3193 return true;
3194
Eli Friedman80c30da2009-11-09 19:20:36 +00003195 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003196
David Blaikie93c86172013-01-17 05:26:25 +00003197 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003198 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003199
3200 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003201 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003202 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003203 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003204 }
3205
Anders Carlsson711f34a2010-04-21 19:52:01 +00003206 // Keep track of the direct virtual bases.
3207 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3208 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3209 E = ClassDecl->bases_end(); I != E; ++I) {
3210 if (I->isVirtual())
3211 DirectVBases.insert(I);
3212 }
3213
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003214 // Push virtual bases before others.
3215 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3216 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3217
Sean Huntcbb67482011-01-08 20:30:50 +00003218 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003219 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3220 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003221 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003222 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003223 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003224 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003225 VBase, IsInheritedVirtualBase,
3226 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003227 HadError = true;
3228 continue;
3229 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003230
John McCallf1860e52010-05-20 23:23:51 +00003231 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003232 }
3233 }
Mike Stump1eb44332009-09-09 15:08:12 +00003234
John McCallf1860e52010-05-20 23:23:51 +00003235 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003236 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3237 E = ClassDecl->bases_end(); Base != E; ++Base) {
3238 // Virtuals are in the virtual base list and already constructed.
3239 if (Base->isVirtual())
3240 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003241
Sean Huntcbb67482011-01-08 20:30:50 +00003242 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003243 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3244 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003245 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003246 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003247 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003248 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003249 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003250 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003251 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003252 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003253
John McCallf1860e52010-05-20 23:23:51 +00003254 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003255 }
3256 }
Mike Stump1eb44332009-09-09 15:08:12 +00003257
John McCallf1860e52010-05-20 23:23:51 +00003258 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003259 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3260 MemEnd = ClassDecl->decls_end();
3261 Mem != MemEnd; ++Mem) {
3262 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003263 // C++ [class.bit]p2:
3264 // A declaration for a bit-field that omits the identifier declares an
3265 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3266 // initialized.
3267 if (F->isUnnamedBitfield())
3268 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003269
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003270 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003271 // handle anonymous struct/union fields based on their individual
3272 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003273 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003274 continue;
3275
3276 if (CollectFieldInitializer(*this, Info, F))
3277 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003278 continue;
3279 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003280
3281 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003282 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003283 continue;
3284
3285 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3286 if (F->getType()->isIncompleteArrayType()) {
3287 assert(ClassDecl->hasFlexibleArrayMember() &&
3288 "Incomplete array type is not valid");
3289 continue;
3290 }
3291
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003292 // Initialize each field of an anonymous struct individually.
3293 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3294 HadError = true;
3295
3296 continue;
3297 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003298 }
Mike Stump1eb44332009-09-09 15:08:12 +00003299
David Blaikie93c86172013-01-17 05:26:25 +00003300 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003301 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003302 Constructor->setNumCtorInitializers(NumInitializers);
3303 CXXCtorInitializer **baseOrMemberInitializers =
3304 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003305 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003306 NumInitializers * sizeof(CXXCtorInitializer*));
3307 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003308
John McCallef027fe2010-03-16 21:39:52 +00003309 // Constructors implicitly reference the base and member
3310 // destructors.
3311 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3312 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003313 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003314
3315 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003316}
3317
David Blaikieee000bb2013-01-17 08:49:22 +00003318static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003319 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003320 const RecordDecl *RD = RT->getDecl();
3321 if (RD->isAnonymousStructOrUnion()) {
3322 for (RecordDecl::field_iterator Field = RD->field_begin(),
3323 E = RD->field_end(); Field != E; ++Field)
3324 PopulateKeysForFields(*Field, IdealInits);
3325 return;
3326 }
Eli Friedman6347f422009-07-21 19:28:10 +00003327 }
David Blaikieee000bb2013-01-17 08:49:22 +00003328 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003329}
3330
Anders Carlssonea356fb2010-04-02 05:42:15 +00003331static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003332 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003333}
3334
Anders Carlssonea356fb2010-04-02 05:42:15 +00003335static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003336 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003337 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003338 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003339
David Blaikieee000bb2013-01-17 08:49:22 +00003340 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003341}
3342
David Blaikie93c86172013-01-17 05:26:25 +00003343static void DiagnoseBaseOrMemInitializerOrder(
3344 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3345 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003346 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003347 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003348
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003349 // Don't check initializers order unless the warning is enabled at the
3350 // location of at least one initializer.
3351 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003352 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003353 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003354 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3355 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003356 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003357 ShouldCheckOrder = true;
3358 break;
3359 }
3360 }
3361 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003362 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003363
John McCalld6ca8da2010-04-10 07:37:23 +00003364 // Build the list of bases and members in the order that they'll
3365 // actually be initialized. The explicit initializers should be in
3366 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003367 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003368
Anders Carlsson071d6102010-04-02 03:38:04 +00003369 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3370
John McCalld6ca8da2010-04-10 07:37:23 +00003371 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003372 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003373 ClassDecl->vbases_begin(),
3374 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003375 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003376
John McCalld6ca8da2010-04-10 07:37:23 +00003377 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003378 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003379 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003380 if (Base->isVirtual())
3381 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003382 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003383 }
Mike Stump1eb44332009-09-09 15:08:12 +00003384
John McCalld6ca8da2010-04-10 07:37:23 +00003385 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003386 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003387 E = ClassDecl->field_end(); Field != E; ++Field) {
3388 if (Field->isUnnamedBitfield())
3389 continue;
3390
David Blaikieee000bb2013-01-17 08:49:22 +00003391 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003392 }
3393
John McCalld6ca8da2010-04-10 07:37:23 +00003394 unsigned NumIdealInits = IdealInitKeys.size();
3395 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003396
Sean Huntcbb67482011-01-08 20:30:50 +00003397 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003398 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003399 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003400 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003401
3402 // Scan forward to try to find this initializer in the idealized
3403 // initializers list.
3404 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3405 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003406 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003407
3408 // If we didn't find this initializer, it must be because we
3409 // scanned past it on a previous iteration. That can only
3410 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003411 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003412 Sema::SemaDiagnosticBuilder D =
3413 SemaRef.Diag(PrevInit->getSourceLocation(),
3414 diag::warn_initializer_out_of_order);
3415
Francois Pichet00eb3f92010-12-04 09:14:42 +00003416 if (PrevInit->isAnyMemberInitializer())
3417 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003418 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003419 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003420
Francois Pichet00eb3f92010-12-04 09:14:42 +00003421 if (Init->isAnyMemberInitializer())
3422 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003423 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003424 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003425
3426 // Move back to the initializer's location in the ideal list.
3427 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3428 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003429 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003430
3431 assert(IdealIndex != NumIdealInits &&
3432 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003433 }
John McCalld6ca8da2010-04-10 07:37:23 +00003434
3435 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003436 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003437}
3438
John McCall3c3ccdb2010-04-10 09:28:51 +00003439namespace {
3440bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003441 CXXCtorInitializer *Init,
3442 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003443 if (!PrevInit) {
3444 PrevInit = Init;
3445 return false;
3446 }
3447
Douglas Gregordc392c12013-03-25 23:28:23 +00003448 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003449 S.Diag(Init->getSourceLocation(),
3450 diag::err_multiple_mem_initialization)
3451 << Field->getDeclName()
3452 << Init->getSourceRange();
3453 else {
John McCallf4c73712011-01-19 06:33:43 +00003454 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003455 assert(BaseClass && "neither field nor base");
3456 S.Diag(Init->getSourceLocation(),
3457 diag::err_multiple_base_initialization)
3458 << QualType(BaseClass, 0)
3459 << Init->getSourceRange();
3460 }
3461 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3462 << 0 << PrevInit->getSourceRange();
3463
3464 return true;
3465}
3466
Sean Huntcbb67482011-01-08 20:30:50 +00003467typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003468typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3469
3470bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003471 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003472 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003473 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003474 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003475 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003476
3477 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003478 if (Parent->isUnion()) {
3479 UnionEntry &En = Unions[Parent];
3480 if (En.first && En.first != Child) {
3481 S.Diag(Init->getSourceLocation(),
3482 diag::err_multiple_mem_union_initialization)
3483 << Field->getDeclName()
3484 << Init->getSourceRange();
3485 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3486 << 0 << En.second->getSourceRange();
3487 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003488 }
3489 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003490 En.first = Child;
3491 En.second = Init;
3492 }
David Blaikie6fe29652011-11-17 06:01:57 +00003493 if (!Parent->isAnonymousStructOrUnion())
3494 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003495 }
3496
3497 Child = Parent;
3498 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003499 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003500
3501 return false;
3502}
3503}
3504
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003505/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003506void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003507 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003508 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003509 bool AnyErrors) {
3510 if (!ConstructorDecl)
3511 return;
3512
3513 AdjustDeclIfTemplate(ConstructorDecl);
3514
3515 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003516 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003517
3518 if (!Constructor) {
3519 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3520 return;
3521 }
3522
John McCall3c3ccdb2010-04-10 09:28:51 +00003523 // Mapping for the duplicate initializers check.
3524 // For member initializers, this is keyed with a FieldDecl*.
3525 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003526 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003527
3528 // Mapping for the inconsistent anonymous-union initializers check.
3529 RedundantUnionMap MemberUnions;
3530
Anders Carlssonea356fb2010-04-02 05:42:15 +00003531 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003532 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003533 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003534
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003535 // Set the source order index.
3536 Init->setSourceOrder(i);
3537
Francois Pichet00eb3f92010-12-04 09:14:42 +00003538 if (Init->isAnyMemberInitializer()) {
3539 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003540 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3541 CheckRedundantUnionInit(*this, Init, MemberUnions))
3542 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003543 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003544 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3545 if (CheckRedundantInit(*this, Init, Members[Key]))
3546 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003547 } else {
3548 assert(Init->isDelegatingInitializer());
3549 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003550 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003551 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003552 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003553 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003554 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003555 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003556 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003557 // Return immediately as the initializer is set.
3558 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003559 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003560 }
3561
Anders Carlssonea356fb2010-04-02 05:42:15 +00003562 if (HadError)
3563 return;
3564
David Blaikie93c86172013-01-17 05:26:25 +00003565 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003566
David Blaikie93c86172013-01-17 05:26:25 +00003567 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003568}
3569
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003570void
John McCallef027fe2010-03-16 21:39:52 +00003571Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3572 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003573 // Ignore dependent contexts. Also ignore unions, since their members never
3574 // have destructors implicitly called.
3575 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003576 return;
John McCall58e6f342010-03-16 05:22:47 +00003577
3578 // FIXME: all the access-control diagnostics are positioned on the
3579 // field/base declaration. That's probably good; that said, the
3580 // user might reasonably want to know why the destructor is being
3581 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003582
Anders Carlsson9f853df2009-11-17 04:44:12 +00003583 // Non-static data members.
3584 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3585 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003586 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003587 if (Field->isInvalidDecl())
3588 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003589
3590 // Don't destroy incomplete or zero-length arrays.
3591 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3592 continue;
3593
Anders Carlsson9f853df2009-11-17 04:44:12 +00003594 QualType FieldType = Context.getBaseElementType(Field->getType());
3595
3596 const RecordType* RT = FieldType->getAs<RecordType>();
3597 if (!RT)
3598 continue;
3599
3600 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003601 if (FieldClassDecl->isInvalidDecl())
3602 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003603 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003604 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003605 // The destructor for an implicit anonymous union member is never invoked.
3606 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3607 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003608
Douglas Gregordb89f282010-07-01 22:47:18 +00003609 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003610 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003611 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003612 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003613 << Field->getDeclName()
3614 << FieldType);
3615
Eli Friedman5f2987c2012-02-02 03:46:19 +00003616 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003617 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003618 }
3619
John McCall58e6f342010-03-16 05:22:47 +00003620 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3621
Anders Carlsson9f853df2009-11-17 04:44:12 +00003622 // Bases.
3623 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3624 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003625 // Bases are always records in a well-formed non-dependent class.
3626 const RecordType *RT = Base->getType()->getAs<RecordType>();
3627
3628 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003629 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003630 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003631
John McCall58e6f342010-03-16 05:22:47 +00003632 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003633 // If our base class is invalid, we probably can't get its dtor anyway.
3634 if (BaseClassDecl->isInvalidDecl())
3635 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003636 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003637 continue;
John McCall58e6f342010-03-16 05:22:47 +00003638
Douglas Gregordb89f282010-07-01 22:47:18 +00003639 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003640 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003641
3642 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003643 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003644 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003645 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003646 << Base->getSourceRange(),
3647 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003648
Eli Friedman5f2987c2012-02-02 03:46:19 +00003649 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003650 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003651 }
3652
3653 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003654 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3655 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003656
3657 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003658 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003659
3660 // Ignore direct virtual bases.
3661 if (DirectVirtualBases.count(RT))
3662 continue;
3663
John McCall58e6f342010-03-16 05:22:47 +00003664 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003665 // If our base class is invalid, we probably can't get its dtor anyway.
3666 if (BaseClassDecl->isInvalidDecl())
3667 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003668 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003669 continue;
John McCall58e6f342010-03-16 05:22:47 +00003670
Douglas Gregordb89f282010-07-01 22:47:18 +00003671 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003672 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003673 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003674 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003675 << VBase->getType(),
3676 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003677
Eli Friedman5f2987c2012-02-02 03:46:19 +00003678 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003679 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003680 }
3681}
3682
John McCalld226f652010-08-21 09:40:31 +00003683void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003684 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003685 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003686
Mike Stump1eb44332009-09-09 15:08:12 +00003687 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003688 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003689 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003690}
3691
Mike Stump1eb44332009-09-09 15:08:12 +00003692bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003693 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003694 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3695 unsigned DiagID;
3696 AbstractDiagSelID SelID;
3697
3698 public:
3699 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3700 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3701
3702 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003703 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003704 if (SelID == -1)
3705 S.Diag(Loc, DiagID) << T;
3706 else
3707 S.Diag(Loc, DiagID) << SelID << T;
3708 }
3709 } Diagnoser(DiagID, SelID);
3710
3711 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003712}
3713
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003714bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003715 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003716 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003717 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003718
Anders Carlsson11f21a02009-03-23 19:10:31 +00003719 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003720 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003721
Ted Kremenek6217b802009-07-29 21:53:49 +00003722 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003723 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003724 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003725 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003726
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003727 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003728 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003729 }
Mike Stump1eb44332009-09-09 15:08:12 +00003730
Ted Kremenek6217b802009-07-29 21:53:49 +00003731 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003732 if (!RT)
3733 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003734
John McCall86ff3082010-02-04 22:26:26 +00003735 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003736
John McCall94c3b562010-08-18 09:41:07 +00003737 // We can't answer whether something is abstract until it has a
3738 // definition. If it's currently being defined, we'll walk back
3739 // over all the declarations when we have a full definition.
3740 const CXXRecordDecl *Def = RD->getDefinition();
3741 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003742 return false;
3743
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003744 if (!RD->isAbstract())
3745 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003746
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003747 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003748 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003749
John McCall94c3b562010-08-18 09:41:07 +00003750 return true;
3751}
3752
3753void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3754 // Check if we've already emitted the list of pure virtual functions
3755 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003756 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003757 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003758
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003759 CXXFinalOverriderMap FinalOverriders;
3760 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003761
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003762 // Keep a set of seen pure methods so we won't diagnose the same method
3763 // more than once.
3764 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3765
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003766 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3767 MEnd = FinalOverriders.end();
3768 M != MEnd;
3769 ++M) {
3770 for (OverridingMethods::iterator SO = M->second.begin(),
3771 SOEnd = M->second.end();
3772 SO != SOEnd; ++SO) {
3773 // C++ [class.abstract]p4:
3774 // A class is abstract if it contains or inherits at least one
3775 // pure virtual function for which the final overrider is pure
3776 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003777
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003778 //
3779 if (SO->second.size() != 1)
3780 continue;
3781
3782 if (!SO->second.front().Method->isPure())
3783 continue;
3784
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003785 if (!SeenPureMethods.insert(SO->second.front().Method))
3786 continue;
3787
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003788 Diag(SO->second.front().Method->getLocation(),
3789 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003790 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003791 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003792 }
3793
3794 if (!PureVirtualClassDiagSet)
3795 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3796 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003797}
3798
Anders Carlsson8211eff2009-03-24 01:19:16 +00003799namespace {
John McCall94c3b562010-08-18 09:41:07 +00003800struct AbstractUsageInfo {
3801 Sema &S;
3802 CXXRecordDecl *Record;
3803 CanQualType AbstractType;
3804 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003805
John McCall94c3b562010-08-18 09:41:07 +00003806 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3807 : S(S), Record(Record),
3808 AbstractType(S.Context.getCanonicalType(
3809 S.Context.getTypeDeclType(Record))),
3810 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003811
John McCall94c3b562010-08-18 09:41:07 +00003812 void DiagnoseAbstractType() {
3813 if (Invalid) return;
3814 S.DiagnoseAbstractType(Record);
3815 Invalid = true;
3816 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003817
John McCall94c3b562010-08-18 09:41:07 +00003818 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3819};
3820
3821struct CheckAbstractUsage {
3822 AbstractUsageInfo &Info;
3823 const NamedDecl *Ctx;
3824
3825 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3826 : Info(Info), Ctx(Ctx) {}
3827
3828 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3829 switch (TL.getTypeLocClass()) {
3830#define ABSTRACT_TYPELOC(CLASS, PARENT)
3831#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003832 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003833#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003834 }
John McCall94c3b562010-08-18 09:41:07 +00003835 }
Mike Stump1eb44332009-09-09 15:08:12 +00003836
John McCall94c3b562010-08-18 09:41:07 +00003837 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3838 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3839 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003840 if (!TL.getArg(I))
3841 continue;
3842
John McCall94c3b562010-08-18 09:41:07 +00003843 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3844 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003845 }
John McCall94c3b562010-08-18 09:41:07 +00003846 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003847
John McCall94c3b562010-08-18 09:41:07 +00003848 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3849 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3850 }
Mike Stump1eb44332009-09-09 15:08:12 +00003851
John McCall94c3b562010-08-18 09:41:07 +00003852 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3853 // Visit the type parameters from a permissive context.
3854 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3855 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3856 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3857 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3858 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3859 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003860 }
John McCall94c3b562010-08-18 09:41:07 +00003861 }
Mike Stump1eb44332009-09-09 15:08:12 +00003862
John McCall94c3b562010-08-18 09:41:07 +00003863 // Visit pointee types from a permissive context.
3864#define CheckPolymorphic(Type) \
3865 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3866 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3867 }
3868 CheckPolymorphic(PointerTypeLoc)
3869 CheckPolymorphic(ReferenceTypeLoc)
3870 CheckPolymorphic(MemberPointerTypeLoc)
3871 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003872 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003873
John McCall94c3b562010-08-18 09:41:07 +00003874 /// Handle all the types we haven't given a more specific
3875 /// implementation for above.
3876 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3877 // Every other kind of type that we haven't called out already
3878 // that has an inner type is either (1) sugar or (2) contains that
3879 // inner type in some way as a subobject.
3880 if (TypeLoc Next = TL.getNextTypeLoc())
3881 return Visit(Next, Sel);
3882
3883 // If there's no inner type and we're in a permissive context,
3884 // don't diagnose.
3885 if (Sel == Sema::AbstractNone) return;
3886
3887 // Check whether the type matches the abstract type.
3888 QualType T = TL.getType();
3889 if (T->isArrayType()) {
3890 Sel = Sema::AbstractArrayType;
3891 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003892 }
John McCall94c3b562010-08-18 09:41:07 +00003893 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3894 if (CT != Info.AbstractType) return;
3895
3896 // It matched; do some magic.
3897 if (Sel == Sema::AbstractArrayType) {
3898 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3899 << T << TL.getSourceRange();
3900 } else {
3901 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3902 << Sel << T << TL.getSourceRange();
3903 }
3904 Info.DiagnoseAbstractType();
3905 }
3906};
3907
3908void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3909 Sema::AbstractDiagSelID Sel) {
3910 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3911}
3912
3913}
3914
3915/// Check for invalid uses of an abstract type in a method declaration.
3916static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3917 CXXMethodDecl *MD) {
3918 // No need to do the check on definitions, which require that
3919 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003920 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003921 return;
3922
3923 // For safety's sake, just ignore it if we don't have type source
3924 // information. This should never happen for non-implicit methods,
3925 // but...
3926 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3927 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3928}
3929
3930/// Check for invalid uses of an abstract type within a class definition.
3931static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3932 CXXRecordDecl *RD) {
3933 for (CXXRecordDecl::decl_iterator
3934 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3935 Decl *D = *I;
3936 if (D->isImplicit()) continue;
3937
3938 // Methods and method templates.
3939 if (isa<CXXMethodDecl>(D)) {
3940 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3941 } else if (isa<FunctionTemplateDecl>(D)) {
3942 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3943 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3944
3945 // Fields and static variables.
3946 } else if (isa<FieldDecl>(D)) {
3947 FieldDecl *FD = cast<FieldDecl>(D);
3948 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3949 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3950 } else if (isa<VarDecl>(D)) {
3951 VarDecl *VD = cast<VarDecl>(D);
3952 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3953 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3954
3955 // Nested classes and class templates.
3956 } else if (isa<CXXRecordDecl>(D)) {
3957 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3958 } else if (isa<ClassTemplateDecl>(D)) {
3959 CheckAbstractClassUsage(Info,
3960 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3961 }
3962 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003963}
3964
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003965/// \brief Perform semantic checks on a class definition that has been
3966/// completing, introducing implicitly-declared members, checking for
3967/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003968void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003969 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003970 return;
3971
John McCall94c3b562010-08-18 09:41:07 +00003972 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3973 AbstractUsageInfo Info(*this, Record);
3974 CheckAbstractClassUsage(Info, Record);
3975 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003976
3977 // If this is not an aggregate type and has no user-declared constructor,
3978 // complain about any non-static data members of reference or const scalar
3979 // type, since they will never get initializers.
3980 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003981 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3982 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003983 bool Complained = false;
3984 for (RecordDecl::field_iterator F = Record->field_begin(),
3985 FEnd = Record->field_end();
3986 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003987 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003988 continue;
3989
Douglas Gregor325e5932010-04-15 00:00:53 +00003990 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003991 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003992 if (!Complained) {
3993 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3994 << Record->getTagKind() << Record;
3995 Complained = true;
3996 }
3997
3998 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3999 << F->getType()->isReferenceType()
4000 << F->getDeclName();
4001 }
4002 }
4003 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004004
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004005 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004006 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004007
4008 if (Record->getIdentifier()) {
4009 // C++ [class.mem]p13:
4010 // If T is the name of a class, then each of the following shall have a
4011 // name different from T:
4012 // - every member of every anonymous union that is a member of class T.
4013 //
4014 // C++ [class.mem]p14:
4015 // In addition, if class T has a user-declared constructor (12.1), every
4016 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004017 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4018 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4019 ++I) {
4020 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004021 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4022 isa<IndirectFieldDecl>(D)) {
4023 Diag(D->getLocation(), diag::err_member_name_of_class)
4024 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004025 break;
4026 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004027 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004028 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004029
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004030 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004031 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004032 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004033 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004034 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4035 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4036 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004037
David Blaikieb6b5b972012-09-21 03:21:07 +00004038 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4039 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4040 DiagnoseAbstractType(Record);
4041 }
4042
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004043 if (!Record->isDependentType()) {
4044 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4045 MEnd = Record->method_end();
4046 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004047 // See if a method overloads virtual methods in a base
4048 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004049 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004050 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004051
4052 // Check whether the explicitly-defaulted special members are valid.
4053 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4054 CheckExplicitlyDefaultedSpecialMember(*M);
4055
4056 // For an explicitly defaulted or deleted special member, we defer
4057 // determining triviality until the class is complete. That time is now!
4058 if (!M->isImplicit() && !M->isUserProvided()) {
4059 CXXSpecialMember CSM = getSpecialMember(*M);
4060 if (CSM != CXXInvalid) {
4061 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4062
4063 // Inform the class that we've finished declaring this member.
4064 Record->finishedDefaultedOrDeletedMember(*M);
4065 }
4066 }
4067 }
4068 }
4069
4070 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4071 // function that is not a constructor declares that member function to be
4072 // const. [...] The class of which that function is a member shall be
4073 // a literal type.
4074 //
4075 // If the class has virtual bases, any constexpr members will already have
4076 // been diagnosed by the checks performed on the member declaration, so
4077 // suppress this (less useful) diagnostic.
4078 //
4079 // We delay this until we know whether an explicitly-defaulted (or deleted)
4080 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004081 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004082 !Record->isLiteral() && !Record->getNumVBases()) {
4083 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4084 MEnd = Record->method_end();
4085 M != MEnd; ++M) {
4086 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4087 switch (Record->getTemplateSpecializationKind()) {
4088 case TSK_ImplicitInstantiation:
4089 case TSK_ExplicitInstantiationDeclaration:
4090 case TSK_ExplicitInstantiationDefinition:
4091 // If a template instantiates to a non-literal type, but its members
4092 // instantiate to constexpr functions, the template is technically
4093 // ill-formed, but we allow it for sanity.
4094 continue;
4095
4096 case TSK_Undeclared:
4097 case TSK_ExplicitSpecialization:
4098 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4099 diag::err_constexpr_method_non_literal);
4100 break;
4101 }
4102
4103 // Only produce one error per class.
4104 break;
4105 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004106 }
4107 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004108
Richard Smith07b0fdc2013-03-18 21:12:30 +00004109 // Declare inheriting constructors. We do this eagerly here because:
4110 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004111 // constructors from different classes.
4112 // - The lazy declaration of the other implicit constructors is so as to not
4113 // waste space and performance on classes that are not meant to be
4114 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004115 // have inheriting constructors.
4116 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004117}
4118
Richard Smith7756afa2012-06-10 05:43:50 +00004119/// Is the special member function which would be selected to perform the
4120/// specified operation on the specified class type a constexpr constructor?
4121static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4122 Sema::CXXSpecialMember CSM,
4123 bool ConstArg) {
4124 Sema::SpecialMemberOverloadResult *SMOR =
4125 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4126 false, false, false, false);
4127 if (!SMOR || !SMOR->getMethod())
4128 // A constructor we wouldn't select can't be "involved in initializing"
4129 // anything.
4130 return true;
4131 return SMOR->getMethod()->isConstexpr();
4132}
4133
4134/// Determine whether the specified special member function would be constexpr
4135/// if it were implicitly defined.
4136static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4137 Sema::CXXSpecialMember CSM,
4138 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004139 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004140 return false;
4141
4142 // C++11 [dcl.constexpr]p4:
4143 // In the definition of a constexpr constructor [...]
4144 switch (CSM) {
4145 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004146 // Since default constructor lookup is essentially trivial (and cannot
4147 // involve, for instance, template instantiation), we compute whether a
4148 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4149 //
4150 // This is important for performance; we need to know whether the default
4151 // constructor is constexpr to determine whether the type is a literal type.
4152 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4153
Richard Smith7756afa2012-06-10 05:43:50 +00004154 case Sema::CXXCopyConstructor:
4155 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004156 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004157 break;
4158
4159 case Sema::CXXCopyAssignment:
4160 case Sema::CXXMoveAssignment:
4161 case Sema::CXXDestructor:
4162 case Sema::CXXInvalid:
4163 return false;
4164 }
4165
4166 // -- if the class is a non-empty union, or for each non-empty anonymous
4167 // union member of a non-union class, exactly one non-static data member
4168 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004169 //
4170 // If we squint, this is guaranteed, since exactly one non-static data member
4171 // will be initialized (if the constructor isn't deleted), we just don't know
4172 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004173 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004174 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004175
4176 // -- the class shall not have any virtual base classes;
4177 if (ClassDecl->getNumVBases())
4178 return false;
4179
4180 // -- every constructor involved in initializing [...] base class
4181 // sub-objects shall be a constexpr constructor;
4182 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4183 BEnd = ClassDecl->bases_end();
4184 B != BEnd; ++B) {
4185 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4186 if (!BaseType) continue;
4187
4188 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4189 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4190 return false;
4191 }
4192
4193 // -- every constructor involved in initializing non-static data members
4194 // [...] shall be a constexpr constructor;
4195 // -- every non-static data member and base class sub-object shall be
4196 // initialized
4197 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4198 FEnd = ClassDecl->field_end();
4199 F != FEnd; ++F) {
4200 if (F->isInvalidDecl())
4201 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004202 if (const RecordType *RecordTy =
4203 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004204 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4205 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4206 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004207 }
4208 }
4209
4210 // All OK, it's constexpr!
4211 return true;
4212}
4213
Richard Smithb9d0b762012-07-27 04:22:15 +00004214static Sema::ImplicitExceptionSpecification
4215computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4216 switch (S.getSpecialMember(MD)) {
4217 case Sema::CXXDefaultConstructor:
4218 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4219 case Sema::CXXCopyConstructor:
4220 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4221 case Sema::CXXCopyAssignment:
4222 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4223 case Sema::CXXMoveConstructor:
4224 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4225 case Sema::CXXMoveAssignment:
4226 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4227 case Sema::CXXDestructor:
4228 return S.ComputeDefaultedDtorExceptionSpec(MD);
4229 case Sema::CXXInvalid:
4230 break;
4231 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004232 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4233 "only special members have implicit exception specs");
4234 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004235}
4236
Richard Smithdd25e802012-07-30 23:48:14 +00004237static void
4238updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4239 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4240 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4241 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004242 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4243 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004244}
4245
Richard Smithb9d0b762012-07-27 04:22:15 +00004246void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4247 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4248 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4249 return;
4250
Richard Smithdd25e802012-07-30 23:48:14 +00004251 // Evaluate the exception specification.
4252 ImplicitExceptionSpecification ExceptSpec =
4253 computeImplicitExceptionSpec(*this, Loc, MD);
4254
4255 // Update the type of the special member to use it.
4256 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4257
4258 // A user-provided destructor can be defined outside the class. When that
4259 // happens, be sure to update the exception specification on both
4260 // declarations.
4261 const FunctionProtoType *CanonicalFPT =
4262 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4263 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4264 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4265 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004266}
4267
Richard Smith3003e1d2012-05-15 04:39:51 +00004268void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4269 CXXRecordDecl *RD = MD->getParent();
4270 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004271
Richard Smith3003e1d2012-05-15 04:39:51 +00004272 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4273 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004274
4275 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004276 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004277 bool First = MD == MD->getCanonicalDecl();
4278
4279 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004280
4281 // C++11 [dcl.fct.def.default]p1:
4282 // A function that is explicitly defaulted shall
4283 // -- be a special member function (checked elsewhere),
4284 // -- have the same type (except for ref-qualifiers, and except that a
4285 // copy operation can take a non-const reference) as an implicit
4286 // declaration, and
4287 // -- not have default arguments.
4288 unsigned ExpectedParams = 1;
4289 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4290 ExpectedParams = 0;
4291 if (MD->getNumParams() != ExpectedParams) {
4292 // This also checks for default arguments: a copy or move constructor with a
4293 // default argument is classified as a default constructor, and assignment
4294 // operations and destructors can't have default arguments.
4295 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4296 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004297 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004298 } else if (MD->isVariadic()) {
4299 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4300 << CSM << MD->getSourceRange();
4301 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004302 }
4303
Richard Smith3003e1d2012-05-15 04:39:51 +00004304 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004305
Richard Smith7756afa2012-06-10 05:43:50 +00004306 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004307 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004308 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004309 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004310 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004311
Richard Smith3003e1d2012-05-15 04:39:51 +00004312 QualType ReturnType = Context.VoidTy;
4313 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4314 // Check for return type matching.
4315 ReturnType = Type->getResultType();
4316 QualType ExpectedReturnType =
4317 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4318 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4319 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4320 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4321 HadError = true;
4322 }
4323
4324 // A defaulted special member cannot have cv-qualifiers.
4325 if (Type->getTypeQuals()) {
4326 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4327 << (CSM == CXXMoveAssignment);
4328 HadError = true;
4329 }
4330 }
4331
4332 // Check for parameter type matching.
4333 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004334 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004335 if (ExpectedParams && ArgType->isReferenceType()) {
4336 // Argument must be reference to possibly-const T.
4337 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004338 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004339
4340 if (ReferentType.isVolatileQualified()) {
4341 Diag(MD->getLocation(),
4342 diag::err_defaulted_special_member_volatile_param) << CSM;
4343 HadError = true;
4344 }
4345
Richard Smith7756afa2012-06-10 05:43:50 +00004346 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004347 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4348 Diag(MD->getLocation(),
4349 diag::err_defaulted_special_member_copy_const_param)
4350 << (CSM == CXXCopyAssignment);
4351 // FIXME: Explain why this special member can't be const.
4352 } else {
4353 Diag(MD->getLocation(),
4354 diag::err_defaulted_special_member_move_const_param)
4355 << (CSM == CXXMoveAssignment);
4356 }
4357 HadError = true;
4358 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004359 } else if (ExpectedParams) {
4360 // A copy assignment operator can take its argument by value, but a
4361 // defaulted one cannot.
4362 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004363 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004364 HadError = true;
4365 }
Sean Huntbe631222011-05-17 20:44:43 +00004366
Richard Smith61802452011-12-22 02:22:31 +00004367 // C++11 [dcl.fct.def.default]p2:
4368 // An explicitly-defaulted function may be declared constexpr only if it
4369 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004370 // Do not apply this rule to members of class templates, since core issue 1358
4371 // makes such functions always instantiate to constexpr functions. For
4372 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004373 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4374 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004375 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4376 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4377 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004378 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004379 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004380 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004381
Richard Smith61802452011-12-22 02:22:31 +00004382 // and may have an explicit exception-specification only if it is compatible
4383 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004384 if (Type->hasExceptionSpec()) {
4385 // Delay the check if this is the first declaration of the special member,
4386 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004387 if (First) {
4388 // If the exception specification needs to be instantiated, do so now,
4389 // before we clobber it with an EST_Unevaluated specification below.
4390 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4391 InstantiateExceptionSpec(MD->getLocStart(), MD);
4392 Type = MD->getType()->getAs<FunctionProtoType>();
4393 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004394 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004395 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004396 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4397 }
Richard Smith61802452011-12-22 02:22:31 +00004398
4399 // If a function is explicitly defaulted on its first declaration,
4400 if (First) {
4401 // -- it is implicitly considered to be constexpr if the implicit
4402 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004403 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004404
Richard Smith3003e1d2012-05-15 04:39:51 +00004405 // -- it is implicitly considered to have the same exception-specification
4406 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004407 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4408 EPI.ExceptionSpecType = EST_Unevaluated;
4409 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004410 MD->setType(Context.getFunctionType(ReturnType,
4411 ArrayRef<QualType>(&ArgType,
4412 ExpectedParams),
4413 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004414 }
4415
Richard Smith3003e1d2012-05-15 04:39:51 +00004416 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004417 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004418 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004419 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004420 // C++11 [dcl.fct.def.default]p4:
4421 // [For a] user-provided explicitly-defaulted function [...] if such a
4422 // function is implicitly defined as deleted, the program is ill-formed.
4423 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4424 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004425 }
4426 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004427
Richard Smith3003e1d2012-05-15 04:39:51 +00004428 if (HadError)
4429 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004430}
4431
Richard Smith1d28caf2012-12-11 01:14:52 +00004432/// Check whether the exception specification provided for an
4433/// explicitly-defaulted special member matches the exception specification
4434/// that would have been generated for an implicit special member, per
4435/// C++11 [dcl.fct.def.default]p2.
4436void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4437 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4438 // Compute the implicit exception specification.
4439 FunctionProtoType::ExtProtoInfo EPI;
4440 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4441 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Jordan Rosebea522f2013-03-08 21:51:21 +00004442 Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004443
4444 // Ensure that it matches.
4445 CheckEquivalentExceptionSpec(
4446 PDiag(diag::err_incorrect_defaulted_exception_spec)
4447 << getSpecialMember(MD), PDiag(),
4448 ImplicitType, SourceLocation(),
4449 SpecifiedType, MD->getLocation());
4450}
4451
4452void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4453 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4454 I != N; ++I)
4455 CheckExplicitlyDefaultedMemberExceptionSpec(
4456 DelayedDefaultedMemberExceptionSpecs[I].first,
4457 DelayedDefaultedMemberExceptionSpecs[I].second);
4458
4459 DelayedDefaultedMemberExceptionSpecs.clear();
4460}
4461
Richard Smith7d5088a2012-02-18 02:02:13 +00004462namespace {
4463struct SpecialMemberDeletionInfo {
4464 Sema &S;
4465 CXXMethodDecl *MD;
4466 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004467 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004468
4469 // Properties of the special member, computed for convenience.
4470 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4471 SourceLocation Loc;
4472
4473 bool AllFieldsAreConst;
4474
4475 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004476 Sema::CXXSpecialMember CSM, bool Diagnose)
4477 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004478 IsConstructor(false), IsAssignment(false), IsMove(false),
4479 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4480 AllFieldsAreConst(true) {
4481 switch (CSM) {
4482 case Sema::CXXDefaultConstructor:
4483 case Sema::CXXCopyConstructor:
4484 IsConstructor = true;
4485 break;
4486 case Sema::CXXMoveConstructor:
4487 IsConstructor = true;
4488 IsMove = true;
4489 break;
4490 case Sema::CXXCopyAssignment:
4491 IsAssignment = true;
4492 break;
4493 case Sema::CXXMoveAssignment:
4494 IsAssignment = true;
4495 IsMove = true;
4496 break;
4497 case Sema::CXXDestructor:
4498 break;
4499 case Sema::CXXInvalid:
4500 llvm_unreachable("invalid special member kind");
4501 }
4502
4503 if (MD->getNumParams()) {
4504 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4505 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4506 }
4507 }
4508
4509 bool inUnion() const { return MD->getParent()->isUnion(); }
4510
4511 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004512 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4513 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004514 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004515 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4516 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4517 Quals = 0;
4518 return S.LookupSpecialMember(Class, CSM,
4519 ConstArg || (Quals & Qualifiers::Const),
4520 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004521 MD->getRefQualifier() == RQ_RValue,
4522 TQ & Qualifiers::Const,
4523 TQ & Qualifiers::Volatile);
4524 }
4525
Richard Smith6c4c36c2012-03-30 20:53:28 +00004526 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004527
Richard Smith6c4c36c2012-03-30 20:53:28 +00004528 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004529 bool shouldDeleteForField(FieldDecl *FD);
4530 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004531
Richard Smith517bb842012-07-18 03:51:16 +00004532 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4533 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004534 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4535 Sema::SpecialMemberOverloadResult *SMOR,
4536 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004537
4538 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004539};
4540}
4541
John McCall12d8d802012-04-09 20:53:23 +00004542/// Is the given special member inaccessible when used on the given
4543/// sub-object.
4544bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4545 CXXMethodDecl *target) {
4546 /// If we're operating on a base class, the object type is the
4547 /// type of this special member.
4548 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004549 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004550 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4551 objectTy = S.Context.getTypeDeclType(MD->getParent());
4552 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4553
4554 // If we're operating on a field, the object type is the type of the field.
4555 } else {
4556 objectTy = S.Context.getTypeDeclType(target->getParent());
4557 }
4558
4559 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4560}
4561
Richard Smith6c4c36c2012-03-30 20:53:28 +00004562/// Check whether we should delete a special member due to the implicit
4563/// definition containing a call to a special member of a subobject.
4564bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4565 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4566 bool IsDtorCallInCtor) {
4567 CXXMethodDecl *Decl = SMOR->getMethod();
4568 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4569
4570 int DiagKind = -1;
4571
4572 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4573 DiagKind = !Decl ? 0 : 1;
4574 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4575 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004576 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004577 DiagKind = 3;
4578 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4579 !Decl->isTrivial()) {
4580 // A member of a union must have a trivial corresponding special member.
4581 // As a weird special case, a destructor call from a union's constructor
4582 // must be accessible and non-deleted, but need not be trivial. Such a
4583 // destructor is never actually called, but is semantically checked as
4584 // if it were.
4585 DiagKind = 4;
4586 }
4587
4588 if (DiagKind == -1)
4589 return false;
4590
4591 if (Diagnose) {
4592 if (Field) {
4593 S.Diag(Field->getLocation(),
4594 diag::note_deleted_special_member_class_subobject)
4595 << CSM << MD->getParent() << /*IsField*/true
4596 << Field << DiagKind << IsDtorCallInCtor;
4597 } else {
4598 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4599 S.Diag(Base->getLocStart(),
4600 diag::note_deleted_special_member_class_subobject)
4601 << CSM << MD->getParent() << /*IsField*/false
4602 << Base->getType() << DiagKind << IsDtorCallInCtor;
4603 }
4604
4605 if (DiagKind == 1)
4606 S.NoteDeletedFunction(Decl);
4607 // FIXME: Explain inaccessibility if DiagKind == 3.
4608 }
4609
4610 return true;
4611}
4612
Richard Smith9a561d52012-02-26 09:11:52 +00004613/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004614/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004615bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004616 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004617 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004618
4619 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004620 // -- any direct or virtual base class, or non-static data member with no
4621 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004622 // either M has no default constructor or overload resolution as applied
4623 // to M's default constructor results in an ambiguity or in a function
4624 // that is deleted or inaccessible
4625 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4626 // -- a direct or virtual base class B that cannot be copied/moved because
4627 // overload resolution, as applied to B's corresponding special member,
4628 // results in an ambiguity or a function that is deleted or inaccessible
4629 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004630 // C++11 [class.dtor]p5:
4631 // -- any direct or virtual base class [...] has a type with a destructor
4632 // that is deleted or inaccessible
4633 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004634 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004635 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004636 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004637
Richard Smith6c4c36c2012-03-30 20:53:28 +00004638 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4639 // -- any direct or virtual base class or non-static data member has a
4640 // type with a destructor that is deleted or inaccessible
4641 if (IsConstructor) {
4642 Sema::SpecialMemberOverloadResult *SMOR =
4643 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4644 false, false, false, false, false);
4645 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4646 return true;
4647 }
4648
Richard Smith9a561d52012-02-26 09:11:52 +00004649 return false;
4650}
4651
4652/// Check whether we should delete a special member function due to the class
4653/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004654bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004655 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004656 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004657}
4658
4659/// Check whether we should delete a special member function due to the class
4660/// having a particular non-static data member.
4661bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4662 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4663 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4664
4665 if (CSM == Sema::CXXDefaultConstructor) {
4666 // For a default constructor, all references must be initialized in-class
4667 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004668 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4669 if (Diagnose)
4670 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4671 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004672 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004673 }
Richard Smith79363f52012-02-27 06:07:25 +00004674 // C++11 [class.ctor]p5: any non-variant non-static data member of
4675 // const-qualified type (or array thereof) with no
4676 // brace-or-equal-initializer does not have a user-provided default
4677 // constructor.
4678 if (!inUnion() && FieldType.isConstQualified() &&
4679 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004680 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4681 if (Diagnose)
4682 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004683 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004684 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004685 }
4686
4687 if (inUnion() && !FieldType.isConstQualified())
4688 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004689 } else if (CSM == Sema::CXXCopyConstructor) {
4690 // For a copy constructor, data members must not be of rvalue reference
4691 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004692 if (FieldType->isRValueReferenceType()) {
4693 if (Diagnose)
4694 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4695 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004696 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004697 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004698 } else if (IsAssignment) {
4699 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004700 if (FieldType->isReferenceType()) {
4701 if (Diagnose)
4702 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4703 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004704 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004705 }
4706 if (!FieldRecord && FieldType.isConstQualified()) {
4707 // C++11 [class.copy]p23:
4708 // -- a non-static data member of const non-class type (or array thereof)
4709 if (Diagnose)
4710 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004711 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004712 return true;
4713 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004714 }
4715
4716 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004717 // Some additional restrictions exist on the variant members.
4718 if (!inUnion() && FieldRecord->isUnion() &&
4719 FieldRecord->isAnonymousStructOrUnion()) {
4720 bool AllVariantFieldsAreConst = true;
4721
Richard Smithdf8dc862012-03-29 19:00:10 +00004722 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004723 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4724 UE = FieldRecord->field_end();
4725 UI != UE; ++UI) {
4726 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004727
4728 if (!UnionFieldType.isConstQualified())
4729 AllVariantFieldsAreConst = false;
4730
Richard Smith9a561d52012-02-26 09:11:52 +00004731 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4732 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004733 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4734 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004735 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004736 }
4737
4738 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004739 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004740 FieldRecord->field_begin() != FieldRecord->field_end()) {
4741 if (Diagnose)
4742 S.Diag(FieldRecord->getLocation(),
4743 diag::note_deleted_default_ctor_all_const)
4744 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004745 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004746 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004747
Richard Smithdf8dc862012-03-29 19:00:10 +00004748 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004749 // This is technically non-conformant, but sanity demands it.
4750 return false;
4751 }
4752
Richard Smith517bb842012-07-18 03:51:16 +00004753 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4754 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004755 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004756 }
4757
4758 return false;
4759}
4760
4761/// C++11 [class.ctor] p5:
4762/// A defaulted default constructor for a class X is defined as deleted if
4763/// X is a union and all of its variant members are of const-qualified type.
4764bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004765 // This is a silly definition, because it gives an empty union a deleted
4766 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004767 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4768 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4769 if (Diagnose)
4770 S.Diag(MD->getParent()->getLocation(),
4771 diag::note_deleted_default_ctor_all_const)
4772 << MD->getParent() << /*not anonymous union*/0;
4773 return true;
4774 }
4775 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004776}
4777
4778/// Determine whether a defaulted special member function should be defined as
4779/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4780/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004781bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4782 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004783 if (MD->isInvalidDecl())
4784 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004785 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004786 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004787 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004788 return false;
4789
Richard Smith7d5088a2012-02-18 02:02:13 +00004790 // C++11 [expr.lambda.prim]p19:
4791 // The closure type associated with a lambda-expression has a
4792 // deleted (8.4.3) default constructor and a deleted copy
4793 // assignment operator.
4794 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004795 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4796 if (Diagnose)
4797 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004798 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004799 }
4800
Richard Smith5bdaac52012-04-02 20:59:25 +00004801 // For an anonymous struct or union, the copy and assignment special members
4802 // will never be used, so skip the check. For an anonymous union declared at
4803 // namespace scope, the constructor and destructor are used.
4804 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4805 RD->isAnonymousStructOrUnion())
4806 return false;
4807
Richard Smith6c4c36c2012-03-30 20:53:28 +00004808 // C++11 [class.copy]p7, p18:
4809 // If the class definition declares a move constructor or move assignment
4810 // operator, an implicitly declared copy constructor or copy assignment
4811 // operator is defined as deleted.
4812 if (MD->isImplicit() &&
4813 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4814 CXXMethodDecl *UserDeclaredMove = 0;
4815
4816 // In Microsoft mode, a user-declared move only causes the deletion of the
4817 // corresponding copy operation, not both copy operations.
4818 if (RD->hasUserDeclaredMoveConstructor() &&
4819 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4820 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004821
4822 // Find any user-declared move constructor.
4823 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4824 E = RD->ctor_end(); I != E; ++I) {
4825 if (I->isMoveConstructor()) {
4826 UserDeclaredMove = *I;
4827 break;
4828 }
4829 }
Richard Smith1c931be2012-04-02 18:40:40 +00004830 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004831 } else if (RD->hasUserDeclaredMoveAssignment() &&
4832 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4833 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004834
4835 // Find any user-declared move assignment operator.
4836 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4837 E = RD->method_end(); I != E; ++I) {
4838 if (I->isMoveAssignmentOperator()) {
4839 UserDeclaredMove = *I;
4840 break;
4841 }
4842 }
Richard Smith1c931be2012-04-02 18:40:40 +00004843 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004844 }
4845
4846 if (UserDeclaredMove) {
4847 Diag(UserDeclaredMove->getLocation(),
4848 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004849 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004850 << UserDeclaredMove->isMoveAssignmentOperator();
4851 return true;
4852 }
4853 }
Sean Hunte16da072011-10-10 06:18:57 +00004854
Richard Smith5bdaac52012-04-02 20:59:25 +00004855 // Do access control from the special member function
4856 ContextRAII MethodContext(*this, MD);
4857
Richard Smith9a561d52012-02-26 09:11:52 +00004858 // C++11 [class.dtor]p5:
4859 // -- for a virtual destructor, lookup of the non-array deallocation function
4860 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004861 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004862 FunctionDecl *OperatorDelete = 0;
4863 DeclarationName Name =
4864 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4865 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004866 OperatorDelete, false)) {
4867 if (Diagnose)
4868 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004869 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004870 }
Richard Smith9a561d52012-02-26 09:11:52 +00004871 }
4872
Richard Smith6c4c36c2012-03-30 20:53:28 +00004873 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004874
Sean Huntcdee3fe2011-05-11 22:34:38 +00004875 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004876 BE = RD->bases_end(); BI != BE; ++BI)
4877 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004878 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004879 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004880
4881 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004882 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004883 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004884 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004885
4886 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004887 FE = RD->field_end(); FI != FE; ++FI)
4888 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004889 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004890 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004891
Richard Smith7d5088a2012-02-18 02:02:13 +00004892 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004893 return true;
4894
4895 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004896}
4897
Richard Smithac713512012-12-08 02:53:02 +00004898/// Perform lookup for a special member of the specified kind, and determine
4899/// whether it is trivial. If the triviality can be determined without the
4900/// lookup, skip it. This is intended for use when determining whether a
4901/// special member of a containing object is trivial, and thus does not ever
4902/// perform overload resolution for default constructors.
4903///
4904/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4905/// member that was most likely to be intended to be trivial, if any.
4906static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4907 Sema::CXXSpecialMember CSM, unsigned Quals,
4908 CXXMethodDecl **Selected) {
4909 if (Selected)
4910 *Selected = 0;
4911
4912 switch (CSM) {
4913 case Sema::CXXInvalid:
4914 llvm_unreachable("not a special member");
4915
4916 case Sema::CXXDefaultConstructor:
4917 // C++11 [class.ctor]p5:
4918 // A default constructor is trivial if:
4919 // - all the [direct subobjects] have trivial default constructors
4920 //
4921 // Note, no overload resolution is performed in this case.
4922 if (RD->hasTrivialDefaultConstructor())
4923 return true;
4924
4925 if (Selected) {
4926 // If there's a default constructor which could have been trivial, dig it
4927 // out. Otherwise, if there's any user-provided default constructor, point
4928 // to that as an example of why there's not a trivial one.
4929 CXXConstructorDecl *DefCtor = 0;
4930 if (RD->needsImplicitDefaultConstructor())
4931 S.DeclareImplicitDefaultConstructor(RD);
4932 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4933 CE = RD->ctor_end(); CI != CE; ++CI) {
4934 if (!CI->isDefaultConstructor())
4935 continue;
4936 DefCtor = *CI;
4937 if (!DefCtor->isUserProvided())
4938 break;
4939 }
4940
4941 *Selected = DefCtor;
4942 }
4943
4944 return false;
4945
4946 case Sema::CXXDestructor:
4947 // C++11 [class.dtor]p5:
4948 // A destructor is trivial if:
4949 // - all the direct [subobjects] have trivial destructors
4950 if (RD->hasTrivialDestructor())
4951 return true;
4952
4953 if (Selected) {
4954 if (RD->needsImplicitDestructor())
4955 S.DeclareImplicitDestructor(RD);
4956 *Selected = RD->getDestructor();
4957 }
4958
4959 return false;
4960
4961 case Sema::CXXCopyConstructor:
4962 // C++11 [class.copy]p12:
4963 // A copy constructor is trivial if:
4964 // - the constructor selected to copy each direct [subobject] is trivial
4965 if (RD->hasTrivialCopyConstructor()) {
4966 if (Quals == Qualifiers::Const)
4967 // We must either select the trivial copy constructor or reach an
4968 // ambiguity; no need to actually perform overload resolution.
4969 return true;
4970 } else if (!Selected) {
4971 return false;
4972 }
4973 // In C++98, we are not supposed to perform overload resolution here, but we
4974 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4975 // cases like B as having a non-trivial copy constructor:
4976 // struct A { template<typename T> A(T&); };
4977 // struct B { mutable A a; };
4978 goto NeedOverloadResolution;
4979
4980 case Sema::CXXCopyAssignment:
4981 // C++11 [class.copy]p25:
4982 // A copy assignment operator is trivial if:
4983 // - the assignment operator selected to copy each direct [subobject] is
4984 // trivial
4985 if (RD->hasTrivialCopyAssignment()) {
4986 if (Quals == Qualifiers::Const)
4987 return true;
4988 } else if (!Selected) {
4989 return false;
4990 }
4991 // In C++98, we are not supposed to perform overload resolution here, but we
4992 // treat that as a language defect.
4993 goto NeedOverloadResolution;
4994
4995 case Sema::CXXMoveConstructor:
4996 case Sema::CXXMoveAssignment:
4997 NeedOverloadResolution:
4998 Sema::SpecialMemberOverloadResult *SMOR =
4999 S.LookupSpecialMember(RD, CSM,
5000 Quals & Qualifiers::Const,
5001 Quals & Qualifiers::Volatile,
5002 /*RValueThis*/false, /*ConstThis*/false,
5003 /*VolatileThis*/false);
5004
5005 // The standard doesn't describe how to behave if the lookup is ambiguous.
5006 // We treat it as not making the member non-trivial, just like the standard
5007 // mandates for the default constructor. This should rarely matter, because
5008 // the member will also be deleted.
5009 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5010 return true;
5011
5012 if (!SMOR->getMethod()) {
5013 assert(SMOR->getKind() ==
5014 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5015 return false;
5016 }
5017
5018 // We deliberately don't check if we found a deleted special member. We're
5019 // not supposed to!
5020 if (Selected)
5021 *Selected = SMOR->getMethod();
5022 return SMOR->getMethod()->isTrivial();
5023 }
5024
5025 llvm_unreachable("unknown special method kind");
5026}
5027
Benjamin Kramera574c892013-02-15 12:30:38 +00005028static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005029 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5030 CI != CE; ++CI)
5031 if (!CI->isImplicit())
5032 return *CI;
5033
5034 // Look for constructor templates.
5035 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5036 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5037 if (CXXConstructorDecl *CD =
5038 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5039 return CD;
5040 }
5041
5042 return 0;
5043}
5044
5045/// The kind of subobject we are checking for triviality. The values of this
5046/// enumeration are used in diagnostics.
5047enum TrivialSubobjectKind {
5048 /// The subobject is a base class.
5049 TSK_BaseClass,
5050 /// The subobject is a non-static data member.
5051 TSK_Field,
5052 /// The object is actually the complete object.
5053 TSK_CompleteObject
5054};
5055
5056/// Check whether the special member selected for a given type would be trivial.
5057static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5058 QualType SubType,
5059 Sema::CXXSpecialMember CSM,
5060 TrivialSubobjectKind Kind,
5061 bool Diagnose) {
5062 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5063 if (!SubRD)
5064 return true;
5065
5066 CXXMethodDecl *Selected;
5067 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5068 Diagnose ? &Selected : 0))
5069 return true;
5070
5071 if (Diagnose) {
5072 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5073 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5074 << Kind << SubType.getUnqualifiedType();
5075 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5076 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5077 } else if (!Selected)
5078 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5079 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5080 else if (Selected->isUserProvided()) {
5081 if (Kind == TSK_CompleteObject)
5082 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5083 << Kind << SubType.getUnqualifiedType() << CSM;
5084 else {
5085 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5086 << Kind << SubType.getUnqualifiedType() << CSM;
5087 S.Diag(Selected->getLocation(), diag::note_declared_at);
5088 }
5089 } else {
5090 if (Kind != TSK_CompleteObject)
5091 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5092 << Kind << SubType.getUnqualifiedType() << CSM;
5093
5094 // Explain why the defaulted or deleted special member isn't trivial.
5095 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5096 }
5097 }
5098
5099 return false;
5100}
5101
5102/// Check whether the members of a class type allow a special member to be
5103/// trivial.
5104static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5105 Sema::CXXSpecialMember CSM,
5106 bool ConstArg, bool Diagnose) {
5107 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5108 FE = RD->field_end(); FI != FE; ++FI) {
5109 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5110 continue;
5111
5112 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5113
5114 // Pretend anonymous struct or union members are members of this class.
5115 if (FI->isAnonymousStructOrUnion()) {
5116 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5117 CSM, ConstArg, Diagnose))
5118 return false;
5119 continue;
5120 }
5121
5122 // C++11 [class.ctor]p5:
5123 // A default constructor is trivial if [...]
5124 // -- no non-static data member of its class has a
5125 // brace-or-equal-initializer
5126 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5127 if (Diagnose)
5128 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5129 return false;
5130 }
5131
5132 // Objective C ARC 4.3.5:
5133 // [...] nontrivally ownership-qualified types are [...] not trivially
5134 // default constructible, copy constructible, move constructible, copy
5135 // assignable, move assignable, or destructible [...]
5136 if (S.getLangOpts().ObjCAutoRefCount &&
5137 FieldType.hasNonTrivialObjCLifetime()) {
5138 if (Diagnose)
5139 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5140 << RD << FieldType.getObjCLifetime();
5141 return false;
5142 }
5143
5144 if (ConstArg && !FI->isMutable())
5145 FieldType.addConst();
5146 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5147 TSK_Field, Diagnose))
5148 return false;
5149 }
5150
5151 return true;
5152}
5153
5154/// Diagnose why the specified class does not have a trivial special member of
5155/// the given kind.
5156void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5157 QualType Ty = Context.getRecordType(RD);
5158 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5159 Ty.addConst();
5160
5161 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5162 TSK_CompleteObject, /*Diagnose*/true);
5163}
5164
5165/// Determine whether a defaulted or deleted special member function is trivial,
5166/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5167/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5168bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5169 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005170 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5171
5172 CXXRecordDecl *RD = MD->getParent();
5173
5174 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005175
5176 // C++11 [class.copy]p12, p25:
5177 // A [special member] is trivial if its declared parameter type is the same
5178 // as if it had been implicitly declared [...]
5179 switch (CSM) {
5180 case CXXDefaultConstructor:
5181 case CXXDestructor:
5182 // Trivial default constructors and destructors cannot have parameters.
5183 break;
5184
5185 case CXXCopyConstructor:
5186 case CXXCopyAssignment: {
5187 // Trivial copy operations always have const, non-volatile parameter types.
5188 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005189 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005190 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5191 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5192 if (Diagnose)
5193 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5194 << Param0->getSourceRange() << Param0->getType()
5195 << Context.getLValueReferenceType(
5196 Context.getRecordType(RD).withConst());
5197 return false;
5198 }
5199 break;
5200 }
5201
5202 case CXXMoveConstructor:
5203 case CXXMoveAssignment: {
5204 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005205 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005206 const RValueReferenceType *RT =
5207 Param0->getType()->getAs<RValueReferenceType>();
5208 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5209 if (Diagnose)
5210 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5211 << Param0->getSourceRange() << Param0->getType()
5212 << Context.getRValueReferenceType(Context.getRecordType(RD));
5213 return false;
5214 }
5215 break;
5216 }
5217
5218 case CXXInvalid:
5219 llvm_unreachable("not a special member");
5220 }
5221
5222 // FIXME: We require that the parameter-declaration-clause is equivalent to
5223 // that of an implicit declaration, not just that the declared parameter type
5224 // matches, in order to prevent absuridities like a function simultaneously
5225 // being a trivial copy constructor and a non-trivial default constructor.
5226 // This issue has not yet been assigned a core issue number.
5227 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5228 if (Diagnose)
5229 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5230 diag::note_nontrivial_default_arg)
5231 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5232 return false;
5233 }
5234 if (MD->isVariadic()) {
5235 if (Diagnose)
5236 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5237 return false;
5238 }
5239
5240 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5241 // A copy/move [constructor or assignment operator] is trivial if
5242 // -- the [member] selected to copy/move each direct base class subobject
5243 // is trivial
5244 //
5245 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5246 // A [default constructor or destructor] is trivial if
5247 // -- all the direct base classes have trivial [default constructors or
5248 // destructors]
5249 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5250 BE = RD->bases_end(); BI != BE; ++BI)
5251 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5252 ConstArg ? BI->getType().withConst()
5253 : BI->getType(),
5254 CSM, TSK_BaseClass, Diagnose))
5255 return false;
5256
5257 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5258 // A copy/move [constructor or assignment operator] for a class X is
5259 // trivial if
5260 // -- for each non-static data member of X that is of class type (or array
5261 // thereof), the constructor selected to copy/move that member is
5262 // trivial
5263 //
5264 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5265 // A [default constructor or destructor] is trivial if
5266 // -- for all of the non-static data members of its class that are of class
5267 // type (or array thereof), each such class has a trivial [default
5268 // constructor or destructor]
5269 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5270 return false;
5271
5272 // C++11 [class.dtor]p5:
5273 // A destructor is trivial if [...]
5274 // -- the destructor is not virtual
5275 if (CSM == CXXDestructor && MD->isVirtual()) {
5276 if (Diagnose)
5277 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5278 return false;
5279 }
5280
5281 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5282 // A [special member] for class X is trivial if [...]
5283 // -- class X has no virtual functions and no virtual base classes
5284 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5285 if (!Diagnose)
5286 return false;
5287
5288 if (RD->getNumVBases()) {
5289 // Check for virtual bases. We already know that the corresponding
5290 // member in all bases is trivial, so vbases must all be direct.
5291 CXXBaseSpecifier &BS = *RD->vbases_begin();
5292 assert(BS.isVirtual());
5293 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5294 return false;
5295 }
5296
5297 // Must have a virtual method.
5298 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5299 ME = RD->method_end(); MI != ME; ++MI) {
5300 if (MI->isVirtual()) {
5301 SourceLocation MLoc = MI->getLocStart();
5302 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5303 return false;
5304 }
5305 }
5306
5307 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5308 }
5309
5310 // Looks like it's trivial!
5311 return true;
5312}
5313
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005314/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005315namespace {
5316 struct FindHiddenVirtualMethodData {
5317 Sema *S;
5318 CXXMethodDecl *Method;
5319 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005320 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005321 };
5322}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005323
David Blaikie5f750682012-10-19 00:53:08 +00005324/// \brief Check whether any most overriden method from MD in Methods
5325static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5326 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5327 if (MD->size_overridden_methods() == 0)
5328 return Methods.count(MD->getCanonicalDecl());
5329 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5330 E = MD->end_overridden_methods();
5331 I != E; ++I)
5332 if (CheckMostOverridenMethods(*I, Methods))
5333 return true;
5334 return false;
5335}
5336
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005337/// \brief Member lookup function that determines whether a given C++
5338/// method overloads virtual methods in a base class without overriding any,
5339/// to be used with CXXRecordDecl::lookupInBases().
5340static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5341 CXXBasePath &Path,
5342 void *UserData) {
5343 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5344
5345 FindHiddenVirtualMethodData &Data
5346 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5347
5348 DeclarationName Name = Data.Method->getDeclName();
5349 assert(Name.getNameKind() == DeclarationName::Identifier);
5350
5351 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005352 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005353 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005354 !Path.Decls.empty();
5355 Path.Decls = Path.Decls.slice(1)) {
5356 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005357 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005358 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005359 foundSameNameMethod = true;
5360 // Interested only in hidden virtual methods.
5361 if (!MD->isVirtual())
5362 continue;
5363 // If the method we are checking overrides a method from its base
5364 // don't warn about the other overloaded methods.
5365 if (!Data.S->IsOverload(Data.Method, MD, false))
5366 return true;
5367 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005368 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005369 overloadedMethods.push_back(MD);
5370 }
5371 }
5372
5373 if (foundSameNameMethod)
5374 Data.OverloadedMethods.append(overloadedMethods.begin(),
5375 overloadedMethods.end());
5376 return foundSameNameMethod;
5377}
5378
David Blaikie5f750682012-10-19 00:53:08 +00005379/// \brief Add the most overriden methods from MD to Methods
5380static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5381 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5382 if (MD->size_overridden_methods() == 0)
5383 Methods.insert(MD->getCanonicalDecl());
5384 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5385 E = MD->end_overridden_methods();
5386 I != E; ++I)
5387 AddMostOverridenMethods(*I, Methods);
5388}
5389
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005390/// \brief See if a method overloads virtual methods in a base class without
5391/// overriding any.
5392void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5393 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005394 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005395 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005396 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005397 return;
5398
5399 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5400 /*bool RecordPaths=*/false,
5401 /*bool DetectVirtual=*/false);
5402 FindHiddenVirtualMethodData Data;
5403 Data.Method = MD;
5404 Data.S = this;
5405
5406 // Keep the base methods that were overriden or introduced in the subclass
5407 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005408 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5409 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5410 NamedDecl *ND = *I;
5411 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005412 ND = shad->getTargetDecl();
5413 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5414 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005415 }
5416
5417 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5418 !Data.OverloadedMethods.empty()) {
5419 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5420 << MD << (Data.OverloadedMethods.size() > 1);
5421
5422 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5423 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005424 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005425 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005426 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5427 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005428 }
5429 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005430}
5431
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005432void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005433 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005434 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005435 SourceLocation RBrac,
5436 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005437 if (!TagDecl)
5438 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005439
Douglas Gregor42af25f2009-05-11 19:58:34 +00005440 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005441
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005442 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5443 if (l->getKind() != AttributeList::AT_Visibility)
5444 continue;
5445 l->setInvalid();
5446 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5447 l->getName();
5448 }
5449
David Blaikie77b6de02011-09-22 02:58:26 +00005450 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005451 // strict aliasing violation!
5452 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005453 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005454
Douglas Gregor23c94db2010-07-02 17:43:08 +00005455 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005456 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005457}
5458
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005459/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5460/// special functions, such as the default constructor, copy
5461/// constructor, or destructor, to the given C++ class (C++
5462/// [special]p1). This routine can only be executed just before the
5463/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005464void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005465 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005466 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005467
Richard Smithbc2a35d2012-12-08 08:32:28 +00005468 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005469 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005470
Richard Smithbc2a35d2012-12-08 08:32:28 +00005471 // If the properties or semantics of the copy constructor couldn't be
5472 // determined while the class was being declared, force a declaration
5473 // of it now.
5474 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5475 DeclareImplicitCopyConstructor(ClassDecl);
5476 }
5477
Richard Smith80ad52f2013-01-02 11:42:31 +00005478 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005479 ++ASTContext::NumImplicitMoveConstructors;
5480
Richard Smithbc2a35d2012-12-08 08:32:28 +00005481 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5482 DeclareImplicitMoveConstructor(ClassDecl);
5483 }
5484
Douglas Gregora376d102010-07-02 21:50:04 +00005485 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5486 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005487
5488 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005489 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005490 // it shows up in the right place in the vtable and that we diagnose
5491 // problems with the implicit exception specification.
5492 if (ClassDecl->isDynamicClass() ||
5493 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005494 DeclareImplicitCopyAssignment(ClassDecl);
5495 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005496
Richard Smith80ad52f2013-01-02 11:42:31 +00005497 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005498 ++ASTContext::NumImplicitMoveAssignmentOperators;
5499
5500 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005501 if (ClassDecl->isDynamicClass() ||
5502 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005503 DeclareImplicitMoveAssignment(ClassDecl);
5504 }
5505
Douglas Gregor4923aa22010-07-02 20:37:36 +00005506 if (!ClassDecl->hasUserDeclaredDestructor()) {
5507 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005508
5509 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005510 // have to declare the destructor immediately. This ensures that, e.g., it
5511 // shows up in the right place in the vtable and that we diagnose problems
5512 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005513 if (ClassDecl->isDynamicClass() ||
5514 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005515 DeclareImplicitDestructor(ClassDecl);
5516 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005517}
5518
Francois Pichet8387e2a2011-04-22 22:18:13 +00005519void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5520 if (!D)
5521 return;
5522
5523 int NumParamList = D->getNumTemplateParameterLists();
5524 for (int i = 0; i < NumParamList; i++) {
5525 TemplateParameterList* Params = D->getTemplateParameterList(i);
5526 for (TemplateParameterList::iterator Param = Params->begin(),
5527 ParamEnd = Params->end();
5528 Param != ParamEnd; ++Param) {
5529 NamedDecl *Named = cast<NamedDecl>(*Param);
5530 if (Named->getDeclName()) {
5531 S->AddDecl(Named);
5532 IdResolver.AddDecl(Named);
5533 }
5534 }
5535 }
5536}
5537
John McCalld226f652010-08-21 09:40:31 +00005538void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005539 if (!D)
5540 return;
5541
5542 TemplateParameterList *Params = 0;
5543 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5544 Params = Template->getTemplateParameters();
5545 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5546 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5547 Params = PartialSpec->getTemplateParameters();
5548 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005549 return;
5550
Douglas Gregor6569d682009-05-27 23:11:45 +00005551 for (TemplateParameterList::iterator Param = Params->begin(),
5552 ParamEnd = Params->end();
5553 Param != ParamEnd; ++Param) {
5554 NamedDecl *Named = cast<NamedDecl>(*Param);
5555 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005556 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005557 IdResolver.AddDecl(Named);
5558 }
5559 }
5560}
5561
John McCalld226f652010-08-21 09:40:31 +00005562void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005563 if (!RecordD) return;
5564 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005565 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005566 PushDeclContext(S, Record);
5567}
5568
John McCalld226f652010-08-21 09:40:31 +00005569void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005570 if (!RecordD) return;
5571 PopDeclContext();
5572}
5573
Douglas Gregor72b505b2008-12-16 21:30:33 +00005574/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5575/// parsing a top-level (non-nested) C++ class, and we are now
5576/// parsing those parts of the given Method declaration that could
5577/// not be parsed earlier (C++ [class.mem]p2), such as default
5578/// arguments. This action should enter the scope of the given
5579/// Method declaration as if we had just parsed the qualified method
5580/// name. However, it should not bring the parameters into scope;
5581/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005582void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005583}
5584
5585/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5586/// C++ method declaration. We're (re-)introducing the given
5587/// function parameter into scope for use in parsing later parts of
5588/// the method declaration. For example, we could see an
5589/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005590void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005591 if (!ParamD)
5592 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005593
John McCalld226f652010-08-21 09:40:31 +00005594 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005595
5596 // If this parameter has an unparsed default argument, clear it out
5597 // to make way for the parsed default argument.
5598 if (Param->hasUnparsedDefaultArg())
5599 Param->setDefaultArg(0);
5600
John McCalld226f652010-08-21 09:40:31 +00005601 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005602 if (Param->getDeclName())
5603 IdResolver.AddDecl(Param);
5604}
5605
5606/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5607/// processing the delayed method declaration for Method. The method
5608/// declaration is now considered finished. There may be a separate
5609/// ActOnStartOfFunctionDef action later (not necessarily
5610/// immediately!) for this method, if it was also defined inside the
5611/// class body.
John McCalld226f652010-08-21 09:40:31 +00005612void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005613 if (!MethodD)
5614 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005615
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005616 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005617
John McCalld226f652010-08-21 09:40:31 +00005618 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005619
5620 // Now that we have our default arguments, check the constructor
5621 // again. It could produce additional diagnostics or affect whether
5622 // the class has implicitly-declared destructors, among other
5623 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005624 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5625 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005626
5627 // Check the default arguments, which we may have added.
5628 if (!Method->isInvalidDecl())
5629 CheckCXXDefaultArguments(Method);
5630}
5631
Douglas Gregor42a552f2008-11-05 20:51:48 +00005632/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005633/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005634/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005635/// emit diagnostics and set the invalid bit to true. In any case, the type
5636/// will be updated to reflect a well-formed type for the constructor and
5637/// returned.
5638QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005639 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005640 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005641
5642 // C++ [class.ctor]p3:
5643 // A constructor shall not be virtual (10.3) or static (9.4). A
5644 // constructor can be invoked for a const, volatile or const
5645 // volatile object. A constructor shall not be declared const,
5646 // volatile, or const volatile (9.3.2).
5647 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005648 if (!D.isInvalidType())
5649 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5650 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5651 << SourceRange(D.getIdentifierLoc());
5652 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005653 }
John McCalld931b082010-08-26 03:08:43 +00005654 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005655 if (!D.isInvalidType())
5656 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5657 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5658 << SourceRange(D.getIdentifierLoc());
5659 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005660 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005661 }
Mike Stump1eb44332009-09-09 15:08:12 +00005662
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005663 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005664 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005665 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005666 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5667 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005668 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005669 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5670 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005671 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005672 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5673 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005674 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005675 }
Mike Stump1eb44332009-09-09 15:08:12 +00005676
Douglas Gregorc938c162011-01-26 05:01:58 +00005677 // C++0x [class.ctor]p4:
5678 // A constructor shall not be declared with a ref-qualifier.
5679 if (FTI.hasRefQualifier()) {
5680 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5681 << FTI.RefQualifierIsLValueRef
5682 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5683 D.setInvalidType();
5684 }
5685
Douglas Gregor42a552f2008-11-05 20:51:48 +00005686 // Rebuild the function type "R" without any type qualifiers (in
5687 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005688 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005689 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005690 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5691 return R;
5692
5693 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5694 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005695 EPI.RefQualifier = RQ_None;
5696
Richard Smith07b0fdc2013-03-18 21:12:30 +00005697 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005698}
5699
Douglas Gregor72b505b2008-12-16 21:30:33 +00005700/// CheckConstructor - Checks a fully-formed constructor for
5701/// well-formedness, issuing any diagnostics required. Returns true if
5702/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005703void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005704 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005705 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5706 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005707 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005708
5709 // C++ [class.copy]p3:
5710 // A declaration of a constructor for a class X is ill-formed if
5711 // its first parameter is of type (optionally cv-qualified) X and
5712 // either there are no other parameters or else all other
5713 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005714 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005715 ((Constructor->getNumParams() == 1) ||
5716 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005717 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5718 Constructor->getTemplateSpecializationKind()
5719 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005720 QualType ParamType = Constructor->getParamDecl(0)->getType();
5721 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5722 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005723 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005724 const char *ConstRef
5725 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5726 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005727 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005728 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005729
5730 // FIXME: Rather that making the constructor invalid, we should endeavor
5731 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005732 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005733 }
5734 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005735}
5736
John McCall15442822010-08-04 01:04:25 +00005737/// CheckDestructor - Checks a fully-formed destructor definition for
5738/// well-formedness, issuing any diagnostics required. Returns true
5739/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005740bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005741 CXXRecordDecl *RD = Destructor->getParent();
5742
5743 if (Destructor->isVirtual()) {
5744 SourceLocation Loc;
5745
5746 if (!Destructor->isImplicit())
5747 Loc = Destructor->getLocation();
5748 else
5749 Loc = RD->getLocation();
5750
5751 // If we have a virtual destructor, look up the deallocation function
5752 FunctionDecl *OperatorDelete = 0;
5753 DeclarationName Name =
5754 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005755 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005756 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005757
Eli Friedman5f2987c2012-02-02 03:46:19 +00005758 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005759
5760 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005761 }
Anders Carlsson37909802009-11-30 21:24:50 +00005762
5763 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005764}
5765
Mike Stump1eb44332009-09-09 15:08:12 +00005766static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005767FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5768 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5769 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005770 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005771}
5772
Douglas Gregor42a552f2008-11-05 20:51:48 +00005773/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5774/// the well-formednes of the destructor declarator @p D with type @p
5775/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005776/// emit diagnostics and set the declarator to invalid. Even if this happens,
5777/// will be updated to reflect a well-formed type for the destructor and
5778/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005779QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005780 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005781 // C++ [class.dtor]p1:
5782 // [...] A typedef-name that names a class is a class-name
5783 // (7.1.3); however, a typedef-name that names a class shall not
5784 // be used as the identifier in the declarator for a destructor
5785 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005786 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005787 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005788 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005789 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005790 else if (const TemplateSpecializationType *TST =
5791 DeclaratorType->getAs<TemplateSpecializationType>())
5792 if (TST->isTypeAlias())
5793 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5794 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005795
5796 // C++ [class.dtor]p2:
5797 // A destructor is used to destroy objects of its class type. A
5798 // destructor takes no parameters, and no return type can be
5799 // specified for it (not even void). The address of a destructor
5800 // shall not be taken. A destructor shall not be static. A
5801 // destructor can be invoked for a const, volatile or const
5802 // volatile object. A destructor shall not be declared const,
5803 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005804 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005805 if (!D.isInvalidType())
5806 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5807 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005808 << SourceRange(D.getIdentifierLoc())
5809 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5810
John McCalld931b082010-08-26 03:08:43 +00005811 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005812 }
Chris Lattner65401802009-04-25 08:28:21 +00005813 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005814 // Destructors don't have return types, but the parser will
5815 // happily parse something like:
5816 //
5817 // class X {
5818 // float ~X();
5819 // };
5820 //
5821 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005822 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5823 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5824 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005825 }
Mike Stump1eb44332009-09-09 15:08:12 +00005826
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005827 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005828 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005829 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005830 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5831 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005832 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005833 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5834 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005835 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005836 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5837 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005838 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005839 }
5840
Douglas Gregorc938c162011-01-26 05:01:58 +00005841 // C++0x [class.dtor]p2:
5842 // A destructor shall not be declared with a ref-qualifier.
5843 if (FTI.hasRefQualifier()) {
5844 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5845 << FTI.RefQualifierIsLValueRef
5846 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5847 D.setInvalidType();
5848 }
5849
Douglas Gregor42a552f2008-11-05 20:51:48 +00005850 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005851 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005852 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5853
5854 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005855 FTI.freeArgs();
5856 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005857 }
5858
Mike Stump1eb44332009-09-09 15:08:12 +00005859 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005860 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005861 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005862 D.setInvalidType();
5863 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005864
5865 // Rebuild the function type "R" without any type qualifiers or
5866 // parameters (in case any of the errors above fired) and with
5867 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005868 // types.
John McCalle23cf432010-12-14 08:05:40 +00005869 if (!D.isInvalidType())
5870 return R;
5871
Douglas Gregord92ec472010-07-01 05:10:53 +00005872 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005873 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5874 EPI.Variadic = false;
5875 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005876 EPI.RefQualifier = RQ_None;
Jordan Rosebea522f2013-03-08 21:51:21 +00005877 return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005878}
5879
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005880/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5881/// well-formednes of the conversion function declarator @p D with
5882/// type @p R. If there are any errors in the declarator, this routine
5883/// will emit diagnostics and return true. Otherwise, it will return
5884/// false. Either way, the type @p R will be updated to reflect a
5885/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005886void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005887 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005888 // C++ [class.conv.fct]p1:
5889 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005890 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005891 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005892 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005893 if (!D.isInvalidType())
5894 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5895 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5896 << SourceRange(D.getIdentifierLoc());
5897 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005898 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005899 }
John McCalla3f81372010-04-13 00:04:31 +00005900
5901 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5902
Chris Lattner6e475012009-04-25 08:35:12 +00005903 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005904 // Conversion functions don't have return types, but the parser will
5905 // happily parse something like:
5906 //
5907 // class X {
5908 // float operator bool();
5909 // };
5910 //
5911 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005912 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5913 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5914 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005915 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005916 }
5917
John McCalla3f81372010-04-13 00:04:31 +00005918 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5919
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005920 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005921 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005922 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5923
5924 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005925 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005926 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005927 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005928 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005929 D.setInvalidType();
5930 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005931
John McCalla3f81372010-04-13 00:04:31 +00005932 // Diagnose "&operator bool()" and other such nonsense. This
5933 // is actually a gcc extension which we don't support.
5934 if (Proto->getResultType() != ConvType) {
5935 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5936 << Proto->getResultType();
5937 D.setInvalidType();
5938 ConvType = Proto->getResultType();
5939 }
5940
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005941 // C++ [class.conv.fct]p4:
5942 // The conversion-type-id shall not represent a function type nor
5943 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005944 if (ConvType->isArrayType()) {
5945 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5946 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005947 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005948 } else if (ConvType->isFunctionType()) {
5949 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5950 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005951 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005952 }
5953
5954 // Rebuild the function type "R" without any parameters (in case any
5955 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005956 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005957 if (D.isInvalidType())
Jordan Rosebea522f2013-03-08 21:51:21 +00005958 R = Context.getFunctionType(ConvType, ArrayRef<QualType>(),
5959 Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005960
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005961 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005962 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005963 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005964 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005965 diag::warn_cxx98_compat_explicit_conversion_functions :
5966 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005967 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005968}
5969
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005970/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5971/// the declaration of the given C++ conversion function. This routine
5972/// is responsible for recording the conversion function in the C++
5973/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005974Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005975 assert(Conversion && "Expected to receive a conversion function declaration");
5976
Douglas Gregor9d350972008-12-12 08:25:50 +00005977 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005978
5979 // Make sure we aren't redeclaring the conversion function.
5980 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005981
5982 // C++ [class.conv.fct]p1:
5983 // [...] A conversion function is never used to convert a
5984 // (possibly cv-qualified) object to the (possibly cv-qualified)
5985 // same object type (or a reference to it), to a (possibly
5986 // cv-qualified) base class of that type (or a reference to it),
5987 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005988 // FIXME: Suppress this warning if the conversion function ends up being a
5989 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005990 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005991 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005992 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005993 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005994 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5995 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005996 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005997 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005998 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5999 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006000 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006001 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006002 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006003 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006004 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006005 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006006 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006007 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006008 }
6009
Douglas Gregore80622f2010-09-29 04:25:11 +00006010 if (FunctionTemplateDecl *ConversionTemplate
6011 = Conversion->getDescribedFunctionTemplate())
6012 return ConversionTemplate;
6013
John McCalld226f652010-08-21 09:40:31 +00006014 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006015}
6016
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006017//===----------------------------------------------------------------------===//
6018// Namespace Handling
6019//===----------------------------------------------------------------------===//
6020
Richard Smithd1a55a62012-10-04 22:13:39 +00006021/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6022/// reopened.
6023static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6024 SourceLocation Loc,
6025 IdentifierInfo *II, bool *IsInline,
6026 NamespaceDecl *PrevNS) {
6027 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006028
Richard Smithc969e6a2012-10-05 01:46:25 +00006029 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6030 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6031 // inline namespaces, with the intention of bringing names into namespace std.
6032 //
6033 // We support this just well enough to get that case working; this is not
6034 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006035 if (*IsInline && II && II->getName().startswith("__atomic") &&
6036 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006037 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006038 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6039 NS = NS->getPreviousDecl())
6040 NS->setInline(*IsInline);
6041 // Patch up the lookup table for the containing namespace. This isn't really
6042 // correct, but it's good enough for this particular case.
6043 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6044 E = PrevNS->decls_end(); I != E; ++I)
6045 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6046 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6047 return;
6048 }
6049
6050 if (PrevNS->isInline())
6051 // The user probably just forgot the 'inline', so suggest that it
6052 // be added back.
6053 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6054 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6055 else
6056 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6057 << IsInline;
6058
6059 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6060 *IsInline = PrevNS->isInline();
6061}
John McCallea318642010-08-26 09:15:37 +00006062
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006063/// ActOnStartNamespaceDef - This is called at the start of a namespace
6064/// definition.
John McCalld226f652010-08-21 09:40:31 +00006065Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006066 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006067 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006068 SourceLocation IdentLoc,
6069 IdentifierInfo *II,
6070 SourceLocation LBrace,
6071 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006072 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6073 // For anonymous namespace, take the location of the left brace.
6074 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006075 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006076 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006077 bool IsStd = false;
6078 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006079 Scope *DeclRegionScope = NamespcScope->getParent();
6080
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006081 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006082 if (II) {
6083 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006084 // The identifier in an original-namespace-definition shall not
6085 // have been previously defined in the declarative region in
6086 // which the original-namespace-definition appears. The
6087 // identifier in an original-namespace-definition is the name of
6088 // the namespace. Subsequently in that declarative region, it is
6089 // treated as an original-namespace-name.
6090 //
6091 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006092 // look through using directives, just look for any ordinary names.
6093
6094 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006095 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6096 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006097 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006098 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6099 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6100 ++I) {
6101 if ((*I)->getIdentifierNamespace() & IDNS) {
6102 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006103 break;
6104 }
6105 }
6106
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006107 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6108
6109 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006110 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006111 if (IsInline != PrevNS->isInline())
6112 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6113 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006114 } else if (PrevDecl) {
6115 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006116 Diag(Loc, diag::err_redefinition_different_kind)
6117 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006118 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006119 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006120 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006121 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006122 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006123 // This is the first "real" definition of the namespace "std", so update
6124 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006125 PrevNS = getStdNamespace();
6126 IsStd = true;
6127 AddToKnown = !IsInline;
6128 } else {
6129 // We've seen this namespace for the first time.
6130 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006131 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006132 } else {
John McCall9aeed322009-10-01 00:25:31 +00006133 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006134
6135 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006136 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006137 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006138 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006139 } else {
6140 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006141 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006142 }
6143
Richard Smithd1a55a62012-10-04 22:13:39 +00006144 if (PrevNS && IsInline != PrevNS->isInline())
6145 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6146 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006147 }
6148
6149 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6150 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006151 if (IsInvalid)
6152 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006153
6154 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006155
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006156 // FIXME: Should we be merging attributes?
6157 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006158 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006159
6160 if (IsStd)
6161 StdNamespace = Namespc;
6162 if (AddToKnown)
6163 KnownNamespaces[Namespc] = false;
6164
6165 if (II) {
6166 PushOnScopeChains(Namespc, DeclRegionScope);
6167 } else {
6168 // Link the anonymous namespace into its parent.
6169 DeclContext *Parent = CurContext->getRedeclContext();
6170 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6171 TU->setAnonymousNamespace(Namespc);
6172 } else {
6173 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006174 }
John McCall9aeed322009-10-01 00:25:31 +00006175
Douglas Gregora4181472010-03-24 00:46:35 +00006176 CurContext->addDecl(Namespc);
6177
John McCall9aeed322009-10-01 00:25:31 +00006178 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6179 // behaves as if it were replaced by
6180 // namespace unique { /* empty body */ }
6181 // using namespace unique;
6182 // namespace unique { namespace-body }
6183 // where all occurrences of 'unique' in a translation unit are
6184 // replaced by the same identifier and this identifier differs
6185 // from all other identifiers in the entire program.
6186
6187 // We just create the namespace with an empty name and then add an
6188 // implicit using declaration, just like the standard suggests.
6189 //
6190 // CodeGen enforces the "universally unique" aspect by giving all
6191 // declarations semantically contained within an anonymous
6192 // namespace internal linkage.
6193
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006194 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006195 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006196 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006197 /* 'using' */ LBrace,
6198 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006199 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006200 /* identifier */ SourceLocation(),
6201 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006202 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006203 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006204 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006205 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006206 }
6207
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006208 ActOnDocumentableDecl(Namespc);
6209
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006210 // Although we could have an invalid decl (i.e. the namespace name is a
6211 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006212 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6213 // for the namespace has the declarations that showed up in that particular
6214 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006215 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006216 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006217}
6218
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006219/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6220/// is a namespace alias, returns the namespace it points to.
6221static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6222 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6223 return AD->getNamespace();
6224 return dyn_cast_or_null<NamespaceDecl>(D);
6225}
6226
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006227/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6228/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006229void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006230 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6231 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006232 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006233 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006234 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006235 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006236}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006237
John McCall384aff82010-08-25 07:42:41 +00006238CXXRecordDecl *Sema::getStdBadAlloc() const {
6239 return cast_or_null<CXXRecordDecl>(
6240 StdBadAlloc.get(Context.getExternalSource()));
6241}
6242
6243NamespaceDecl *Sema::getStdNamespace() const {
6244 return cast_or_null<NamespaceDecl>(
6245 StdNamespace.get(Context.getExternalSource()));
6246}
6247
Douglas Gregor66992202010-06-29 17:53:46 +00006248/// \brief Retrieve the special "std" namespace, which may require us to
6249/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006250NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006251 if (!StdNamespace) {
6252 // The "std" namespace has not yet been defined, so build one implicitly.
6253 StdNamespace = NamespaceDecl::Create(Context,
6254 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006255 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006256 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006257 &PP.getIdentifierTable().get("std"),
6258 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006259 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006260 }
6261
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006262 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006263}
6264
Sebastian Redl395e04d2012-01-17 22:49:33 +00006265bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006266 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006267 "Looking for std::initializer_list outside of C++.");
6268
6269 // We're looking for implicit instantiations of
6270 // template <typename E> class std::initializer_list.
6271
6272 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6273 return false;
6274
Sebastian Redl84760e32012-01-17 22:49:58 +00006275 ClassTemplateDecl *Template = 0;
6276 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006277
Sebastian Redl84760e32012-01-17 22:49:58 +00006278 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006279
Sebastian Redl84760e32012-01-17 22:49:58 +00006280 ClassTemplateSpecializationDecl *Specialization =
6281 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6282 if (!Specialization)
6283 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006284
Sebastian Redl84760e32012-01-17 22:49:58 +00006285 Template = Specialization->getSpecializedTemplate();
6286 Arguments = Specialization->getTemplateArgs().data();
6287 } else if (const TemplateSpecializationType *TST =
6288 Ty->getAs<TemplateSpecializationType>()) {
6289 Template = dyn_cast_or_null<ClassTemplateDecl>(
6290 TST->getTemplateName().getAsTemplateDecl());
6291 Arguments = TST->getArgs();
6292 }
6293 if (!Template)
6294 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006295
6296 if (!StdInitializerList) {
6297 // Haven't recognized std::initializer_list yet, maybe this is it.
6298 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6299 if (TemplateClass->getIdentifier() !=
6300 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006301 !getStdNamespace()->InEnclosingNamespaceSetOf(
6302 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006303 return false;
6304 // This is a template called std::initializer_list, but is it the right
6305 // template?
6306 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006307 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006308 return false;
6309 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6310 return false;
6311
6312 // It's the right template.
6313 StdInitializerList = Template;
6314 }
6315
6316 if (Template != StdInitializerList)
6317 return false;
6318
6319 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006320 if (Element)
6321 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006322 return true;
6323}
6324
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006325static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6326 NamespaceDecl *Std = S.getStdNamespace();
6327 if (!Std) {
6328 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6329 return 0;
6330 }
6331
6332 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6333 Loc, Sema::LookupOrdinaryName);
6334 if (!S.LookupQualifiedName(Result, Std)) {
6335 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6336 return 0;
6337 }
6338 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6339 if (!Template) {
6340 Result.suppressDiagnostics();
6341 // We found something weird. Complain about the first thing we found.
6342 NamedDecl *Found = *Result.begin();
6343 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6344 return 0;
6345 }
6346
6347 // We found some template called std::initializer_list. Now verify that it's
6348 // correct.
6349 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006350 if (Params->getMinRequiredArguments() != 1 ||
6351 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006352 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6353 return 0;
6354 }
6355
6356 return Template;
6357}
6358
6359QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6360 if (!StdInitializerList) {
6361 StdInitializerList = LookupStdInitializerList(*this, Loc);
6362 if (!StdInitializerList)
6363 return QualType();
6364 }
6365
6366 TemplateArgumentListInfo Args(Loc, Loc);
6367 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6368 Context.getTrivialTypeSourceInfo(Element,
6369 Loc)));
6370 return Context.getCanonicalType(
6371 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6372}
6373
Sebastian Redl98d36062012-01-17 22:50:14 +00006374bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6375 // C++ [dcl.init.list]p2:
6376 // A constructor is an initializer-list constructor if its first parameter
6377 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6378 // std::initializer_list<E> for some type E, and either there are no other
6379 // parameters or else all other parameters have default arguments.
6380 if (Ctor->getNumParams() < 1 ||
6381 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6382 return false;
6383
6384 QualType ArgType = Ctor->getParamDecl(0)->getType();
6385 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6386 ArgType = RT->getPointeeType().getUnqualifiedType();
6387
6388 return isStdInitializerList(ArgType, 0);
6389}
6390
Douglas Gregor9172aa62011-03-26 22:25:30 +00006391/// \brief Determine whether a using statement is in a context where it will be
6392/// apply in all contexts.
6393static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6394 switch (CurContext->getDeclKind()) {
6395 case Decl::TranslationUnit:
6396 return true;
6397 case Decl::LinkageSpec:
6398 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6399 default:
6400 return false;
6401 }
6402}
6403
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006404namespace {
6405
6406// Callback to only accept typo corrections that are namespaces.
6407class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6408 public:
6409 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6410 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6411 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6412 }
6413 return false;
6414 }
6415};
6416
6417}
6418
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006419static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6420 CXXScopeSpec &SS,
6421 SourceLocation IdentLoc,
6422 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006423 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006424 R.clear();
6425 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006426 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006427 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006428 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6429 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006430 if (DeclContext *DC = S.computeDeclContext(SS, false))
6431 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6432 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006433 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6434 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006435 else
6436 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6437 << Ident << CorrectedQuotedStr
6438 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006439
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006440 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6441 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006442
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006443 R.addDecl(Corrected.getCorrectionDecl());
6444 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006445 }
6446 return false;
6447}
6448
John McCalld226f652010-08-21 09:40:31 +00006449Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006450 SourceLocation UsingLoc,
6451 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006452 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006453 SourceLocation IdentLoc,
6454 IdentifierInfo *NamespcName,
6455 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006456 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6457 assert(NamespcName && "Invalid NamespcName.");
6458 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006459
6460 // This can only happen along a recovery path.
6461 while (S->getFlags() & Scope::TemplateParamScope)
6462 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006463 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006464
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006465 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006466 NestedNameSpecifier *Qualifier = 0;
6467 if (SS.isSet())
6468 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6469
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006470 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006471 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6472 LookupParsedName(R, S, &SS);
6473 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006474 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006475
Douglas Gregor66992202010-06-29 17:53:46 +00006476 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006477 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006478 // Allow "using namespace std;" or "using namespace ::std;" even if
6479 // "std" hasn't been defined yet, for GCC compatibility.
6480 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6481 NamespcName->isStr("std")) {
6482 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006483 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006484 R.resolveKind();
6485 }
6486 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006487 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006488 }
6489
John McCallf36e02d2009-10-09 21:13:30 +00006490 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006491 NamedDecl *Named = R.getFoundDecl();
6492 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6493 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006494 // C++ [namespace.udir]p1:
6495 // A using-directive specifies that the names in the nominated
6496 // namespace can be used in the scope in which the
6497 // using-directive appears after the using-directive. During
6498 // unqualified name lookup (3.4.1), the names appear as if they
6499 // were declared in the nearest enclosing namespace which
6500 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006501 // namespace. [Note: in this context, "contains" means "contains
6502 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006503
6504 // Find enclosing context containing both using-directive and
6505 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006506 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006507 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6508 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6509 CommonAncestor = CommonAncestor->getParent();
6510
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006511 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006512 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006513 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006514
Douglas Gregor9172aa62011-03-26 22:25:30 +00006515 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006516 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006517 Diag(IdentLoc, diag::warn_using_directive_in_header);
6518 }
6519
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006520 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006521 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006522 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006523 }
6524
Richard Smith6b3d3e52013-02-20 19:22:51 +00006525 if (UDir)
6526 ProcessDeclAttributeList(S, UDir, AttrList);
6527
John McCalld226f652010-08-21 09:40:31 +00006528 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006529}
6530
6531void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006532 // If the scope has an associated entity and the using directive is at
6533 // namespace or translation unit scope, add the UsingDirectiveDecl into
6534 // its lookup structure so qualified name lookup can find it.
6535 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6536 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006537 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006538 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006539 // Otherwise, it is at block sope. The using-directives will affect lookup
6540 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006541 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006542}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006543
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006544
John McCalld226f652010-08-21 09:40:31 +00006545Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006546 AccessSpecifier AS,
6547 bool HasUsingKeyword,
6548 SourceLocation UsingLoc,
6549 CXXScopeSpec &SS,
6550 UnqualifiedId &Name,
6551 AttributeList *AttrList,
6552 bool IsTypeName,
6553 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006554 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006555
Douglas Gregor12c118a2009-11-04 16:30:06 +00006556 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006557 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006558 case UnqualifiedId::IK_Identifier:
6559 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006560 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006561 case UnqualifiedId::IK_ConversionFunctionId:
6562 break;
6563
6564 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006565 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006566 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006567 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006568 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006569 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006570 diag::err_using_decl_constructor)
6571 << SS.getRange();
6572
Richard Smith80ad52f2013-01-02 11:42:31 +00006573 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006574
John McCalld226f652010-08-21 09:40:31 +00006575 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006576
6577 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006578 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006579 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006580 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006581
6582 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006583 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006584 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006585 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006586 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006587
6588 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6589 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006590 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006591 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006592
Richard Smith07b0fdc2013-03-18 21:12:30 +00006593 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006594 // TODO: store that the declaration was written without 'using' and
6595 // talk about access decls instead of using decls in the
6596 // diagnostics.
6597 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006598 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006599
6600 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006601 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006602 }
6603
Douglas Gregor56c04582010-12-16 00:46:58 +00006604 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6605 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6606 return 0;
6607
John McCall9488ea12009-11-17 05:59:44 +00006608 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006609 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006610 /* IsInstantiation */ false,
6611 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006612 if (UD)
6613 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006614
John McCalld226f652010-08-21 09:40:31 +00006615 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006616}
6617
Douglas Gregor09acc982010-07-07 23:08:52 +00006618/// \brief Determine whether a using declaration considers the given
6619/// declarations as "equivalent", e.g., if they are redeclarations of
6620/// the same entity or are both typedefs of the same type.
6621static bool
6622IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6623 bool &SuppressRedeclaration) {
6624 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6625 SuppressRedeclaration = false;
6626 return true;
6627 }
6628
Richard Smith162e1c12011-04-15 14:24:37 +00006629 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6630 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006631 SuppressRedeclaration = true;
6632 return Context.hasSameType(TD1->getUnderlyingType(),
6633 TD2->getUnderlyingType());
6634 }
6635
6636 return false;
6637}
6638
6639
John McCall9f54ad42009-12-10 09:41:52 +00006640/// Determines whether to create a using shadow decl for a particular
6641/// decl, given the set of decls existing prior to this using lookup.
6642bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6643 const LookupResult &Previous) {
6644 // Diagnose finding a decl which is not from a base class of the
6645 // current class. We do this now because there are cases where this
6646 // function will silently decide not to build a shadow decl, which
6647 // will pre-empt further diagnostics.
6648 //
6649 // We don't need to do this in C++0x because we do the check once on
6650 // the qualifier.
6651 //
6652 // FIXME: diagnose the following if we care enough:
6653 // struct A { int foo; };
6654 // struct B : A { using A::foo; };
6655 // template <class T> struct C : A {};
6656 // template <class T> struct D : C<T> { using B::foo; } // <---
6657 // This is invalid (during instantiation) in C++03 because B::foo
6658 // resolves to the using decl in B, which is not a base class of D<T>.
6659 // We can't diagnose it immediately because C<T> is an unknown
6660 // specialization. The UsingShadowDecl in D<T> then points directly
6661 // to A::foo, which will look well-formed when we instantiate.
6662 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006663 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006664 DeclContext *OrigDC = Orig->getDeclContext();
6665
6666 // Handle enums and anonymous structs.
6667 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6668 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6669 while (OrigRec->isAnonymousStructOrUnion())
6670 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6671
6672 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6673 if (OrigDC == CurContext) {
6674 Diag(Using->getLocation(),
6675 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006676 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006677 Diag(Orig->getLocation(), diag::note_using_decl_target);
6678 return true;
6679 }
6680
Douglas Gregordc355712011-02-25 00:36:19 +00006681 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006682 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006683 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006684 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006685 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006686 Diag(Orig->getLocation(), diag::note_using_decl_target);
6687 return true;
6688 }
6689 }
6690
6691 if (Previous.empty()) return false;
6692
6693 NamedDecl *Target = Orig;
6694 if (isa<UsingShadowDecl>(Target))
6695 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6696
John McCalld7533ec2009-12-11 02:33:26 +00006697 // If the target happens to be one of the previous declarations, we
6698 // don't have a conflict.
6699 //
6700 // FIXME: but we might be increasing its access, in which case we
6701 // should redeclare it.
6702 NamedDecl *NonTag = 0, *Tag = 0;
6703 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6704 I != E; ++I) {
6705 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006706 bool Result;
6707 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6708 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006709
6710 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6711 }
6712
John McCall9f54ad42009-12-10 09:41:52 +00006713 if (Target->isFunctionOrFunctionTemplate()) {
6714 FunctionDecl *FD;
6715 if (isa<FunctionTemplateDecl>(Target))
6716 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6717 else
6718 FD = cast<FunctionDecl>(Target);
6719
6720 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006721 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006722 case Ovl_Overload:
6723 return false;
6724
6725 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006726 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006727 break;
6728
6729 // We found a decl with the exact signature.
6730 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006731 // If we're in a record, we want to hide the target, so we
6732 // return true (without a diagnostic) to tell the caller not to
6733 // build a shadow decl.
6734 if (CurContext->isRecord())
6735 return true;
6736
6737 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006738 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006739 break;
6740 }
6741
6742 Diag(Target->getLocation(), diag::note_using_decl_target);
6743 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6744 return true;
6745 }
6746
6747 // Target is not a function.
6748
John McCall9f54ad42009-12-10 09:41:52 +00006749 if (isa<TagDecl>(Target)) {
6750 // No conflict between a tag and a non-tag.
6751 if (!Tag) return false;
6752
John McCall41ce66f2009-12-10 19:51:03 +00006753 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006754 Diag(Target->getLocation(), diag::note_using_decl_target);
6755 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6756 return true;
6757 }
6758
6759 // No conflict between a tag and a non-tag.
6760 if (!NonTag) return false;
6761
John McCall41ce66f2009-12-10 19:51:03 +00006762 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006763 Diag(Target->getLocation(), diag::note_using_decl_target);
6764 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6765 return true;
6766}
6767
John McCall9488ea12009-11-17 05:59:44 +00006768/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006769UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006770 UsingDecl *UD,
6771 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006772
6773 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006774 NamedDecl *Target = Orig;
6775 if (isa<UsingShadowDecl>(Target)) {
6776 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6777 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006778 }
6779
6780 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006781 = UsingShadowDecl::Create(Context, CurContext,
6782 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006783 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006784
6785 Shadow->setAccess(UD->getAccess());
6786 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6787 Shadow->setInvalidDecl();
6788
John McCall9488ea12009-11-17 05:59:44 +00006789 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006790 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006791 else
John McCall604e7f12009-12-08 07:46:18 +00006792 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006793
John McCall604e7f12009-12-08 07:46:18 +00006794
John McCall9f54ad42009-12-10 09:41:52 +00006795 return Shadow;
6796}
John McCall604e7f12009-12-08 07:46:18 +00006797
John McCall9f54ad42009-12-10 09:41:52 +00006798/// Hides a using shadow declaration. This is required by the current
6799/// using-decl implementation when a resolvable using declaration in a
6800/// class is followed by a declaration which would hide or override
6801/// one or more of the using decl's targets; for example:
6802///
6803/// struct Base { void foo(int); };
6804/// struct Derived : Base {
6805/// using Base::foo;
6806/// void foo(int);
6807/// };
6808///
6809/// The governing language is C++03 [namespace.udecl]p12:
6810///
6811/// When a using-declaration brings names from a base class into a
6812/// derived class scope, member functions in the derived class
6813/// override and/or hide member functions with the same name and
6814/// parameter types in a base class (rather than conflicting).
6815///
6816/// There are two ways to implement this:
6817/// (1) optimistically create shadow decls when they're not hidden
6818/// by existing declarations, or
6819/// (2) don't create any shadow decls (or at least don't make them
6820/// visible) until we've fully parsed/instantiated the class.
6821/// The problem with (1) is that we might have to retroactively remove
6822/// a shadow decl, which requires several O(n) operations because the
6823/// decl structures are (very reasonably) not designed for removal.
6824/// (2) avoids this but is very fiddly and phase-dependent.
6825void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006826 if (Shadow->getDeclName().getNameKind() ==
6827 DeclarationName::CXXConversionFunctionName)
6828 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6829
John McCall9f54ad42009-12-10 09:41:52 +00006830 // Remove it from the DeclContext...
6831 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006832
John McCall9f54ad42009-12-10 09:41:52 +00006833 // ...and the scope, if applicable...
6834 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006835 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006836 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006837 }
6838
John McCall9f54ad42009-12-10 09:41:52 +00006839 // ...and the using decl.
6840 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6841
6842 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006843 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006844}
6845
John McCall7ba107a2009-11-18 02:36:19 +00006846/// Builds a using declaration.
6847///
6848/// \param IsInstantiation - Whether this call arises from an
6849/// instantiation of an unresolved using declaration. We treat
6850/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006851NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6852 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006853 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006854 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006855 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006856 bool IsInstantiation,
6857 bool IsTypeName,
6858 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006859 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006860 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006861 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006862
Anders Carlsson550b14b2009-08-28 05:49:21 +00006863 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006864
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006865 if (SS.isEmpty()) {
6866 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006867 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006868 }
Mike Stump1eb44332009-09-09 15:08:12 +00006869
John McCall9f54ad42009-12-10 09:41:52 +00006870 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006871 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006872 ForRedeclaration);
6873 Previous.setHideTags(false);
6874 if (S) {
6875 LookupName(Previous, S);
6876
6877 // It is really dumb that we have to do this.
6878 LookupResult::Filter F = Previous.makeFilter();
6879 while (F.hasNext()) {
6880 NamedDecl *D = F.next();
6881 if (!isDeclInScope(D, CurContext, S))
6882 F.erase();
6883 }
6884 F.done();
6885 } else {
6886 assert(IsInstantiation && "no scope in non-instantiation");
6887 assert(CurContext->isRecord() && "scope not record in instantiation");
6888 LookupQualifiedName(Previous, CurContext);
6889 }
6890
John McCall9f54ad42009-12-10 09:41:52 +00006891 // Check for invalid redeclarations.
6892 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6893 return 0;
6894
6895 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006896 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6897 return 0;
6898
John McCallaf8e6ed2009-11-12 03:15:40 +00006899 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006900 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006901 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006902 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006903 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006904 // FIXME: not all declaration name kinds are legal here
6905 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6906 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006907 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006908 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006909 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006910 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6911 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006912 }
John McCalled976492009-12-04 22:46:56 +00006913 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006914 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6915 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006916 }
John McCalled976492009-12-04 22:46:56 +00006917 D->setAccess(AS);
6918 CurContext->addDecl(D);
6919
6920 if (!LookupContext) return D;
6921 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006922
John McCall77bb1aa2010-05-01 00:40:08 +00006923 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006924 UD->setInvalidDecl();
6925 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006926 }
6927
Richard Smithc5a89a12012-04-02 01:30:27 +00006928 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006929 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006930 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006931 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006932 return UD;
6933 }
6934
6935 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006936
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006937 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006938
John McCall604e7f12009-12-08 07:46:18 +00006939 // Unlike most lookups, we don't always want to hide tag
6940 // declarations: tag names are visible through the using declaration
6941 // even if hidden by ordinary names, *except* in a dependent context
6942 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006943 if (!IsInstantiation)
6944 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006945
John McCallb9abd8722012-04-07 03:04:20 +00006946 // For the purposes of this lookup, we have a base object type
6947 // equal to that of the current context.
6948 if (CurContext->isRecord()) {
6949 R.setBaseObjectType(
6950 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6951 }
6952
John McCalla24dc2e2009-11-17 02:14:36 +00006953 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006954
John McCallf36e02d2009-10-09 21:13:30 +00006955 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006956 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006957 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006958 UD->setInvalidDecl();
6959 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006960 }
6961
John McCalled976492009-12-04 22:46:56 +00006962 if (R.isAmbiguous()) {
6963 UD->setInvalidDecl();
6964 return UD;
6965 }
Mike Stump1eb44332009-09-09 15:08:12 +00006966
John McCall7ba107a2009-11-18 02:36:19 +00006967 if (IsTypeName) {
6968 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006969 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006970 Diag(IdentLoc, diag::err_using_typename_non_type);
6971 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6972 Diag((*I)->getUnderlyingDecl()->getLocation(),
6973 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006974 UD->setInvalidDecl();
6975 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006976 }
6977 } else {
6978 // If we asked for a non-typename and we got a type, error out,
6979 // but only if this is an instantiation of an unresolved using
6980 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006981 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006982 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6983 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006984 UD->setInvalidDecl();
6985 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006986 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006987 }
6988
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006989 // C++0x N2914 [namespace.udecl]p6:
6990 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006991 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006992 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6993 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006994 UD->setInvalidDecl();
6995 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006996 }
Mike Stump1eb44332009-09-09 15:08:12 +00006997
John McCall9f54ad42009-12-10 09:41:52 +00006998 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6999 if (!CheckUsingShadowDecl(UD, *I, Previous))
7000 BuildUsingShadowDecl(S, UD, *I);
7001 }
John McCall9488ea12009-11-17 05:59:44 +00007002
7003 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007004}
7005
Sebastian Redlf677ea32011-02-05 19:23:19 +00007006/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007007bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7008 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007009
Douglas Gregordc355712011-02-25 00:36:19 +00007010 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007011 assert(SourceType &&
7012 "Using decl naming constructor doesn't have type in scope spec.");
7013 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7014
7015 // Check whether the named type is a direct base class.
7016 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7017 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7018 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7019 BaseIt != BaseE; ++BaseIt) {
7020 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7021 if (CanonicalSourceType == BaseType)
7022 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007023 if (BaseIt->getType()->isDependentType())
7024 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007025 }
7026
7027 if (BaseIt == BaseE) {
7028 // Did not find SourceType in the bases.
7029 Diag(UD->getUsingLocation(),
7030 diag::err_using_decl_constructor_not_in_direct_base)
7031 << UD->getNameInfo().getSourceRange()
7032 << QualType(SourceType, 0) << TargetClass;
7033 return true;
7034 }
7035
Richard Smithc5a89a12012-04-02 01:30:27 +00007036 if (!CurContext->isDependentContext())
7037 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007038
7039 return false;
7040}
7041
John McCall9f54ad42009-12-10 09:41:52 +00007042/// Checks that the given using declaration is not an invalid
7043/// redeclaration. Note that this is checking only for the using decl
7044/// itself, not for any ill-formedness among the UsingShadowDecls.
7045bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7046 bool isTypeName,
7047 const CXXScopeSpec &SS,
7048 SourceLocation NameLoc,
7049 const LookupResult &Prev) {
7050 // C++03 [namespace.udecl]p8:
7051 // C++0x [namespace.udecl]p10:
7052 // A using-declaration is a declaration and can therefore be used
7053 // repeatedly where (and only where) multiple declarations are
7054 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007055 //
John McCall8a726212010-11-29 18:01:58 +00007056 // That's in non-member contexts.
7057 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007058 return false;
7059
7060 NestedNameSpecifier *Qual
7061 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7062
7063 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7064 NamedDecl *D = *I;
7065
7066 bool DTypename;
7067 NestedNameSpecifier *DQual;
7068 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7069 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007070 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007071 } else if (UnresolvedUsingValueDecl *UD
7072 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7073 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007074 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007075 } else if (UnresolvedUsingTypenameDecl *UD
7076 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7077 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007078 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007079 } else continue;
7080
7081 // using decls differ if one says 'typename' and the other doesn't.
7082 // FIXME: non-dependent using decls?
7083 if (isTypeName != DTypename) continue;
7084
7085 // using decls differ if they name different scopes (but note that
7086 // template instantiation can cause this check to trigger when it
7087 // didn't before instantiation).
7088 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7089 Context.getCanonicalNestedNameSpecifier(DQual))
7090 continue;
7091
7092 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007093 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007094 return true;
7095 }
7096
7097 return false;
7098}
7099
John McCall604e7f12009-12-08 07:46:18 +00007100
John McCalled976492009-12-04 22:46:56 +00007101/// Checks that the given nested-name qualifier used in a using decl
7102/// in the current context is appropriately related to the current
7103/// scope. If an error is found, diagnoses it and returns true.
7104bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7105 const CXXScopeSpec &SS,
7106 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007107 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007108
John McCall604e7f12009-12-08 07:46:18 +00007109 if (!CurContext->isRecord()) {
7110 // C++03 [namespace.udecl]p3:
7111 // C++0x [namespace.udecl]p8:
7112 // A using-declaration for a class member shall be a member-declaration.
7113
7114 // If we weren't able to compute a valid scope, it must be a
7115 // dependent class scope.
7116 if (!NamedContext || NamedContext->isRecord()) {
7117 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7118 << SS.getRange();
7119 return true;
7120 }
7121
7122 // Otherwise, everything is known to be fine.
7123 return false;
7124 }
7125
7126 // The current scope is a record.
7127
7128 // If the named context is dependent, we can't decide much.
7129 if (!NamedContext) {
7130 // FIXME: in C++0x, we can diagnose if we can prove that the
7131 // nested-name-specifier does not refer to a base class, which is
7132 // still possible in some cases.
7133
7134 // Otherwise we have to conservatively report that things might be
7135 // okay.
7136 return false;
7137 }
7138
7139 if (!NamedContext->isRecord()) {
7140 // Ideally this would point at the last name in the specifier,
7141 // but we don't have that level of source info.
7142 Diag(SS.getRange().getBegin(),
7143 diag::err_using_decl_nested_name_specifier_is_not_class)
7144 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7145 return true;
7146 }
7147
Douglas Gregor6fb07292010-12-21 07:41:49 +00007148 if (!NamedContext->isDependentContext() &&
7149 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7150 return true;
7151
Richard Smith80ad52f2013-01-02 11:42:31 +00007152 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007153 // C++0x [namespace.udecl]p3:
7154 // In a using-declaration used as a member-declaration, the
7155 // nested-name-specifier shall name a base class of the class
7156 // being defined.
7157
7158 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7159 cast<CXXRecordDecl>(NamedContext))) {
7160 if (CurContext == NamedContext) {
7161 Diag(NameLoc,
7162 diag::err_using_decl_nested_name_specifier_is_current_class)
7163 << SS.getRange();
7164 return true;
7165 }
7166
7167 Diag(SS.getRange().getBegin(),
7168 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7169 << (NestedNameSpecifier*) SS.getScopeRep()
7170 << cast<CXXRecordDecl>(CurContext)
7171 << SS.getRange();
7172 return true;
7173 }
7174
7175 return false;
7176 }
7177
7178 // C++03 [namespace.udecl]p4:
7179 // A using-declaration used as a member-declaration shall refer
7180 // to a member of a base class of the class being defined [etc.].
7181
7182 // Salient point: SS doesn't have to name a base class as long as
7183 // lookup only finds members from base classes. Therefore we can
7184 // diagnose here only if we can prove that that can't happen,
7185 // i.e. if the class hierarchies provably don't intersect.
7186
7187 // TODO: it would be nice if "definitely valid" results were cached
7188 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7189 // need to be repeated.
7190
7191 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007192 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007193
7194 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7195 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7196 Data->Bases.insert(Base);
7197 return true;
7198 }
7199
7200 bool hasDependentBases(const CXXRecordDecl *Class) {
7201 return !Class->forallBases(collect, this);
7202 }
7203
7204 /// Returns true if the base is dependent or is one of the
7205 /// accumulated base classes.
7206 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7207 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7208 return !Data->Bases.count(Base);
7209 }
7210
7211 bool mightShareBases(const CXXRecordDecl *Class) {
7212 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7213 }
7214 };
7215
7216 UserData Data;
7217
7218 // Returns false if we find a dependent base.
7219 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7220 return false;
7221
7222 // Returns false if the class has a dependent base or if it or one
7223 // of its bases is present in the base set of the current context.
7224 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7225 return false;
7226
7227 Diag(SS.getRange().getBegin(),
7228 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7229 << (NestedNameSpecifier*) SS.getScopeRep()
7230 << cast<CXXRecordDecl>(CurContext)
7231 << SS.getRange();
7232
7233 return true;
John McCalled976492009-12-04 22:46:56 +00007234}
7235
Richard Smith162e1c12011-04-15 14:24:37 +00007236Decl *Sema::ActOnAliasDeclaration(Scope *S,
7237 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007238 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007239 SourceLocation UsingLoc,
7240 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007241 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007242 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007243 // Skip up to the relevant declaration scope.
7244 while (S->getFlags() & Scope::TemplateParamScope)
7245 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007246 assert((S->getFlags() & Scope::DeclScope) &&
7247 "got alias-declaration outside of declaration scope");
7248
7249 if (Type.isInvalid())
7250 return 0;
7251
7252 bool Invalid = false;
7253 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7254 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007255 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007256
7257 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7258 return 0;
7259
7260 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007261 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007262 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007263 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7264 TInfo->getTypeLoc().getBeginLoc());
7265 }
Richard Smith162e1c12011-04-15 14:24:37 +00007266
7267 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7268 LookupName(Previous, S);
7269
7270 // Warn about shadowing the name of a template parameter.
7271 if (Previous.isSingleResult() &&
7272 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007273 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007274 Previous.clear();
7275 }
7276
7277 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7278 "name in alias declaration must be an identifier");
7279 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7280 Name.StartLocation,
7281 Name.Identifier, TInfo);
7282
7283 NewTD->setAccess(AS);
7284
7285 if (Invalid)
7286 NewTD->setInvalidDecl();
7287
Richard Smith6b3d3e52013-02-20 19:22:51 +00007288 ProcessDeclAttributeList(S, NewTD, AttrList);
7289
Richard Smith3e4c6c42011-05-05 21:57:07 +00007290 CheckTypedefForVariablyModifiedType(S, NewTD);
7291 Invalid |= NewTD->isInvalidDecl();
7292
Richard Smith162e1c12011-04-15 14:24:37 +00007293 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007294
7295 NamedDecl *NewND;
7296 if (TemplateParamLists.size()) {
7297 TypeAliasTemplateDecl *OldDecl = 0;
7298 TemplateParameterList *OldTemplateParams = 0;
7299
7300 if (TemplateParamLists.size() != 1) {
7301 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007302 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7303 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007304 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007305 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007306
7307 // Only consider previous declarations in the same scope.
7308 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7309 /*ExplicitInstantiationOrSpecialization*/false);
7310 if (!Previous.empty()) {
7311 Redeclaration = true;
7312
7313 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7314 if (!OldDecl && !Invalid) {
7315 Diag(UsingLoc, diag::err_redefinition_different_kind)
7316 << Name.Identifier;
7317
7318 NamedDecl *OldD = Previous.getRepresentativeDecl();
7319 if (OldD->getLocation().isValid())
7320 Diag(OldD->getLocation(), diag::note_previous_definition);
7321
7322 Invalid = true;
7323 }
7324
7325 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7326 if (TemplateParameterListsAreEqual(TemplateParams,
7327 OldDecl->getTemplateParameters(),
7328 /*Complain=*/true,
7329 TPL_TemplateMatch))
7330 OldTemplateParams = OldDecl->getTemplateParameters();
7331 else
7332 Invalid = true;
7333
7334 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7335 if (!Invalid &&
7336 !Context.hasSameType(OldTD->getUnderlyingType(),
7337 NewTD->getUnderlyingType())) {
7338 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7339 // but we can't reasonably accept it.
7340 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7341 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7342 if (OldTD->getLocation().isValid())
7343 Diag(OldTD->getLocation(), diag::note_previous_definition);
7344 Invalid = true;
7345 }
7346 }
7347 }
7348
7349 // Merge any previous default template arguments into our parameters,
7350 // and check the parameter list.
7351 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7352 TPC_TypeAliasTemplate))
7353 return 0;
7354
7355 TypeAliasTemplateDecl *NewDecl =
7356 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7357 Name.Identifier, TemplateParams,
7358 NewTD);
7359
7360 NewDecl->setAccess(AS);
7361
7362 if (Invalid)
7363 NewDecl->setInvalidDecl();
7364 else if (OldDecl)
7365 NewDecl->setPreviousDeclaration(OldDecl);
7366
7367 NewND = NewDecl;
7368 } else {
7369 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7370 NewND = NewTD;
7371 }
Richard Smith162e1c12011-04-15 14:24:37 +00007372
7373 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007374 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007375
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007376 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007377 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007378}
7379
John McCalld226f652010-08-21 09:40:31 +00007380Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007381 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007382 SourceLocation AliasLoc,
7383 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007384 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007385 SourceLocation IdentLoc,
7386 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007387
Anders Carlsson81c85c42009-03-28 23:53:49 +00007388 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007389 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7390 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007391
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007392 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007393 NamedDecl *PrevDecl
7394 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7395 ForRedeclaration);
7396 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7397 PrevDecl = 0;
7398
7399 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007400 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007401 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007402 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007403 // FIXME: At some point, we'll want to create the (redundant)
7404 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007405 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007406 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007407 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007408 }
Mike Stump1eb44332009-09-09 15:08:12 +00007409
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007410 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7411 diag::err_redefinition_different_kind;
7412 Diag(AliasLoc, DiagID) << Alias;
7413 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007414 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007415 }
7416
John McCalla24dc2e2009-11-17 02:14:36 +00007417 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007418 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007419
John McCallf36e02d2009-10-09 21:13:30 +00007420 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007421 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007422 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007423 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007424 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007425 }
Mike Stump1eb44332009-09-09 15:08:12 +00007426
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007427 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007428 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007429 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007430 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007431
John McCall3dbd3d52010-02-16 06:53:13 +00007432 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007433 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007434}
7435
Sean Hunt001cad92011-05-10 00:49:42 +00007436Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007437Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7438 CXXMethodDecl *MD) {
7439 CXXRecordDecl *ClassDecl = MD->getParent();
7440
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007441 // C++ [except.spec]p14:
7442 // An implicitly declared special member function (Clause 12) shall have an
7443 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007444 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007445 if (ClassDecl->isInvalidDecl())
7446 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007447
Sebastian Redl60618fa2011-03-12 11:50:43 +00007448 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007449 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7450 BEnd = ClassDecl->bases_end();
7451 B != BEnd; ++B) {
7452 if (B->isVirtual()) // Handled below.
7453 continue;
7454
Douglas Gregor18274032010-07-03 00:47:00 +00007455 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7456 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007457 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7458 // If this is a deleted function, add it anyway. This might be conformant
7459 // with the standard. This might not. I'm not sure. It might not matter.
7460 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007461 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007462 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007463 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007464
7465 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007466 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7467 BEnd = ClassDecl->vbases_end();
7468 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007469 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7470 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007471 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7472 // If this is a deleted function, add it anyway. This might be conformant
7473 // with the standard. This might not. I'm not sure. It might not matter.
7474 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007475 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007476 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007477 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007478
7479 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007480 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7481 FEnd = ClassDecl->field_end();
7482 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007483 if (F->hasInClassInitializer()) {
7484 if (Expr *E = F->getInClassInitializer())
7485 ExceptSpec.CalledExpr(E);
7486 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007487 // DR1351:
7488 // If the brace-or-equal-initializer of a non-static data member
7489 // invokes a defaulted default constructor of its class or of an
7490 // enclosing class in a potentially evaluated subexpression, the
7491 // program is ill-formed.
7492 //
7493 // This resolution is unworkable: the exception specification of the
7494 // default constructor can be needed in an unevaluated context, in
7495 // particular, in the operand of a noexcept-expression, and we can be
7496 // unable to compute an exception specification for an enclosed class.
7497 //
7498 // We do not allow an in-class initializer to require the evaluation
7499 // of the exception specification for any in-class initializer whose
7500 // definition is not lexically complete.
7501 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007502 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007503 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007504 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7505 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7506 // If this is a deleted function, add it anyway. This might be conformant
7507 // with the standard. This might not. I'm not sure. It might not matter.
7508 // In particular, the problem is that this function never gets called. It
7509 // might just be ill-formed because this function attempts to refer to
7510 // a deleted function here.
7511 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007512 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007513 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007514 }
John McCalle23cf432010-12-14 08:05:40 +00007515
Sean Hunt001cad92011-05-10 00:49:42 +00007516 return ExceptSpec;
7517}
7518
Richard Smith07b0fdc2013-03-18 21:12:30 +00007519Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007520Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7521 CXXRecordDecl *ClassDecl = CD->getParent();
7522
7523 // C++ [except.spec]p14:
7524 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007525 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007526 if (ClassDecl->isInvalidDecl())
7527 return ExceptSpec;
7528
7529 // Inherited constructor.
7530 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7531 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7532 // FIXME: Copying or moving the parameters could add extra exceptions to the
7533 // set, as could the default arguments for the inherited constructor. This
7534 // will be addressed when we implement the resolution of core issue 1351.
7535 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7536
7537 // Direct base-class constructors.
7538 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7539 BEnd = ClassDecl->bases_end();
7540 B != BEnd; ++B) {
7541 if (B->isVirtual()) // Handled below.
7542 continue;
7543
7544 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7545 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7546 if (BaseClassDecl == InheritedDecl)
7547 continue;
7548 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7549 if (Constructor)
7550 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7551 }
7552 }
7553
7554 // Virtual base-class constructors.
7555 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7556 BEnd = ClassDecl->vbases_end();
7557 B != BEnd; ++B) {
7558 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7559 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7560 if (BaseClassDecl == InheritedDecl)
7561 continue;
7562 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7563 if (Constructor)
7564 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7565 }
7566 }
7567
7568 // Field constructors.
7569 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7570 FEnd = ClassDecl->field_end();
7571 F != FEnd; ++F) {
7572 if (F->hasInClassInitializer()) {
7573 if (Expr *E = F->getInClassInitializer())
7574 ExceptSpec.CalledExpr(E);
7575 else if (!F->isInvalidDecl())
7576 Diag(CD->getLocation(),
7577 diag::err_in_class_initializer_references_def_ctor) << CD;
7578 } else if (const RecordType *RecordTy
7579 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7580 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7581 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7582 if (Constructor)
7583 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7584 }
7585 }
7586
Richard Smith07b0fdc2013-03-18 21:12:30 +00007587 return ExceptSpec;
7588}
7589
Richard Smithafb49182012-11-29 01:34:07 +00007590namespace {
7591/// RAII object to register a special member as being currently declared.
7592struct DeclaringSpecialMember {
7593 Sema &S;
7594 Sema::SpecialMemberDecl D;
7595 bool WasAlreadyBeingDeclared;
7596
7597 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7598 : S(S), D(RD, CSM) {
7599 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7600 if (WasAlreadyBeingDeclared)
7601 // This almost never happens, but if it does, ensure that our cache
7602 // doesn't contain a stale result.
7603 S.SpecialMemberCache.clear();
7604
7605 // FIXME: Register a note to be produced if we encounter an error while
7606 // declaring the special member.
7607 }
7608 ~DeclaringSpecialMember() {
7609 if (!WasAlreadyBeingDeclared)
7610 S.SpecialMembersBeingDeclared.erase(D);
7611 }
7612
7613 /// \brief Are we already trying to declare this special member?
7614 bool isAlreadyBeingDeclared() const {
7615 return WasAlreadyBeingDeclared;
7616 }
7617};
7618}
7619
Sean Hunt001cad92011-05-10 00:49:42 +00007620CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7621 CXXRecordDecl *ClassDecl) {
7622 // C++ [class.ctor]p5:
7623 // A default constructor for a class X is a constructor of class X
7624 // that can be called without an argument. If there is no
7625 // user-declared constructor for class X, a default constructor is
7626 // implicitly declared. An implicitly-declared default constructor
7627 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007628 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007629 "Should not build implicit default constructor!");
7630
Richard Smithafb49182012-11-29 01:34:07 +00007631 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7632 if (DSM.isAlreadyBeingDeclared())
7633 return 0;
7634
Richard Smith7756afa2012-06-10 05:43:50 +00007635 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7636 CXXDefaultConstructor,
7637 false);
7638
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007639 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007640 CanQualType ClassType
7641 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007642 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007643 DeclarationName Name
7644 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007645 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007646 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007647 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007648 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007649 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007650 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007651 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007652 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007653
7654 // Build an exception specification pointing back at this constructor.
7655 FunctionProtoType::ExtProtoInfo EPI;
7656 EPI.ExceptionSpecType = EST_Unevaluated;
7657 EPI.ExceptionSpecDecl = DefaultCon;
Jordan Rosebea522f2013-03-08 21:51:21 +00007658 DefaultCon->setType(Context.getFunctionType(Context.VoidTy,
7659 ArrayRef<QualType>(),
7660 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007661
Richard Smithbc2a35d2012-12-08 08:32:28 +00007662 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7663 // constructors is easy to compute.
7664 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7665
7666 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007667 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007668
Douglas Gregor18274032010-07-03 00:47:00 +00007669 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007670 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007671
Douglas Gregor23c94db2010-07-02 17:43:08 +00007672 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007673 PushOnScopeChains(DefaultCon, S, false);
7674 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007675
Douglas Gregor32df23e2010-07-01 22:02:46 +00007676 return DefaultCon;
7677}
7678
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007679void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7680 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007681 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007682 !Constructor->doesThisDeclarationHaveABody() &&
7683 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007684 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007685
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007686 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007687 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007688
Eli Friedman9a14db32012-10-18 20:14:08 +00007689 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007690 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007691 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007692 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007693 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007694 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007695 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007696 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007697 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007698
7699 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007700 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007701
7702 Constructor->setUsed();
7703 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007704
7705 if (ASTMutationListener *L = getASTMutationListener()) {
7706 L->CompletedImplicitDefinition(Constructor);
7707 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007708}
7709
Richard Smith7a614d82011-06-11 17:19:42 +00007710void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007711 // Check that any explicitly-defaulted methods have exception specifications
7712 // compatible with their implicit exception specifications.
7713 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007714}
7715
Richard Smith4841ca52013-04-10 05:48:59 +00007716namespace {
7717/// Information on inheriting constructors to declare.
7718class InheritingConstructorInfo {
7719public:
7720 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7721 : SemaRef(SemaRef), Derived(Derived) {
7722 // Mark the constructors that we already have in the derived class.
7723 //
7724 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7725 // unless there is a user-declared constructor with the same signature in
7726 // the class where the using-declaration appears.
7727 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7728 }
7729
7730 void inheritAll(CXXRecordDecl *RD) {
7731 visitAll(RD, &InheritingConstructorInfo::inherit);
7732 }
7733
7734private:
7735 /// Information about an inheriting constructor.
7736 struct InheritingConstructor {
7737 InheritingConstructor()
7738 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7739
7740 /// If \c true, a constructor with this signature is already declared
7741 /// in the derived class.
7742 bool DeclaredInDerived;
7743
7744 /// The constructor which is inherited.
7745 const CXXConstructorDecl *BaseCtor;
7746
7747 /// The derived constructor we declared.
7748 CXXConstructorDecl *DerivedCtor;
7749 };
7750
7751 /// Inheriting constructors with a given canonical type. There can be at
7752 /// most one such non-template constructor, and any number of templated
7753 /// constructors.
7754 struct InheritingConstructorsForType {
7755 InheritingConstructor NonTemplate;
7756 llvm::SmallVector<
7757 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7758
7759 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7760 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7761 TemplateParameterList *ParamList = FTD->getTemplateParameters();
7762 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7763 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7764 false, S.TPL_TemplateMatch))
7765 return Templates[I].second;
7766 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7767 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007768 }
Richard Smith4841ca52013-04-10 05:48:59 +00007769
7770 return NonTemplate;
7771 }
7772 };
7773
7774 /// Get or create the inheriting constructor record for a constructor.
7775 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7776 QualType CtorType) {
7777 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7778 .getEntry(SemaRef, Ctor);
7779 }
7780
7781 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7782
7783 /// Process all constructors for a class.
7784 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7785 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7786 CtorE = RD->ctor_end();
7787 CtorIt != CtorE; ++CtorIt)
7788 (this->*Callback)(*CtorIt);
7789 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7790 I(RD->decls_begin()), E(RD->decls_end());
7791 I != E; ++I) {
7792 const FunctionDecl *FD = (*I)->getTemplatedDecl();
7793 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7794 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007795 }
7796 }
Richard Smith4841ca52013-04-10 05:48:59 +00007797
7798 /// Note that a constructor (or constructor template) was declared in Derived.
7799 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7800 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7801 }
7802
7803 /// Inherit a single constructor.
7804 void inherit(const CXXConstructorDecl *Ctor) {
7805 const FunctionProtoType *CtorType =
7806 Ctor->getType()->castAs<FunctionProtoType>();
7807 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7808 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7809
7810 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7811
7812 // Core issue (no number yet): the ellipsis is always discarded.
7813 if (EPI.Variadic) {
7814 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7815 SemaRef.Diag(Ctor->getLocation(),
7816 diag::note_using_decl_constructor_ellipsis);
7817 EPI.Variadic = false;
7818 }
7819
7820 // Declare a constructor for each number of parameters.
7821 //
7822 // C++11 [class.inhctor]p1:
7823 // The candidate set of inherited constructors from the class X named in
7824 // the using-declaration consists of [... modulo defects ...] for each
7825 // constructor or constructor template of X, the set of constructors or
7826 // constructor templates that results from omitting any ellipsis parameter
7827 // specification and successively omitting parameters with a default
7828 // argument from the end of the parameter-type-list
7829 for (unsigned Params = std::max(minParamsToInherit(Ctor),
7830 Ctor->getMinRequiredArguments()),
7831 MaxParams = Ctor->getNumParams();
7832 Params <= MaxParams; ++Params)
7833 declareCtor(UsingLoc, Ctor,
7834 SemaRef.Context.getFunctionType(
7835 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7836 }
7837
7838 /// Find the using-declaration which specified that we should inherit the
7839 /// constructors of \p Base.
7840 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
7841 // No fancy lookup required; just look for the base constructor name
7842 // directly within the derived class.
7843 ASTContext &Context = SemaRef.Context;
7844 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
7845 Context.getCanonicalType(Context.getRecordType(Base)));
7846 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
7847 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
7848 }
7849
7850 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
7851 // C++11 [class.inhctor]p3:
7852 // [F]or each constructor template in the candidate set of inherited
7853 // constructors, a constructor template is implicitly declared
7854 if (Ctor->getDescribedFunctionTemplate())
7855 return 0;
7856
7857 // For each non-template constructor in the candidate set of inherited
7858 // constructors other than a constructor having no parameters or a
7859 // copy/move constructor having a single parameter, a constructor is
7860 // implicitly declared [...]
7861 if (Ctor->getNumParams() == 0)
7862 return 1;
7863 if (Ctor->isCopyOrMoveConstructor())
7864 return 2;
7865
7866 // Per discussion on core reflector, never inherit a constructor which
7867 // would become a default, copy, or move constructor of Derived either.
7868 const ParmVarDecl *PD = Ctor->getParamDecl(0);
7869 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
7870 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
7871 }
7872
7873 /// Declare a single inheriting constructor, inheriting the specified
7874 /// constructor, with the given type.
7875 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
7876 QualType DerivedType) {
7877 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
7878
7879 // C++11 [class.inhctor]p3:
7880 // ... a constructor is implicitly declared with the same constructor
7881 // characteristics unless there is a user-declared constructor with
7882 // the same signature in the class where the using-declaration appears
7883 if (Entry.DeclaredInDerived)
7884 return;
7885
7886 // C++11 [class.inhctor]p7:
7887 // If two using-declarations declare inheriting constructors with the
7888 // same signature, the program is ill-formed
7889 if (Entry.DerivedCtor) {
7890 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
7891 // Only diagnose this once per constructor.
7892 if (Entry.DerivedCtor->isInvalidDecl())
7893 return;
7894 Entry.DerivedCtor->setInvalidDecl();
7895
7896 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7897 SemaRef.Diag(BaseCtor->getLocation(),
7898 diag::note_using_decl_constructor_conflict_current_ctor);
7899 SemaRef.Diag(Entry.BaseCtor->getLocation(),
7900 diag::note_using_decl_constructor_conflict_previous_ctor);
7901 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
7902 diag::note_using_decl_constructor_conflict_previous_using);
7903 } else {
7904 // Core issue (no number): if the same inheriting constructor is
7905 // produced by multiple base class constructors from the same base
7906 // class, the inheriting constructor is defined as deleted.
7907 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
7908 }
7909
7910 return;
7911 }
7912
7913 ASTContext &Context = SemaRef.Context;
7914 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
7915 Context.getCanonicalType(Context.getRecordType(Derived)));
7916 DeclarationNameInfo NameInfo(Name, UsingLoc);
7917
7918 TemplateParameterList *TemplateParams = 0;
7919 if (const FunctionTemplateDecl *FTD =
7920 BaseCtor->getDescribedFunctionTemplate()) {
7921 TemplateParams = FTD->getTemplateParameters();
7922 // We're reusing template parameters from a different DeclContext. This
7923 // is questionable at best, but works out because the template depth in
7924 // both places is guaranteed to be 0.
7925 // FIXME: Rebuild the template parameters in the new context, and
7926 // transform the function type to refer to them.
7927 }
7928
7929 // Build type source info pointing at the using-declaration. This is
7930 // required by template instantiation.
7931 TypeSourceInfo *TInfo =
7932 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
7933 FunctionProtoTypeLoc ProtoLoc =
7934 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
7935
7936 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
7937 Context, Derived, UsingLoc, NameInfo, DerivedType,
7938 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
7939 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
7940
7941 // Build an unevaluated exception specification for this constructor.
7942 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
7943 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7944 EPI.ExceptionSpecType = EST_Unevaluated;
7945 EPI.ExceptionSpecDecl = DerivedCtor;
7946 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
7947 FPT->getArgTypes(), EPI));
7948
7949 // Build the parameter declarations.
7950 SmallVector<ParmVarDecl *, 16> ParamDecls;
7951 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
7952 TypeSourceInfo *TInfo =
7953 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
7954 ParmVarDecl *PD = ParmVarDecl::Create(
7955 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
7956 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
7957 PD->setScopeInfo(0, I);
7958 PD->setImplicit();
7959 ParamDecls.push_back(PD);
7960 ProtoLoc.setArg(I, PD);
7961 }
7962
7963 // Set up the new constructor.
7964 DerivedCtor->setAccess(BaseCtor->getAccess());
7965 DerivedCtor->setParams(ParamDecls);
7966 DerivedCtor->setInheritedConstructor(BaseCtor);
7967 if (BaseCtor->isDeleted())
7968 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
7969
7970 // If this is a constructor template, build the template declaration.
7971 if (TemplateParams) {
7972 FunctionTemplateDecl *DerivedTemplate =
7973 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
7974 TemplateParams, DerivedCtor);
7975 DerivedTemplate->setAccess(BaseCtor->getAccess());
7976 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
7977 Derived->addDecl(DerivedTemplate);
7978 } else {
7979 Derived->addDecl(DerivedCtor);
7980 }
7981
7982 Entry.BaseCtor = BaseCtor;
7983 Entry.DerivedCtor = DerivedCtor;
7984 }
7985
7986 Sema &SemaRef;
7987 CXXRecordDecl *Derived;
7988 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
7989 MapType Map;
7990};
7991}
7992
7993void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
7994 // Defer declaring the inheriting constructors until the class is
7995 // instantiated.
7996 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00007997 return;
7998
Richard Smith4841ca52013-04-10 05:48:59 +00007999 // Find base classes from which we might inherit constructors.
8000 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8001 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8002 BaseE = ClassDecl->bases_end();
8003 BaseIt != BaseE; ++BaseIt)
8004 if (BaseIt->getInheritConstructors())
8005 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008006
Richard Smith4841ca52013-04-10 05:48:59 +00008007 // Go no further if we're not inheriting any constructors.
8008 if (InheritedBases.empty())
8009 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008010
Richard Smith4841ca52013-04-10 05:48:59 +00008011 // Declare the inherited constructors.
8012 InheritingConstructorInfo ICI(*this, ClassDecl);
8013 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8014 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008015}
8016
Richard Smith07b0fdc2013-03-18 21:12:30 +00008017void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8018 CXXConstructorDecl *Constructor) {
8019 CXXRecordDecl *ClassDecl = Constructor->getParent();
8020 assert(Constructor->getInheritedConstructor() &&
8021 !Constructor->doesThisDeclarationHaveABody() &&
8022 !Constructor->isDeleted());
8023
8024 SynthesizedFunctionScope Scope(*this, Constructor);
8025 DiagnosticErrorTrap Trap(Diags);
8026 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8027 Trap.hasErrorOccurred()) {
8028 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8029 << Context.getTagDeclType(ClassDecl);
8030 Constructor->setInvalidDecl();
8031 return;
8032 }
8033
8034 SourceLocation Loc = Constructor->getLocation();
8035 Constructor->setBody(new (Context) CompoundStmt(Loc));
8036
8037 Constructor->setUsed();
8038 MarkVTableUsed(CurrentLocation, ClassDecl);
8039
8040 if (ASTMutationListener *L = getASTMutationListener()) {
8041 L->CompletedImplicitDefinition(Constructor);
8042 }
8043}
8044
8045
Sean Huntcb45a0f2011-05-12 22:46:25 +00008046Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008047Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8048 CXXRecordDecl *ClassDecl = MD->getParent();
8049
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008050 // C++ [except.spec]p14:
8051 // An implicitly declared special member function (Clause 12) shall have
8052 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008053 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008054 if (ClassDecl->isInvalidDecl())
8055 return ExceptSpec;
8056
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008057 // Direct base-class destructors.
8058 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8059 BEnd = ClassDecl->bases_end();
8060 B != BEnd; ++B) {
8061 if (B->isVirtual()) // Handled below.
8062 continue;
8063
8064 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008065 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008066 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008067 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008068
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008069 // Virtual base-class destructors.
8070 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8071 BEnd = ClassDecl->vbases_end();
8072 B != BEnd; ++B) {
8073 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008074 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008075 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008076 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008077
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008078 // Field destructors.
8079 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8080 FEnd = ClassDecl->field_end();
8081 F != FEnd; ++F) {
8082 if (const RecordType *RecordTy
8083 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008084 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008085 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008086 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008087
Sean Huntcb45a0f2011-05-12 22:46:25 +00008088 return ExceptSpec;
8089}
8090
8091CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8092 // C++ [class.dtor]p2:
8093 // If a class has no user-declared destructor, a destructor is
8094 // declared implicitly. An implicitly-declared destructor is an
8095 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008096 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008097
Richard Smithafb49182012-11-29 01:34:07 +00008098 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8099 if (DSM.isAlreadyBeingDeclared())
8100 return 0;
8101
Douglas Gregor4923aa22010-07-02 20:37:36 +00008102 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008103 CanQualType ClassType
8104 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008105 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008106 DeclarationName Name
8107 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008108 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008109 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008110 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8111 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008112 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008113 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008114 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008115 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008116
8117 // Build an exception specification pointing back at this destructor.
8118 FunctionProtoType::ExtProtoInfo EPI;
8119 EPI.ExceptionSpecType = EST_Unevaluated;
8120 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00008121 Destructor->setType(Context.getFunctionType(Context.VoidTy,
8122 ArrayRef<QualType>(),
8123 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008124
Richard Smithbc2a35d2012-12-08 08:32:28 +00008125 AddOverriddenMethods(ClassDecl, Destructor);
8126
8127 // We don't need to use SpecialMemberIsTrivial here; triviality for
8128 // destructors is easy to compute.
8129 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8130
8131 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008132 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008133
Douglas Gregor4923aa22010-07-02 20:37:36 +00008134 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008135 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008136
Douglas Gregor4923aa22010-07-02 20:37:36 +00008137 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008138 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008139 PushOnScopeChains(Destructor, S, false);
8140 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008141
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008142 return Destructor;
8143}
8144
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008145void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008146 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008147 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008148 !Destructor->doesThisDeclarationHaveABody() &&
8149 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008150 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008151 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008152 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008153
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008154 if (Destructor->isInvalidDecl())
8155 return;
8156
Eli Friedman9a14db32012-10-18 20:14:08 +00008157 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008158
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008159 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008160 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8161 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008162
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008163 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008164 Diag(CurrentLocation, diag::note_member_synthesized_at)
8165 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8166
8167 Destructor->setInvalidDecl();
8168 return;
8169 }
8170
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008171 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008172 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008173 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008174 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008175 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008176
8177 if (ASTMutationListener *L = getASTMutationListener()) {
8178 L->CompletedImplicitDefinition(Destructor);
8179 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008180}
8181
Richard Smitha4156b82012-04-21 18:42:51 +00008182/// \brief Perform any semantic analysis which needs to be delayed until all
8183/// pending class member declarations have been parsed.
8184void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008185 // If the context is an invalid C++ class, just suppress these checks.
8186 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8187 if (Record->isInvalidDecl()) {
8188 DelayedDestructorExceptionSpecChecks.clear();
8189 return;
8190 }
8191 }
8192
Richard Smitha4156b82012-04-21 18:42:51 +00008193 // Perform any deferred checking of exception specifications for virtual
8194 // destructors.
8195 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8196 i != e; ++i) {
8197 const CXXDestructorDecl *Dtor =
8198 DelayedDestructorExceptionSpecChecks[i].first;
8199 assert(!Dtor->getParent()->isDependentType() &&
8200 "Should not ever add destructors of templates into the list.");
8201 CheckOverridingFunctionExceptionSpec(Dtor,
8202 DelayedDestructorExceptionSpecChecks[i].second);
8203 }
8204 DelayedDestructorExceptionSpecChecks.clear();
8205}
8206
Richard Smithb9d0b762012-07-27 04:22:15 +00008207void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8208 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008209 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008210 "adjusting dtor exception specs was introduced in c++11");
8211
Sebastian Redl0ee33912011-05-19 05:13:44 +00008212 // C++11 [class.dtor]p3:
8213 // A declaration of a destructor that does not have an exception-
8214 // specification is implicitly considered to have the same exception-
8215 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008216 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008217 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008218 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008219 return;
8220
Chandler Carruth3f224b22011-09-20 04:55:26 +00008221 // Replace the destructor's type, building off the existing one. Fortunately,
8222 // the only thing of interest in the destructor type is its extended info.
8223 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008224 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8225 EPI.ExceptionSpecType = EST_Unevaluated;
8226 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00008227 Destructor->setType(Context.getFunctionType(Context.VoidTy,
8228 ArrayRef<QualType>(),
8229 EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008230
Sebastian Redl0ee33912011-05-19 05:13:44 +00008231 // FIXME: If the destructor has a body that could throw, and the newly created
8232 // spec doesn't allow exceptions, we should emit a warning, because this
8233 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008234 // However, we don't have a body or an exception specification yet, so it
8235 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008236}
8237
Richard Smith8c889532012-11-14 00:50:40 +00008238/// When generating a defaulted copy or move assignment operator, if a field
8239/// should be copied with __builtin_memcpy rather than via explicit assignments,
8240/// do so. This optimization only applies for arrays of scalars, and for arrays
8241/// of class type where the selected copy/move-assignment operator is trivial.
8242static StmtResult
8243buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8244 Expr *To, Expr *From) {
8245 // Compute the size of the memory buffer to be copied.
8246 QualType SizeType = S.Context.getSizeType();
8247 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8248 S.Context.getTypeSizeInChars(T).getQuantity());
8249
8250 // Take the address of the field references for "from" and "to". We
8251 // directly construct UnaryOperators here because semantic analysis
8252 // does not permit us to take the address of an xvalue.
8253 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8254 S.Context.getPointerType(From->getType()),
8255 VK_RValue, OK_Ordinary, Loc);
8256 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8257 S.Context.getPointerType(To->getType()),
8258 VK_RValue, OK_Ordinary, Loc);
8259
8260 const Type *E = T->getBaseElementTypeUnsafe();
8261 bool NeedsCollectableMemCpy =
8262 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8263
8264 // Create a reference to the __builtin_objc_memmove_collectable function
8265 StringRef MemCpyName = NeedsCollectableMemCpy ?
8266 "__builtin_objc_memmove_collectable" :
8267 "__builtin_memcpy";
8268 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8269 Sema::LookupOrdinaryName);
8270 S.LookupName(R, S.TUScope, true);
8271
8272 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8273 if (!MemCpy)
8274 // Something went horribly wrong earlier, and we will have complained
8275 // about it.
8276 return StmtError();
8277
8278 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8279 VK_RValue, Loc, 0);
8280 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8281
8282 Expr *CallArgs[] = {
8283 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8284 };
8285 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8286 Loc, CallArgs, Loc);
8287
8288 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8289 return S.Owned(Call.takeAs<Stmt>());
8290}
8291
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008292/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008293/// \c To.
8294///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008295/// This routine is used to copy/move the members of a class with an
8296/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008297/// copied are arrays, this routine builds for loops to copy them.
8298///
8299/// \param S The Sema object used for type-checking.
8300///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008301/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008302///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008303/// \param T The type of the expressions being copied/moved. Both expressions
8304/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008305///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008306/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008307///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008308/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008309///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008310/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008311/// Otherwise, it's a non-static member subobject.
8312///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008313/// \param Copying Whether we're copying or moving.
8314///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008315/// \param Depth Internal parameter recording the depth of the recursion.
8316///
Richard Smith8c889532012-11-14 00:50:40 +00008317/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8318/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008319static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008320buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8321 Expr *To, Expr *From,
8322 bool CopyingBaseSubobject, bool Copying,
8323 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008324 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008325 // Each subobject is assigned in the manner appropriate to its type:
8326 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008327 // - if the subobject is of class type, as if by a call to operator= with
8328 // the subobject as the object expression and the corresponding
8329 // subobject of x as a single function argument (as if by explicit
8330 // qualification; that is, ignoring any possible virtual overriding
8331 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008332 //
8333 // C++03 [class.copy]p13:
8334 // - if the subobject is of class type, the copy assignment operator for
8335 // the class is used (as if by explicit qualification; that is,
8336 // ignoring any possible virtual overriding functions in more derived
8337 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008338 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8339 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008340
Douglas Gregor06a9f362010-05-01 20:49:11 +00008341 // Look for operator=.
8342 DeclarationName Name
8343 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8344 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8345 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008346
Richard Smith044c8aa2012-11-13 00:54:12 +00008347 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8348 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008349 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008350 LookupResult::Filter F = OpLookup.makeFilter();
8351 while (F.hasNext()) {
8352 NamedDecl *D = F.next();
8353 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8354 if (Method->isCopyAssignmentOperator() ||
8355 (!Copying && Method->isMoveAssignmentOperator()))
8356 continue;
8357
8358 F.erase();
8359 }
8360 F.done();
John McCallb0207482010-03-16 06:11:48 +00008361 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008362
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008363 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008364 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008365 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008366 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008367 // ambiguities), we need to cast "this" to that subobject type; to
8368 // ensure that we don't go through the virtual call mechanism, we need
8369 // to qualify the operator= name with the base class (see below). However,
8370 // this means that if the base class has a protected copy assignment
8371 // operator, the protected member access check will fail. So, we
8372 // rewrite "protected" access to "public" access in this case, since we
8373 // know by construction that we're calling from a derived class.
8374 if (CopyingBaseSubobject) {
8375 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8376 L != LEnd; ++L) {
8377 if (L.getAccess() == AS_protected)
8378 L.setAccess(AS_public);
8379 }
8380 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008381
Douglas Gregor06a9f362010-05-01 20:49:11 +00008382 // Create the nested-name-specifier that will be used to qualify the
8383 // reference to operator=; this is required to suppress the virtual
8384 // call mechanism.
8385 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008386 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008387 SS.MakeTrivial(S.Context,
8388 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008389 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008390 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008391
Douglas Gregor06a9f362010-05-01 20:49:11 +00008392 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008393 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008394 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008395 /*TemplateKWLoc=*/SourceLocation(),
8396 /*FirstQualifierInScope=*/0,
8397 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008398 /*TemplateArgs=*/0,
8399 /*SuppressQualifierCheck=*/true);
8400 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008401 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008402
Douglas Gregor06a9f362010-05-01 20:49:11 +00008403 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008404
Richard Smith044c8aa2012-11-13 00:54:12 +00008405 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008406 OpEqualRef.takeAs<Expr>(),
8407 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008408 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008409 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008410
Richard Smith8c889532012-11-14 00:50:40 +00008411 // If we built a call to a trivial 'operator=' while copying an array,
8412 // bail out. We'll replace the whole shebang with a memcpy.
8413 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8414 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8415 return StmtResult((Stmt*)0);
8416
Richard Smith044c8aa2012-11-13 00:54:12 +00008417 // Convert to an expression-statement, and clean up any produced
8418 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008419 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008420 }
John McCallb0207482010-03-16 06:11:48 +00008421
Richard Smith044c8aa2012-11-13 00:54:12 +00008422 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008423 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008424 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008425 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008426 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008427 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008428 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008429 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008430 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008431
8432 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008433 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008434
Douglas Gregor06a9f362010-05-01 20:49:11 +00008435 // Construct a loop over the array bounds, e.g.,
8436 //
8437 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8438 //
8439 // that will copy each of the array elements.
8440 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008441
Douglas Gregor06a9f362010-05-01 20:49:11 +00008442 // Create the iteration variable.
8443 IdentifierInfo *IterationVarName = 0;
8444 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008445 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008446 llvm::raw_svector_ostream OS(Str);
8447 OS << "__i" << Depth;
8448 IterationVarName = &S.Context.Idents.get(OS.str());
8449 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008450 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008451 IterationVarName, SizeType,
8452 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008453 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008454
Douglas Gregor06a9f362010-05-01 20:49:11 +00008455 // Initialize the iteration variable to zero.
8456 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008457 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008458
8459 // Create a reference to the iteration variable; we'll use this several
8460 // times throughout.
8461 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008462 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008463 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008464 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8465 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8466
Douglas Gregor06a9f362010-05-01 20:49:11 +00008467 // Create the DeclStmt that holds the iteration variable.
8468 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008469
Douglas Gregor06a9f362010-05-01 20:49:11 +00008470 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008471 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008472 IterationVarRefRVal,
8473 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008474 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008475 IterationVarRefRVal,
8476 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008477 if (!Copying) // Cast to rvalue
8478 From = CastForMoving(S, From);
8479
8480 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008481 StmtResult Copy =
8482 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8483 To, From, CopyingBaseSubobject,
8484 Copying, Depth + 1);
8485 // Bail out if copying fails or if we determined that we should use memcpy.
8486 if (Copy.isInvalid() || !Copy.get())
8487 return Copy;
8488
8489 // Create the comparison against the array bound.
8490 llvm::APInt Upper
8491 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8492 Expr *Comparison
8493 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8494 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8495 BO_NE, S.Context.BoolTy,
8496 VK_RValue, OK_Ordinary, Loc, false);
8497
8498 // Create the pre-increment of the iteration variable.
8499 Expr *Increment
8500 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8501 VK_LValue, OK_Ordinary, Loc);
8502
Douglas Gregor06a9f362010-05-01 20:49:11 +00008503 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008504 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008505 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008506 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008507 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008508}
8509
Richard Smith8c889532012-11-14 00:50:40 +00008510static StmtResult
8511buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8512 Expr *To, Expr *From,
8513 bool CopyingBaseSubobject, bool Copying) {
8514 // Maybe we should use a memcpy?
8515 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8516 T.isTriviallyCopyableType(S.Context))
8517 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8518
8519 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8520 CopyingBaseSubobject,
8521 Copying, 0));
8522
8523 // If we ended up picking a trivial assignment operator for an array of a
8524 // non-trivially-copyable class type, just emit a memcpy.
8525 if (!Result.isInvalid() && !Result.get())
8526 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8527
8528 return Result;
8529}
8530
Richard Smithb9d0b762012-07-27 04:22:15 +00008531Sema::ImplicitExceptionSpecification
8532Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8533 CXXRecordDecl *ClassDecl = MD->getParent();
8534
8535 ImplicitExceptionSpecification ExceptSpec(*this);
8536 if (ClassDecl->isInvalidDecl())
8537 return ExceptSpec;
8538
8539 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8540 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8541 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8542
Douglas Gregorb87786f2010-07-01 17:48:08 +00008543 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008544 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008545 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008546
8547 // It is unspecified whether or not an implicit copy assignment operator
8548 // attempts to deduplicate calls to assignment operators of virtual bases are
8549 // made. As such, this exception specification is effectively unspecified.
8550 // Based on a similar decision made for constness in C++0x, we're erring on
8551 // the side of assuming such calls to be made regardless of whether they
8552 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008553 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8554 BaseEnd = ClassDecl->bases_end();
8555 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008556 if (Base->isVirtual())
8557 continue;
8558
Douglas Gregora376d102010-07-02 21:50:04 +00008559 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008560 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008561 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8562 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008563 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008564 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008565
8566 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8567 BaseEnd = ClassDecl->vbases_end();
8568 Base != BaseEnd; ++Base) {
8569 CXXRecordDecl *BaseClassDecl
8570 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8571 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8572 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008573 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008574 }
8575
Douglas Gregorb87786f2010-07-01 17:48:08 +00008576 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8577 FieldEnd = ClassDecl->field_end();
8578 Field != FieldEnd;
8579 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008580 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008581 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8582 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008583 LookupCopyingAssignment(FieldClassDecl,
8584 ArgQuals | FieldType.getCVRQualifiers(),
8585 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008586 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008587 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008588 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008589
Richard Smithb9d0b762012-07-27 04:22:15 +00008590 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008591}
8592
8593CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8594 // Note: The following rules are largely analoguous to the copy
8595 // constructor rules. Note that virtual bases are not taken into account
8596 // for determining the argument type of the operator. Note also that
8597 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008598 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008599
Richard Smithafb49182012-11-29 01:34:07 +00008600 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8601 if (DSM.isAlreadyBeingDeclared())
8602 return 0;
8603
Sean Hunt30de05c2011-05-14 05:23:20 +00008604 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8605 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008606 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008607 ArgType = ArgType.withConst();
8608 ArgType = Context.getLValueReferenceType(ArgType);
8609
Douglas Gregord3c35902010-07-01 16:36:15 +00008610 // An implicitly-declared copy assignment operator is an inline public
8611 // member of its class.
8612 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008613 SourceLocation ClassLoc = ClassDecl->getLocation();
8614 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008615 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008616 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008617 /*TInfo=*/0,
8618 /*StorageClass=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008619 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008620 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008621 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008622 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008623 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008624
8625 // Build an exception specification pointing back at this member.
8626 FunctionProtoType::ExtProtoInfo EPI;
8627 EPI.ExceptionSpecType = EST_Unevaluated;
8628 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008629 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008630
Douglas Gregord3c35902010-07-01 16:36:15 +00008631 // Add the parameter to the operator.
8632 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008633 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008634 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008635 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008636 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008637
Richard Smithbc2a35d2012-12-08 08:32:28 +00008638 AddOverriddenMethods(ClassDecl, CopyAssignment);
8639
8640 CopyAssignment->setTrivial(
8641 ClassDecl->needsOverloadResolutionForCopyAssignment()
8642 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8643 : ClassDecl->hasTrivialCopyAssignment());
8644
Nico Weberafcc96a2012-01-23 03:19:29 +00008645 // C++0x [class.copy]p19:
8646 // .... If the class definition does not explicitly declare a copy
8647 // assignment operator, there is no user-declared move constructor, and
8648 // there is no user-declared move assignment operator, a copy assignment
8649 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008650 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008651 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008652
Richard Smithbc2a35d2012-12-08 08:32:28 +00008653 // Note that we have added this copy-assignment operator.
8654 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8655
8656 if (Scope *S = getScopeForContext(ClassDecl))
8657 PushOnScopeChains(CopyAssignment, S, false);
8658 ClassDecl->addDecl(CopyAssignment);
8659
Douglas Gregord3c35902010-07-01 16:36:15 +00008660 return CopyAssignment;
8661}
8662
Douglas Gregor06a9f362010-05-01 20:49:11 +00008663void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8664 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008665 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008666 CopyAssignOperator->isOverloadedOperator() &&
8667 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008668 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8669 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008670 "DefineImplicitCopyAssignment called for wrong function");
8671
8672 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8673
8674 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8675 CopyAssignOperator->setInvalidDecl();
8676 return;
8677 }
8678
8679 CopyAssignOperator->setUsed();
8680
Eli Friedman9a14db32012-10-18 20:14:08 +00008681 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008682 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008683
8684 // C++0x [class.copy]p30:
8685 // The implicitly-defined or explicitly-defaulted copy assignment operator
8686 // for a non-union class X performs memberwise copy assignment of its
8687 // subobjects. The direct base classes of X are assigned first, in the
8688 // order of their declaration in the base-specifier-list, and then the
8689 // immediate non-static data members of X are assigned, in the order in
8690 // which they were declared in the class definition.
8691
8692 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008693 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008694
8695 // The parameter for the "other" object, which we are copying from.
8696 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8697 Qualifiers OtherQuals = Other->getType().getQualifiers();
8698 QualType OtherRefType = Other->getType();
8699 if (const LValueReferenceType *OtherRef
8700 = OtherRefType->getAs<LValueReferenceType>()) {
8701 OtherRefType = OtherRef->getPointeeType();
8702 OtherQuals = OtherRefType.getQualifiers();
8703 }
8704
8705 // Our location for everything implicitly-generated.
8706 SourceLocation Loc = CopyAssignOperator->getLocation();
8707
8708 // Construct a reference to the "other" object. We'll be using this
8709 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008710 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008711 assert(OtherRef && "Reference to parameter cannot fail!");
8712
8713 // Construct the "this" pointer. We'll be using this throughout the generated
8714 // ASTs.
8715 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8716 assert(This && "Reference to this cannot fail!");
8717
8718 // Assign base classes.
8719 bool Invalid = false;
8720 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8721 E = ClassDecl->bases_end(); Base != E; ++Base) {
8722 // Form the assignment:
8723 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8724 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008725 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008726 Invalid = true;
8727 continue;
8728 }
8729
John McCallf871d0c2010-08-07 06:22:56 +00008730 CXXCastPath BasePath;
8731 BasePath.push_back(Base);
8732
Douglas Gregor06a9f362010-05-01 20:49:11 +00008733 // Construct the "from" expression, which is an implicit cast to the
8734 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008735 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008736 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8737 CK_UncheckedDerivedToBase,
8738 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008739
8740 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008741 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008742
8743 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008744 To = ImpCastExprToType(To.take(),
8745 Context.getCVRQualifiedType(BaseType,
8746 CopyAssignOperator->getTypeQualifiers()),
8747 CK_UncheckedDerivedToBase,
8748 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008749
8750 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008751 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008752 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008753 /*CopyingBaseSubobject=*/true,
8754 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008755 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008756 Diag(CurrentLocation, diag::note_member_synthesized_at)
8757 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8758 CopyAssignOperator->setInvalidDecl();
8759 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008760 }
8761
8762 // Success! Record the copy.
8763 Statements.push_back(Copy.takeAs<Expr>());
8764 }
8765
Douglas Gregor06a9f362010-05-01 20:49:11 +00008766 // Assign non-static members.
8767 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8768 FieldEnd = ClassDecl->field_end();
8769 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008770 if (Field->isUnnamedBitfield())
8771 continue;
8772
Douglas Gregor06a9f362010-05-01 20:49:11 +00008773 // Check for members of reference type; we can't copy those.
8774 if (Field->getType()->isReferenceType()) {
8775 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8776 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8777 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008778 Diag(CurrentLocation, diag::note_member_synthesized_at)
8779 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008780 Invalid = true;
8781 continue;
8782 }
8783
8784 // Check for members of const-qualified, non-class type.
8785 QualType BaseType = Context.getBaseElementType(Field->getType());
8786 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8787 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8788 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8789 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008790 Diag(CurrentLocation, diag::note_member_synthesized_at)
8791 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008792 Invalid = true;
8793 continue;
8794 }
John McCallb77115d2011-06-17 00:18:42 +00008795
8796 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008797 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8798 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008799
8800 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008801 if (FieldType->isIncompleteArrayType()) {
8802 assert(ClassDecl->hasFlexibleArrayMember() &&
8803 "Incomplete array type is not valid");
8804 continue;
8805 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008806
8807 // Build references to the field in the object we're copying from and to.
8808 CXXScopeSpec SS; // Intentionally empty
8809 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8810 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008811 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008812 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008813 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008814 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008815 SS, SourceLocation(), 0,
8816 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008817 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008818 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008819 SS, SourceLocation(), 0,
8820 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008821 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8822 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008823
Douglas Gregor06a9f362010-05-01 20:49:11 +00008824 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008825 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008826 To.get(), From.get(),
8827 /*CopyingBaseSubobject=*/false,
8828 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008829 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008830 Diag(CurrentLocation, diag::note_member_synthesized_at)
8831 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8832 CopyAssignOperator->setInvalidDecl();
8833 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008834 }
8835
8836 // Success! Record the copy.
8837 Statements.push_back(Copy.takeAs<Stmt>());
8838 }
8839
8840 if (!Invalid) {
8841 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008842 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008843
John McCall60d7b3a2010-08-24 06:29:42 +00008844 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008845 if (Return.isInvalid())
8846 Invalid = true;
8847 else {
8848 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008849
8850 if (Trap.hasErrorOccurred()) {
8851 Diag(CurrentLocation, diag::note_member_synthesized_at)
8852 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8853 Invalid = true;
8854 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008855 }
8856 }
8857
8858 if (Invalid) {
8859 CopyAssignOperator->setInvalidDecl();
8860 return;
8861 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008862
8863 StmtResult Body;
8864 {
8865 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008866 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008867 /*isStmtExpr=*/false);
8868 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8869 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008870 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008871
8872 if (ASTMutationListener *L = getASTMutationListener()) {
8873 L->CompletedImplicitDefinition(CopyAssignOperator);
8874 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008875}
8876
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008877Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008878Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8879 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008880
Richard Smithb9d0b762012-07-27 04:22:15 +00008881 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008882 if (ClassDecl->isInvalidDecl())
8883 return ExceptSpec;
8884
8885 // C++0x [except.spec]p14:
8886 // An implicitly declared special member function (Clause 12) shall have an
8887 // exception-specification. [...]
8888
8889 // It is unspecified whether or not an implicit move assignment operator
8890 // attempts to deduplicate calls to assignment operators of virtual bases are
8891 // made. As such, this exception specification is effectively unspecified.
8892 // Based on a similar decision made for constness in C++0x, we're erring on
8893 // the side of assuming such calls to be made regardless of whether they
8894 // actually happen.
8895 // Note that a move constructor is not implicitly declared when there are
8896 // virtual bases, but it can still be user-declared and explicitly defaulted.
8897 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8898 BaseEnd = ClassDecl->bases_end();
8899 Base != BaseEnd; ++Base) {
8900 if (Base->isVirtual())
8901 continue;
8902
8903 CXXRecordDecl *BaseClassDecl
8904 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8905 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008906 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008907 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008908 }
8909
8910 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8911 BaseEnd = ClassDecl->vbases_end();
8912 Base != BaseEnd; ++Base) {
8913 CXXRecordDecl *BaseClassDecl
8914 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8915 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008916 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008917 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008918 }
8919
8920 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8921 FieldEnd = ClassDecl->field_end();
8922 Field != FieldEnd;
8923 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008924 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008925 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008926 if (CXXMethodDecl *MoveAssign =
8927 LookupMovingAssignment(FieldClassDecl,
8928 FieldType.getCVRQualifiers(),
8929 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008930 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008931 }
8932 }
8933
8934 return ExceptSpec;
8935}
8936
Richard Smith1c931be2012-04-02 18:40:40 +00008937/// Determine whether the class type has any direct or indirect virtual base
8938/// classes which have a non-trivial move assignment operator.
8939static bool
8940hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8941 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8942 BaseEnd = ClassDecl->vbases_end();
8943 Base != BaseEnd; ++Base) {
8944 CXXRecordDecl *BaseClass =
8945 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8946
8947 // Try to declare the move assignment. If it would be deleted, then the
8948 // class does not have a non-trivial move assignment.
8949 if (BaseClass->needsImplicitMoveAssignment())
8950 S.DeclareImplicitMoveAssignment(BaseClass);
8951
Richard Smith426391c2012-11-16 00:53:38 +00008952 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008953 return true;
8954 }
8955
8956 return false;
8957}
8958
8959/// Determine whether the given type either has a move constructor or is
8960/// trivially copyable.
8961static bool
8962hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8963 Type = S.Context.getBaseElementType(Type);
8964
8965 // FIXME: Technically, non-trivially-copyable non-class types, such as
8966 // reference types, are supposed to return false here, but that appears
8967 // to be a standard defect.
8968 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008969 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008970 return true;
8971
8972 if (Type.isTriviallyCopyableType(S.Context))
8973 return true;
8974
8975 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008976 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8977 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008978 if (ClassDecl->needsImplicitMoveConstructor())
8979 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008980 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008981 }
8982
Richard Smithe5411b72012-12-01 02:35:44 +00008983 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8984 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008985 if (ClassDecl->needsImplicitMoveAssignment())
8986 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008987 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008988}
8989
8990/// Determine whether all non-static data members and direct or virtual bases
8991/// of class \p ClassDecl have either a move operation, or are trivially
8992/// copyable.
8993static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8994 bool IsConstructor) {
8995 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8996 BaseEnd = ClassDecl->bases_end();
8997 Base != BaseEnd; ++Base) {
8998 if (Base->isVirtual())
8999 continue;
9000
9001 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9002 return false;
9003 }
9004
9005 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9006 BaseEnd = ClassDecl->vbases_end();
9007 Base != BaseEnd; ++Base) {
9008 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9009 return false;
9010 }
9011
9012 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9013 FieldEnd = ClassDecl->field_end();
9014 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009015 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009016 return false;
9017 }
9018
9019 return true;
9020}
9021
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009022CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009023 // C++11 [class.copy]p20:
9024 // If the definition of a class X does not explicitly declare a move
9025 // assignment operator, one will be implicitly declared as defaulted
9026 // if and only if:
9027 //
9028 // - [first 4 bullets]
9029 assert(ClassDecl->needsImplicitMoveAssignment());
9030
Richard Smithafb49182012-11-29 01:34:07 +00009031 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9032 if (DSM.isAlreadyBeingDeclared())
9033 return 0;
9034
Richard Smith1c931be2012-04-02 18:40:40 +00009035 // [Checked after we build the declaration]
9036 // - the move assignment operator would not be implicitly defined as
9037 // deleted,
9038
9039 // [DR1402]:
9040 // - X has no direct or indirect virtual base class with a non-trivial
9041 // move assignment operator, and
9042 // - each of X's non-static data members and direct or virtual base classes
9043 // has a type that either has a move assignment operator or is trivially
9044 // copyable.
9045 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9046 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9047 ClassDecl->setFailedImplicitMoveAssignment();
9048 return 0;
9049 }
9050
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009051 // Note: The following rules are largely analoguous to the move
9052 // constructor rules.
9053
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009054 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9055 QualType RetType = Context.getLValueReferenceType(ArgType);
9056 ArgType = Context.getRValueReferenceType(ArgType);
9057
9058 // An implicitly-declared move assignment operator is an inline public
9059 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009060 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9061 SourceLocation ClassLoc = ClassDecl->getLocation();
9062 DeclarationNameInfo NameInfo(Name, ClassLoc);
9063 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00009064 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009065 /*TInfo=*/0,
9066 /*StorageClass=*/SC_None,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009067 /*isInline=*/true,
9068 /*isConstexpr=*/false,
9069 SourceLocation());
9070 MoveAssignment->setAccess(AS_public);
9071 MoveAssignment->setDefaulted();
9072 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009073
Richard Smithb9d0b762012-07-27 04:22:15 +00009074 // Build an exception specification pointing back at this member.
9075 FunctionProtoType::ExtProtoInfo EPI;
9076 EPI.ExceptionSpecType = EST_Unevaluated;
9077 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009078 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009079
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009080 // Add the parameter to the operator.
9081 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9082 ClassLoc, ClassLoc, /*Id=*/0,
9083 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009084 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009085 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009086
Richard Smithbc2a35d2012-12-08 08:32:28 +00009087 AddOverriddenMethods(ClassDecl, MoveAssignment);
9088
9089 MoveAssignment->setTrivial(
9090 ClassDecl->needsOverloadResolutionForMoveAssignment()
9091 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9092 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009093
9094 // C++0x [class.copy]p9:
9095 // If the definition of a class X does not explicitly declare a move
9096 // assignment operator, one will be implicitly declared as defaulted if and
9097 // only if:
9098 // [...]
9099 // - the move assignment operator would not be implicitly defined as
9100 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009101 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009102 // Cache this result so that we don't try to generate this over and over
9103 // on every lookup, leaking memory and wasting time.
9104 ClassDecl->setFailedImplicitMoveAssignment();
9105 return 0;
9106 }
9107
Richard Smithbc2a35d2012-12-08 08:32:28 +00009108 // Note that we have added this copy-assignment operator.
9109 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9110
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009111 if (Scope *S = getScopeForContext(ClassDecl))
9112 PushOnScopeChains(MoveAssignment, S, false);
9113 ClassDecl->addDecl(MoveAssignment);
9114
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009115 return MoveAssignment;
9116}
9117
9118void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9119 CXXMethodDecl *MoveAssignOperator) {
9120 assert((MoveAssignOperator->isDefaulted() &&
9121 MoveAssignOperator->isOverloadedOperator() &&
9122 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009123 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9124 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009125 "DefineImplicitMoveAssignment called for wrong function");
9126
9127 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9128
9129 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9130 MoveAssignOperator->setInvalidDecl();
9131 return;
9132 }
9133
9134 MoveAssignOperator->setUsed();
9135
Eli Friedman9a14db32012-10-18 20:14:08 +00009136 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009137 DiagnosticErrorTrap Trap(Diags);
9138
9139 // C++0x [class.copy]p28:
9140 // The implicitly-defined or move assignment operator for a non-union class
9141 // X performs memberwise move assignment of its subobjects. The direct base
9142 // classes of X are assigned first, in the order of their declaration in the
9143 // base-specifier-list, and then the immediate non-static data members of X
9144 // are assigned, in the order in which they were declared in the class
9145 // definition.
9146
9147 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009148 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009149
9150 // The parameter for the "other" object, which we are move from.
9151 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9152 QualType OtherRefType = Other->getType()->
9153 getAs<RValueReferenceType>()->getPointeeType();
9154 assert(OtherRefType.getQualifiers() == 0 &&
9155 "Bad argument type of defaulted move assignment");
9156
9157 // Our location for everything implicitly-generated.
9158 SourceLocation Loc = MoveAssignOperator->getLocation();
9159
9160 // Construct a reference to the "other" object. We'll be using this
9161 // throughout the generated ASTs.
9162 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9163 assert(OtherRef && "Reference to parameter cannot fail!");
9164 // Cast to rvalue.
9165 OtherRef = CastForMoving(*this, OtherRef);
9166
9167 // Construct the "this" pointer. We'll be using this throughout the generated
9168 // ASTs.
9169 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9170 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009171
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009172 // Assign base classes.
9173 bool Invalid = false;
9174 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9175 E = ClassDecl->bases_end(); Base != E; ++Base) {
9176 // Form the assignment:
9177 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9178 QualType BaseType = Base->getType().getUnqualifiedType();
9179 if (!BaseType->isRecordType()) {
9180 Invalid = true;
9181 continue;
9182 }
9183
9184 CXXCastPath BasePath;
9185 BasePath.push_back(Base);
9186
9187 // Construct the "from" expression, which is an implicit cast to the
9188 // appropriately-qualified base type.
9189 Expr *From = OtherRef;
9190 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009191 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009192
9193 // Dereference "this".
9194 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9195
9196 // Implicitly cast "this" to the appropriately-qualified base type.
9197 To = ImpCastExprToType(To.take(),
9198 Context.getCVRQualifiedType(BaseType,
9199 MoveAssignOperator->getTypeQualifiers()),
9200 CK_UncheckedDerivedToBase,
9201 VK_LValue, &BasePath);
9202
9203 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009204 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009205 To.get(), From,
9206 /*CopyingBaseSubobject=*/true,
9207 /*Copying=*/false);
9208 if (Move.isInvalid()) {
9209 Diag(CurrentLocation, diag::note_member_synthesized_at)
9210 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9211 MoveAssignOperator->setInvalidDecl();
9212 return;
9213 }
9214
9215 // Success! Record the move.
9216 Statements.push_back(Move.takeAs<Expr>());
9217 }
9218
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009219 // Assign non-static members.
9220 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9221 FieldEnd = ClassDecl->field_end();
9222 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009223 if (Field->isUnnamedBitfield())
9224 continue;
9225
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009226 // Check for members of reference type; we can't move those.
9227 if (Field->getType()->isReferenceType()) {
9228 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9229 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9230 Diag(Field->getLocation(), diag::note_declared_at);
9231 Diag(CurrentLocation, diag::note_member_synthesized_at)
9232 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9233 Invalid = true;
9234 continue;
9235 }
9236
9237 // Check for members of const-qualified, non-class type.
9238 QualType BaseType = Context.getBaseElementType(Field->getType());
9239 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9240 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9241 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9242 Diag(Field->getLocation(), diag::note_declared_at);
9243 Diag(CurrentLocation, diag::note_member_synthesized_at)
9244 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9245 Invalid = true;
9246 continue;
9247 }
9248
9249 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009250 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9251 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009252
9253 QualType FieldType = Field->getType().getNonReferenceType();
9254 if (FieldType->isIncompleteArrayType()) {
9255 assert(ClassDecl->hasFlexibleArrayMember() &&
9256 "Incomplete array type is not valid");
9257 continue;
9258 }
9259
9260 // Build references to the field in the object we're copying from and to.
9261 CXXScopeSpec SS; // Intentionally empty
9262 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9263 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009264 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009265 MemberLookup.resolveKind();
9266 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9267 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009268 SS, SourceLocation(), 0,
9269 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009270 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9271 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009272 SS, SourceLocation(), 0,
9273 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009274 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9275 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9276
9277 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9278 "Member reference with rvalue base must be rvalue except for reference "
9279 "members, which aren't allowed for move assignment.");
9280
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009281 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009282 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009283 To.get(), From.get(),
9284 /*CopyingBaseSubobject=*/false,
9285 /*Copying=*/false);
9286 if (Move.isInvalid()) {
9287 Diag(CurrentLocation, diag::note_member_synthesized_at)
9288 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9289 MoveAssignOperator->setInvalidDecl();
9290 return;
9291 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009292
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009293 // Success! Record the copy.
9294 Statements.push_back(Move.takeAs<Stmt>());
9295 }
9296
9297 if (!Invalid) {
9298 // Add a "return *this;"
9299 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9300
9301 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9302 if (Return.isInvalid())
9303 Invalid = true;
9304 else {
9305 Statements.push_back(Return.takeAs<Stmt>());
9306
9307 if (Trap.hasErrorOccurred()) {
9308 Diag(CurrentLocation, diag::note_member_synthesized_at)
9309 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9310 Invalid = true;
9311 }
9312 }
9313 }
9314
9315 if (Invalid) {
9316 MoveAssignOperator->setInvalidDecl();
9317 return;
9318 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009319
9320 StmtResult Body;
9321 {
9322 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009323 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009324 /*isStmtExpr=*/false);
9325 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9326 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009327 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9328
9329 if (ASTMutationListener *L = getASTMutationListener()) {
9330 L->CompletedImplicitDefinition(MoveAssignOperator);
9331 }
9332}
9333
Richard Smithb9d0b762012-07-27 04:22:15 +00009334Sema::ImplicitExceptionSpecification
9335Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9336 CXXRecordDecl *ClassDecl = MD->getParent();
9337
9338 ImplicitExceptionSpecification ExceptSpec(*this);
9339 if (ClassDecl->isInvalidDecl())
9340 return ExceptSpec;
9341
9342 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9343 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9344 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9345
Douglas Gregor0d405db2010-07-01 20:59:04 +00009346 // C++ [except.spec]p14:
9347 // An implicitly declared special member function (Clause 12) shall have an
9348 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009349 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9350 BaseEnd = ClassDecl->bases_end();
9351 Base != BaseEnd;
9352 ++Base) {
9353 // Virtual bases are handled below.
9354 if (Base->isVirtual())
9355 continue;
9356
Douglas Gregor22584312010-07-02 23:41:54 +00009357 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009358 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009359 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009360 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009361 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009362 }
9363 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9364 BaseEnd = ClassDecl->vbases_end();
9365 Base != BaseEnd;
9366 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009367 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009368 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009369 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009370 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009371 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009372 }
9373 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9374 FieldEnd = ClassDecl->field_end();
9375 Field != FieldEnd;
9376 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009377 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009378 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9379 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009380 LookupCopyingConstructor(FieldClassDecl,
9381 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009382 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009383 }
9384 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009385
Richard Smithb9d0b762012-07-27 04:22:15 +00009386 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009387}
9388
9389CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9390 CXXRecordDecl *ClassDecl) {
9391 // C++ [class.copy]p4:
9392 // If the class definition does not explicitly declare a copy
9393 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009394 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009395
Richard Smithafb49182012-11-29 01:34:07 +00009396 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9397 if (DSM.isAlreadyBeingDeclared())
9398 return 0;
9399
Sean Hunt49634cf2011-05-13 06:10:58 +00009400 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9401 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009402 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009403 if (Const)
9404 ArgType = ArgType.withConst();
9405 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009406
Richard Smith7756afa2012-06-10 05:43:50 +00009407 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9408 CXXCopyConstructor,
9409 Const);
9410
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009411 DeclarationName Name
9412 = Context.DeclarationNames.getCXXConstructorName(
9413 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009414 SourceLocation ClassLoc = ClassDecl->getLocation();
9415 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009416
9417 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009418 // member of its class.
9419 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009420 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009421 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009422 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009423 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009424 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009425
Richard Smithb9d0b762012-07-27 04:22:15 +00009426 // Build an exception specification pointing back at this member.
9427 FunctionProtoType::ExtProtoInfo EPI;
9428 EPI.ExceptionSpecType = EST_Unevaluated;
9429 EPI.ExceptionSpecDecl = CopyConstructor;
9430 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009431 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009432
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009433 // Add the parameter to the constructor.
9434 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009435 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009436 /*IdentifierInfo=*/0,
9437 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009438 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009439 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009440
Richard Smithbc2a35d2012-12-08 08:32:28 +00009441 CopyConstructor->setTrivial(
9442 ClassDecl->needsOverloadResolutionForCopyConstructor()
9443 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9444 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009445
Nico Weberafcc96a2012-01-23 03:19:29 +00009446 // C++11 [class.copy]p8:
9447 // ... If the class definition does not explicitly declare a copy
9448 // constructor, there is no user-declared move constructor, and there is no
9449 // user-declared move assignment operator, a copy constructor is implicitly
9450 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009451 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009452 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009453
Richard Smithbc2a35d2012-12-08 08:32:28 +00009454 // Note that we have declared this constructor.
9455 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9456
9457 if (Scope *S = getScopeForContext(ClassDecl))
9458 PushOnScopeChains(CopyConstructor, S, false);
9459 ClassDecl->addDecl(CopyConstructor);
9460
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009461 return CopyConstructor;
9462}
9463
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009464void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009465 CXXConstructorDecl *CopyConstructor) {
9466 assert((CopyConstructor->isDefaulted() &&
9467 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009468 !CopyConstructor->doesThisDeclarationHaveABody() &&
9469 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009470 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009471
Anders Carlsson63010a72010-04-23 16:24:12 +00009472 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009473 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009474
Eli Friedman9a14db32012-10-18 20:14:08 +00009475 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009476 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009477
David Blaikie93c86172013-01-17 05:26:25 +00009478 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009479 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009480 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009481 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009482 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009483 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009484 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009485 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9486 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009487 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009488 /*isStmtExpr=*/false)
9489 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009490 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009491 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009492
9493 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009494 if (ASTMutationListener *L = getASTMutationListener()) {
9495 L->CompletedImplicitDefinition(CopyConstructor);
9496 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009497}
9498
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009499Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009500Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9501 CXXRecordDecl *ClassDecl = MD->getParent();
9502
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009503 // C++ [except.spec]p14:
9504 // An implicitly declared special member function (Clause 12) shall have an
9505 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009506 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009507 if (ClassDecl->isInvalidDecl())
9508 return ExceptSpec;
9509
9510 // Direct base-class constructors.
9511 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9512 BEnd = ClassDecl->bases_end();
9513 B != BEnd; ++B) {
9514 if (B->isVirtual()) // Handled below.
9515 continue;
9516
9517 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9518 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009519 CXXConstructorDecl *Constructor =
9520 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009521 // If this is a deleted function, add it anyway. This might be conformant
9522 // with the standard. This might not. I'm not sure. It might not matter.
9523 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009524 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009525 }
9526 }
9527
9528 // Virtual base-class constructors.
9529 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9530 BEnd = ClassDecl->vbases_end();
9531 B != BEnd; ++B) {
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 // Field constructors.
9544 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9545 FEnd = ClassDecl->field_end();
9546 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009547 QualType FieldType = Context.getBaseElementType(F->getType());
9548 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9549 CXXConstructorDecl *Constructor =
9550 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
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 // In particular, the problem is that this function never gets called. It
9554 // might just be ill-formed because this function attempts to refer to
9555 // a deleted function here.
9556 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009557 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009558 }
9559 }
9560
9561 return ExceptSpec;
9562}
9563
9564CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9565 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009566 // C++11 [class.copy]p9:
9567 // If the definition of a class X does not explicitly declare a move
9568 // constructor, one will be implicitly declared as defaulted if and only if:
9569 //
9570 // - [first 4 bullets]
9571 assert(ClassDecl->needsImplicitMoveConstructor());
9572
Richard Smithafb49182012-11-29 01:34:07 +00009573 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9574 if (DSM.isAlreadyBeingDeclared())
9575 return 0;
9576
Richard Smith1c931be2012-04-02 18:40:40 +00009577 // [Checked after we build the declaration]
9578 // - the move assignment operator would not be implicitly defined as
9579 // deleted,
9580
9581 // [DR1402]:
9582 // - each of X's non-static data members and direct or virtual base classes
9583 // has a type that either has a move constructor or is trivially copyable.
9584 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9585 ClassDecl->setFailedImplicitMoveConstructor();
9586 return 0;
9587 }
9588
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009589 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9590 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009591
Richard Smith7756afa2012-06-10 05:43:50 +00009592 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9593 CXXMoveConstructor,
9594 false);
9595
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009596 DeclarationName Name
9597 = Context.DeclarationNames.getCXXConstructorName(
9598 Context.getCanonicalType(ClassType));
9599 SourceLocation ClassLoc = ClassDecl->getLocation();
9600 DeclarationNameInfo NameInfo(Name, ClassLoc);
9601
9602 // C++0x [class.copy]p11:
9603 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009604 // member of its class.
9605 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009606 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009607 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009608 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009609 MoveConstructor->setAccess(AS_public);
9610 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009611
Richard Smithb9d0b762012-07-27 04:22:15 +00009612 // Build an exception specification pointing back at this member.
9613 FunctionProtoType::ExtProtoInfo EPI;
9614 EPI.ExceptionSpecType = EST_Unevaluated;
9615 EPI.ExceptionSpecDecl = MoveConstructor;
9616 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009617 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009618
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009619 // Add the parameter to the constructor.
9620 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9621 ClassLoc, ClassLoc,
9622 /*IdentifierInfo=*/0,
9623 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009624 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009625 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009626
Richard Smithbc2a35d2012-12-08 08:32:28 +00009627 MoveConstructor->setTrivial(
9628 ClassDecl->needsOverloadResolutionForMoveConstructor()
9629 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9630 : ClassDecl->hasTrivialMoveConstructor());
9631
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009632 // C++0x [class.copy]p9:
9633 // If the definition of a class X does not explicitly declare a move
9634 // constructor, one will be implicitly declared as defaulted if and only if:
9635 // [...]
9636 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009637 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009638 // Cache this result so that we don't try to generate this over and over
9639 // on every lookup, leaking memory and wasting time.
9640 ClassDecl->setFailedImplicitMoveConstructor();
9641 return 0;
9642 }
9643
9644 // Note that we have declared this constructor.
9645 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9646
9647 if (Scope *S = getScopeForContext(ClassDecl))
9648 PushOnScopeChains(MoveConstructor, S, false);
9649 ClassDecl->addDecl(MoveConstructor);
9650
9651 return MoveConstructor;
9652}
9653
9654void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9655 CXXConstructorDecl *MoveConstructor) {
9656 assert((MoveConstructor->isDefaulted() &&
9657 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009658 !MoveConstructor->doesThisDeclarationHaveABody() &&
9659 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009660 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9661
9662 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9663 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9664
Eli Friedman9a14db32012-10-18 20:14:08 +00009665 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009666 DiagnosticErrorTrap Trap(Diags);
9667
David Blaikie93c86172013-01-17 05:26:25 +00009668 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009669 Trap.hasErrorOccurred()) {
9670 Diag(CurrentLocation, diag::note_member_synthesized_at)
9671 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9672 MoveConstructor->setInvalidDecl();
9673 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009674 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009675 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9676 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009677 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009678 /*isStmtExpr=*/false)
9679 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009680 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009681 }
9682
9683 MoveConstructor->setUsed();
9684
9685 if (ASTMutationListener *L = getASTMutationListener()) {
9686 L->CompletedImplicitDefinition(MoveConstructor);
9687 }
9688}
9689
Douglas Gregore4e68d42012-02-15 19:33:52 +00009690bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9691 return FD->isDeleted() &&
9692 (FD->isDefaulted() || FD->isImplicit()) &&
9693 isa<CXXMethodDecl>(FD);
9694}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009695
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009696/// \brief Mark the call operator of the given lambda closure type as "used".
9697static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9698 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009699 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009700 Lambda->lookup(
9701 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009702 CallOperator->setReferenced();
9703 CallOperator->setUsed();
9704}
9705
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009706void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9707 SourceLocation CurrentLocation,
9708 CXXConversionDecl *Conv)
9709{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009710 CXXRecordDecl *Lambda = Conv->getParent();
9711
9712 // Make sure that the lambda call operator is marked used.
9713 markLambdaCallOperatorUsed(*this, Lambda);
9714
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009715 Conv->setUsed();
9716
Eli Friedman9a14db32012-10-18 20:14:08 +00009717 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009718 DiagnosticErrorTrap Trap(Diags);
9719
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009720 // Return the address of the __invoke function.
9721 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9722 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009723 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009724 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9725 VK_LValue, Conv->getLocation()).take();
9726 assert(FunctionRef && "Can't refer to __invoke function?");
9727 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009728 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009729 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009730 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009731
9732 // Fill in the __invoke function with a dummy implementation. IR generation
9733 // will fill in the actual details.
9734 Invoke->setUsed();
9735 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009736 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009737
9738 if (ASTMutationListener *L = getASTMutationListener()) {
9739 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009740 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009741 }
9742}
9743
9744void Sema::DefineImplicitLambdaToBlockPointerConversion(
9745 SourceLocation CurrentLocation,
9746 CXXConversionDecl *Conv)
9747{
9748 Conv->setUsed();
9749
Eli Friedman9a14db32012-10-18 20:14:08 +00009750 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009751 DiagnosticErrorTrap Trap(Diags);
9752
Douglas Gregorac1303e2012-02-22 05:02:47 +00009753 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009754 Expr *This = ActOnCXXThis(CurrentLocation).take();
9755 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009756
Eli Friedman23f02672012-03-01 04:01:32 +00009757 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9758 Conv->getLocation(),
9759 Conv, DerefThis);
9760
9761 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9762 // behavior. Note that only the general conversion function does this
9763 // (since it's unusable otherwise); in the case where we inline the
9764 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009765 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009766 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9767 CK_CopyAndAutoreleaseBlockObject,
9768 BuildBlock.get(), 0, VK_RValue);
9769
9770 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009771 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009772 Conv->setInvalidDecl();
9773 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009774 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009775
Douglas Gregorac1303e2012-02-22 05:02:47 +00009776 // Create the return statement that returns the block from the conversion
9777 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009778 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009779 if (Return.isInvalid()) {
9780 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9781 Conv->setInvalidDecl();
9782 return;
9783 }
9784
9785 // Set the body of the conversion function.
9786 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009787 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009788 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009789 Conv->getLocation()));
9790
Douglas Gregorac1303e2012-02-22 05:02:47 +00009791 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009792 if (ASTMutationListener *L = getASTMutationListener()) {
9793 L->CompletedImplicitDefinition(Conv);
9794 }
9795}
9796
Douglas Gregorf52757d2012-03-10 06:53:13 +00009797/// \brief Determine whether the given list arguments contains exactly one
9798/// "real" (non-default) argument.
9799static bool hasOneRealArgument(MultiExprArg Args) {
9800 switch (Args.size()) {
9801 case 0:
9802 return false;
9803
9804 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009805 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009806 return false;
9807
9808 // fall through
9809 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009810 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009811 }
9812
9813 return false;
9814}
9815
John McCall60d7b3a2010-08-24 06:29:42 +00009816ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009817Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009818 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009819 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009820 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009821 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009822 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009823 unsigned ConstructKind,
9824 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009825 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009826
Douglas Gregor2f599792010-04-02 18:24:57 +00009827 // C++0x [class.copy]p34:
9828 // When certain criteria are met, an implementation is allowed to
9829 // omit the copy/move construction of a class object, even if the
9830 // copy/move constructor and/or destructor for the object have
9831 // side effects. [...]
9832 // - when a temporary class object that has not been bound to a
9833 // reference (12.2) would be copied/moved to a class object
9834 // with the same cv-unqualified type, the copy/move operation
9835 // can be omitted by constructing the temporary object
9836 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009837 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009838 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009839 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009840 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009841 }
Mike Stump1eb44332009-09-09 15:08:12 +00009842
9843 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009844 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009845 IsListInitialization, RequiresZeroInit,
9846 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009847}
9848
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009849/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9850/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009851ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009852Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9853 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009854 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009855 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009856 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009857 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009858 unsigned ConstructKind,
9859 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009860 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009861 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009862 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +00009863 HadMultipleCandidates,
9864 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009865 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9866 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009867}
9868
John McCall68c6c9a2010-02-02 09:10:11 +00009869void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009870 if (VD->isInvalidDecl()) return;
9871
John McCall68c6c9a2010-02-02 09:10:11 +00009872 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009873 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009874 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009875 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009876
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009877 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009878 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009879 CheckDestructorAccess(VD->getLocation(), Destructor,
9880 PDiag(diag::err_access_dtor_var)
9881 << VD->getDeclName()
9882 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009883 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009884
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009885 if (!VD->hasGlobalStorage()) return;
9886
9887 // Emit warning for non-trivial dtor in global scope (a real global,
9888 // class-static, function-static).
9889 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9890
9891 // TODO: this should be re-enabled for static locals by !CXAAtExit
9892 if (!VD->isStaticLocal())
9893 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009894}
9895
Douglas Gregor39da0b82009-09-09 23:08:42 +00009896/// \brief Given a constructor and the set of arguments provided for the
9897/// constructor, convert the arguments and add any required default arguments
9898/// to form a proper call to this constructor.
9899///
9900/// \returns true if an error occurred, false otherwise.
9901bool
9902Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9903 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009904 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009905 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009906 bool AllowExplicit,
9907 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009908 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9909 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009910 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009911
9912 const FunctionProtoType *Proto
9913 = Constructor->getType()->getAs<FunctionProtoType>();
9914 assert(Proto && "Constructor without a prototype?");
9915 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009916
9917 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009918 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009919 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009920 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009921 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009922
9923 VariadicCallType CallType =
9924 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009925 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009926 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9927 Proto, 0, Args, NumArgs, AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009928 CallType, AllowExplicit,
9929 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009930 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009931
9932 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9933
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00009934 CheckConstructorCall(Constructor,
9935 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9936 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +00009937 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009938
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009939 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009940}
9941
Anders Carlsson20d45d22009-12-12 00:32:00 +00009942static inline bool
9943CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9944 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009945 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009946 if (isa<NamespaceDecl>(DC)) {
9947 return SemaRef.Diag(FnDecl->getLocation(),
9948 diag::err_operator_new_delete_declared_in_namespace)
9949 << FnDecl->getDeclName();
9950 }
9951
9952 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009953 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009954 return SemaRef.Diag(FnDecl->getLocation(),
9955 diag::err_operator_new_delete_declared_static)
9956 << FnDecl->getDeclName();
9957 }
9958
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009959 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009960}
9961
Anders Carlsson156c78e2009-12-13 17:53:43 +00009962static inline bool
9963CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9964 CanQualType ExpectedResultType,
9965 CanQualType ExpectedFirstParamType,
9966 unsigned DependentParamTypeDiag,
9967 unsigned InvalidParamTypeDiag) {
9968 QualType ResultType =
9969 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9970
9971 // Check that the result type is not dependent.
9972 if (ResultType->isDependentType())
9973 return SemaRef.Diag(FnDecl->getLocation(),
9974 diag::err_operator_new_delete_dependent_result_type)
9975 << FnDecl->getDeclName() << ExpectedResultType;
9976
9977 // Check that the result type is what we expect.
9978 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9979 return SemaRef.Diag(FnDecl->getLocation(),
9980 diag::err_operator_new_delete_invalid_result_type)
9981 << FnDecl->getDeclName() << ExpectedResultType;
9982
9983 // A function template must have at least 2 parameters.
9984 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9985 return SemaRef.Diag(FnDecl->getLocation(),
9986 diag::err_operator_new_delete_template_too_few_parameters)
9987 << FnDecl->getDeclName();
9988
9989 // The function decl must have at least 1 parameter.
9990 if (FnDecl->getNumParams() == 0)
9991 return SemaRef.Diag(FnDecl->getLocation(),
9992 diag::err_operator_new_delete_too_few_parameters)
9993 << FnDecl->getDeclName();
9994
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009995 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009996 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9997 if (FirstParamType->isDependentType())
9998 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9999 << FnDecl->getDeclName() << ExpectedFirstParamType;
10000
10001 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010002 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010003 ExpectedFirstParamType)
10004 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10005 << FnDecl->getDeclName() << ExpectedFirstParamType;
10006
10007 return false;
10008}
10009
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010010static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010011CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010012 // C++ [basic.stc.dynamic.allocation]p1:
10013 // A program is ill-formed if an allocation function is declared in a
10014 // namespace scope other than global scope or declared static in global
10015 // scope.
10016 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10017 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010018
10019 CanQualType SizeTy =
10020 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10021
10022 // C++ [basic.stc.dynamic.allocation]p1:
10023 // The return type shall be void*. The first parameter shall have type
10024 // std::size_t.
10025 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10026 SizeTy,
10027 diag::err_operator_new_dependent_param_type,
10028 diag::err_operator_new_param_type))
10029 return true;
10030
10031 // C++ [basic.stc.dynamic.allocation]p1:
10032 // The first parameter shall not have an associated default argument.
10033 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010034 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010035 diag::err_operator_new_default_arg)
10036 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10037
10038 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010039}
10040
10041static bool
Richard Smith444d3842012-10-20 08:26:51 +000010042CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010043 // C++ [basic.stc.dynamic.deallocation]p1:
10044 // A program is ill-formed if deallocation functions are declared in a
10045 // namespace scope other than global scope or declared static in global
10046 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010047 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10048 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010049
10050 // C++ [basic.stc.dynamic.deallocation]p2:
10051 // Each deallocation function shall return void and its first parameter
10052 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010053 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10054 SemaRef.Context.VoidPtrTy,
10055 diag::err_operator_delete_dependent_param_type,
10056 diag::err_operator_delete_param_type))
10057 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010058
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010059 return false;
10060}
10061
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010062/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10063/// of this overloaded operator is well-formed. If so, returns false;
10064/// otherwise, emits appropriate diagnostics and returns true.
10065bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010066 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010067 "Expected an overloaded operator declaration");
10068
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010069 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10070
Mike Stump1eb44332009-09-09 15:08:12 +000010071 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010072 // The allocation and deallocation functions, operator new,
10073 // operator new[], operator delete and operator delete[], are
10074 // described completely in 3.7.3. The attributes and restrictions
10075 // found in the rest of this subclause do not apply to them unless
10076 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010077 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010078 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010079
Anders Carlssona3ccda52009-12-12 00:26:23 +000010080 if (Op == OO_New || Op == OO_Array_New)
10081 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010082
10083 // C++ [over.oper]p6:
10084 // An operator function shall either be a non-static member
10085 // function or be a non-member function and have at least one
10086 // parameter whose type is a class, a reference to a class, an
10087 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010088 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10089 if (MethodDecl->isStatic())
10090 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010091 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010092 } else {
10093 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010094 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10095 ParamEnd = FnDecl->param_end();
10096 Param != ParamEnd; ++Param) {
10097 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010098 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10099 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010100 ClassOrEnumParam = true;
10101 break;
10102 }
10103 }
10104
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010105 if (!ClassOrEnumParam)
10106 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010107 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010108 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010109 }
10110
10111 // C++ [over.oper]p8:
10112 // An operator function cannot have default arguments (8.3.6),
10113 // except where explicitly stated below.
10114 //
Mike Stump1eb44332009-09-09 15:08:12 +000010115 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010116 // (C++ [over.call]p1).
10117 if (Op != OO_Call) {
10118 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10119 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010120 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010121 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010122 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010123 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010124 }
10125 }
10126
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010127 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10128 { false, false, false }
10129#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10130 , { Unary, Binary, MemberOnly }
10131#include "clang/Basic/OperatorKinds.def"
10132 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010133
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010134 bool CanBeUnaryOperator = OperatorUses[Op][0];
10135 bool CanBeBinaryOperator = OperatorUses[Op][1];
10136 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010137
10138 // C++ [over.oper]p8:
10139 // [...] Operator functions cannot have more or fewer parameters
10140 // than the number required for the corresponding operator, as
10141 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010142 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010143 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010144 if (Op != OO_Call &&
10145 ((NumParams == 1 && !CanBeUnaryOperator) ||
10146 (NumParams == 2 && !CanBeBinaryOperator) ||
10147 (NumParams < 1) || (NumParams > 2))) {
10148 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010149 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010150 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010151 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010152 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010153 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010154 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010155 assert(CanBeBinaryOperator &&
10156 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010157 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010158 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010159
Chris Lattner416e46f2008-11-21 07:57:12 +000010160 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010161 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010162 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010163
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010164 // Overloaded operators other than operator() cannot be variadic.
10165 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010166 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010167 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010168 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010169 }
10170
10171 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010172 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10173 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010174 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010175 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010176 }
10177
10178 // C++ [over.inc]p1:
10179 // The user-defined function called operator++ implements the
10180 // prefix and postfix ++ operator. If this function is a member
10181 // function with no parameters, or a non-member function with one
10182 // parameter of class or enumeration type, it defines the prefix
10183 // increment operator ++ for objects of that type. If the function
10184 // is a member function with one parameter (which shall be of type
10185 // int) or a non-member function with two parameters (the second
10186 // of which shall be of type int), it defines the postfix
10187 // increment operator ++ for objects of that type.
10188 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10189 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10190 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010191 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010192 ParamIsInt = BT->getKind() == BuiltinType::Int;
10193
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010194 if (!ParamIsInt)
10195 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010196 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010197 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010198 }
10199
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010200 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010201}
Chris Lattner5a003a42008-12-17 07:09:26 +000010202
Sean Hunta6c058d2010-01-13 09:01:02 +000010203/// CheckLiteralOperatorDeclaration - Check whether the declaration
10204/// of this literal operator function is well-formed. If so, returns
10205/// false; otherwise, emits appropriate diagnostics and returns true.
10206bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010207 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010208 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10209 << FnDecl->getDeclName();
10210 return true;
10211 }
10212
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010213 if (FnDecl->isExternC()) {
10214 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10215 return true;
10216 }
10217
Sean Hunta6c058d2010-01-13 09:01:02 +000010218 bool Valid = false;
10219
Richard Smith36f5cfe2012-03-09 08:00:36 +000010220 // This might be the definition of a literal operator template.
10221 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10222 // This might be a specialization of a literal operator template.
10223 if (!TpDecl)
10224 TpDecl = FnDecl->getPrimaryTemplate();
10225
Sean Hunt216c2782010-04-07 23:11:06 +000010226 // template <char...> type operator "" name() is the only valid template
10227 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010228 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010229 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010230 // Must have only one template parameter
10231 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10232 if (Params->size() == 1) {
10233 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010234 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010235
Sean Hunt216c2782010-04-07 23:11:06 +000010236 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010237 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10238 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10239 Valid = true;
10240 }
10241 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010242 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010243 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010244 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10245
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010246 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010247
Sean Hunt30019c02010-04-07 22:57:35 +000010248 // unsigned long long int, long double, and any character type are allowed
10249 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010250 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10251 Context.hasSameType(T, Context.LongDoubleTy) ||
10252 Context.hasSameType(T, Context.CharTy) ||
10253 Context.hasSameType(T, Context.WCharTy) ||
10254 Context.hasSameType(T, Context.Char16Ty) ||
10255 Context.hasSameType(T, Context.Char32Ty)) {
10256 if (++Param == FnDecl->param_end())
10257 Valid = true;
10258 goto FinishedParams;
10259 }
10260
Sean Hunt30019c02010-04-07 22:57:35 +000010261 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010262 const PointerType *PT = T->getAs<PointerType>();
10263 if (!PT)
10264 goto FinishedParams;
10265 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010266 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010267 goto FinishedParams;
10268 T = T.getUnqualifiedType();
10269
10270 // Move on to the second parameter;
10271 ++Param;
10272
10273 // If there is no second parameter, the first must be a const char *
10274 if (Param == FnDecl->param_end()) {
10275 if (Context.hasSameType(T, Context.CharTy))
10276 Valid = true;
10277 goto FinishedParams;
10278 }
10279
10280 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10281 // are allowed as the first parameter to a two-parameter function
10282 if (!(Context.hasSameType(T, Context.CharTy) ||
10283 Context.hasSameType(T, Context.WCharTy) ||
10284 Context.hasSameType(T, Context.Char16Ty) ||
10285 Context.hasSameType(T, Context.Char32Ty)))
10286 goto FinishedParams;
10287
10288 // The second and final parameter must be an std::size_t
10289 T = (*Param)->getType().getUnqualifiedType();
10290 if (Context.hasSameType(T, Context.getSizeType()) &&
10291 ++Param == FnDecl->param_end())
10292 Valid = true;
10293 }
10294
10295 // FIXME: This diagnostic is absolutely terrible.
10296FinishedParams:
10297 if (!Valid) {
10298 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10299 << FnDecl->getDeclName();
10300 return true;
10301 }
10302
Richard Smitha9e88b22012-03-09 08:16:22 +000010303 // A parameter-declaration-clause containing a default argument is not
10304 // equivalent to any of the permitted forms.
10305 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10306 ParamEnd = FnDecl->param_end();
10307 Param != ParamEnd; ++Param) {
10308 if ((*Param)->hasDefaultArg()) {
10309 Diag((*Param)->getDefaultArgRange().getBegin(),
10310 diag::err_literal_operator_default_argument)
10311 << (*Param)->getDefaultArgRange();
10312 break;
10313 }
10314 }
10315
Richard Smith2fb4ae32012-03-08 02:39:21 +000010316 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010317 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10318 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010319 // C++11 [usrlit.suffix]p1:
10320 // Literal suffix identifiers that do not start with an underscore
10321 // are reserved for future standardization.
10322 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010323 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010324
Sean Hunta6c058d2010-01-13 09:01:02 +000010325 return false;
10326}
10327
Douglas Gregor074149e2009-01-05 19:45:36 +000010328/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10329/// linkage specification, including the language and (if present)
10330/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10331/// the location of the language string literal, which is provided
10332/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10333/// the '{' brace. Otherwise, this linkage specification does not
10334/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010335Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10336 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010337 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010338 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010339 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010340 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010341 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010342 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010343 Language = LinkageSpecDecl::lang_cxx;
10344 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010345 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010346 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010347 }
Mike Stump1eb44332009-09-09 15:08:12 +000010348
Chris Lattnercc98eac2008-12-17 07:13:27 +000010349 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010350
Douglas Gregor074149e2009-01-05 19:45:36 +000010351 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010352 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010353 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010354 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010355 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010356}
10357
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010358/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010359/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10360/// valid, it's the position of the closing '}' brace in a linkage
10361/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010362Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010363 Decl *LinkageSpec,
10364 SourceLocation RBraceLoc) {
10365 if (LinkageSpec) {
10366 if (RBraceLoc.isValid()) {
10367 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10368 LSDecl->setRBraceLoc(RBraceLoc);
10369 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010370 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010371 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010372 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010373}
10374
Michael Han684aa732013-02-22 17:15:32 +000010375Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10376 AttributeList *AttrList,
10377 SourceLocation SemiLoc) {
10378 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10379 // Attribute declarations appertain to empty declaration so we handle
10380 // them here.
10381 if (AttrList)
10382 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010383
Michael Han684aa732013-02-22 17:15:32 +000010384 CurContext->addDecl(ED);
10385 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010386}
10387
Douglas Gregord308e622009-05-18 20:51:54 +000010388/// \brief Perform semantic analysis for the variable declaration that
10389/// occurs within a C++ catch clause, returning the newly-created
10390/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010391VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010392 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010393 SourceLocation StartLoc,
10394 SourceLocation Loc,
10395 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010396 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010397 QualType ExDeclType = TInfo->getType();
10398
Sebastian Redl4b07b292008-12-22 19:15:10 +000010399 // Arrays and functions decay.
10400 if (ExDeclType->isArrayType())
10401 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10402 else if (ExDeclType->isFunctionType())
10403 ExDeclType = Context.getPointerType(ExDeclType);
10404
10405 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10406 // The exception-declaration shall not denote a pointer or reference to an
10407 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010408 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010409 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010410 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010411 Invalid = true;
10412 }
Douglas Gregord308e622009-05-18 20:51:54 +000010413
Sebastian Redl4b07b292008-12-22 19:15:10 +000010414 QualType BaseType = ExDeclType;
10415 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010416 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010417 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010418 BaseType = Ptr->getPointeeType();
10419 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010420 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010421 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010422 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010423 BaseType = Ref->getPointeeType();
10424 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010425 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010426 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010427 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010428 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010429 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010430
Mike Stump1eb44332009-09-09 15:08:12 +000010431 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010432 RequireNonAbstractType(Loc, ExDeclType,
10433 diag::err_abstract_type_in_decl,
10434 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010435 Invalid = true;
10436
John McCall5a180392010-07-24 00:37:23 +000010437 // Only the non-fragile NeXT runtime currently supports C++ catches
10438 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010439 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010440 QualType T = ExDeclType;
10441 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10442 T = RT->getPointeeType();
10443
10444 if (T->isObjCObjectType()) {
10445 Diag(Loc, diag::err_objc_object_catch);
10446 Invalid = true;
10447 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010448 // FIXME: should this be a test for macosx-fragile specifically?
10449 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010450 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010451 }
10452 }
10453
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010454 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010455 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010456 ExDecl->setExceptionVariable(true);
10457
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010458 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010459 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010460 Invalid = true;
10461
Douglas Gregorc41b8782011-07-06 18:14:43 +000010462 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010463 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010464 // Insulate this from anything else we might currently be parsing.
10465 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10466
Douglas Gregor6d182892010-03-05 23:38:39 +000010467 // C++ [except.handle]p16:
10468 // The object declared in an exception-declaration or, if the
10469 // exception-declaration does not specify a name, a temporary (12.2) is
10470 // copy-initialized (8.5) from the exception object. [...]
10471 // The object is destroyed when the handler exits, after the destruction
10472 // of any automatic objects initialized within the handler.
10473 //
10474 // We just pretend to initialize the object with itself, then make sure
10475 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010476 QualType initType = ExDeclType;
10477
10478 InitializedEntity entity =
10479 InitializedEntity::InitializeVariable(ExDecl);
10480 InitializationKind initKind =
10481 InitializationKind::CreateCopy(Loc, SourceLocation());
10482
10483 Expr *opaqueValue =
10484 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10485 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10486 ExprResult result = sequence.Perform(*this, entity, initKind,
10487 MultiExprArg(&opaqueValue, 1));
10488 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010489 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010490 else {
10491 // If the constructor used was non-trivial, set this as the
10492 // "initializer".
10493 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10494 if (!construct->getConstructor()->isTrivial()) {
10495 Expr *init = MaybeCreateExprWithCleanups(construct);
10496 ExDecl->setInit(init);
10497 }
10498
10499 // And make sure it's destructable.
10500 FinalizeVarWithDestructor(ExDecl, recordType);
10501 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010502 }
10503 }
10504
Douglas Gregord308e622009-05-18 20:51:54 +000010505 if (Invalid)
10506 ExDecl->setInvalidDecl();
10507
10508 return ExDecl;
10509}
10510
10511/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10512/// handler.
John McCalld226f652010-08-21 09:40:31 +000010513Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010514 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010515 bool Invalid = D.isInvalidType();
10516
10517 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010518 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10519 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010520 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10521 D.getIdentifierLoc());
10522 Invalid = true;
10523 }
10524
Sebastian Redl4b07b292008-12-22 19:15:10 +000010525 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010526 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010527 LookupOrdinaryName,
10528 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010529 // The scope should be freshly made just for us. There is just no way
10530 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010531 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010532 if (PrevDecl->isTemplateParameter()) {
10533 // Maybe we will complain about the shadowed template parameter.
10534 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010535 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010536 }
10537 }
10538
Chris Lattnereaaebc72009-04-25 08:06:05 +000010539 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010540 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10541 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010542 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010543 }
10544
Douglas Gregor83cb9422010-09-09 17:09:21 +000010545 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010546 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010547 D.getIdentifierLoc(),
10548 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010549 if (Invalid)
10550 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010551
Sebastian Redl4b07b292008-12-22 19:15:10 +000010552 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010553 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010554 PushOnScopeChains(ExDecl, S);
10555 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010556 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010557
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010558 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010559 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010560}
Anders Carlssonfb311762009-03-14 00:25:26 +000010561
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010562Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010563 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010564 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010565 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010566 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010567
Richard Smithe3f470a2012-07-11 22:37:56 +000010568 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10569 return 0;
10570
10571 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10572 AssertMessage, RParenLoc, false);
10573}
10574
10575Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10576 Expr *AssertExpr,
10577 StringLiteral *AssertMessage,
10578 SourceLocation RParenLoc,
10579 bool Failed) {
10580 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10581 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010582 // In a static_assert-declaration, the constant-expression shall be a
10583 // constant expression that can be contextually converted to bool.
10584 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10585 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010586 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010587
Richard Smithdaaefc52011-12-14 23:32:26 +000010588 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010589 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010590 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010591 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010592 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010593
Richard Smithe3f470a2012-07-11 22:37:56 +000010594 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010595 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010596 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010597 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010598 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010599 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010600 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010601 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010602 }
Mike Stump1eb44332009-09-09 15:08:12 +000010603
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010604 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010605 AssertExpr, AssertMessage, RParenLoc,
10606 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010607
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010608 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010609 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010610}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010611
Douglas Gregor1d869352010-04-07 16:53:43 +000010612/// \brief Perform semantic analysis of the given friend type declaration.
10613///
10614/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010615FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010616 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010617 TypeSourceInfo *TSInfo) {
10618 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10619
10620 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010621 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010622
Richard Smith6b130222011-10-18 21:39:00 +000010623 // C++03 [class.friend]p2:
10624 // An elaborated-type-specifier shall be used in a friend declaration
10625 // for a class.*
10626 //
10627 // * The class-key of the elaborated-type-specifier is required.
10628 if (!ActiveTemplateInstantiations.empty()) {
10629 // Do not complain about the form of friend template types during
10630 // template instantiation; we will already have complained when the
10631 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010632 } else {
10633 if (!T->isElaboratedTypeSpecifier()) {
10634 // If we evaluated the type to a record type, suggest putting
10635 // a tag in front.
10636 if (const RecordType *RT = T->getAs<RecordType>()) {
10637 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010638
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010639 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010640
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010641 Diag(TypeRange.getBegin(),
10642 getLangOpts().CPlusPlus11 ?
10643 diag::warn_cxx98_compat_unelaborated_friend_type :
10644 diag::ext_unelaborated_friend_type)
10645 << (unsigned) RD->getTagKind()
10646 << T
10647 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10648 InsertionText);
10649 } else {
10650 Diag(FriendLoc,
10651 getLangOpts().CPlusPlus11 ?
10652 diag::warn_cxx98_compat_nonclass_type_friend :
10653 diag::ext_nonclass_type_friend)
10654 << T
10655 << TypeRange;
10656 }
10657 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010658 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010659 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010660 diag::warn_cxx98_compat_enum_friend :
10661 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010662 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010663 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010664 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010665
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010666 // C++11 [class.friend]p3:
10667 // A friend declaration that does not declare a function shall have one
10668 // of the following forms:
10669 // friend elaborated-type-specifier ;
10670 // friend simple-type-specifier ;
10671 // friend typename-specifier ;
10672 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10673 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10674 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010675
Douglas Gregor06245bf2010-04-07 17:57:12 +000010676 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010677 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010678 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010679 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010680}
10681
John McCall9a34edb2010-10-19 01:40:49 +000010682/// Handle a friend tag declaration where the scope specifier was
10683/// templated.
10684Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10685 unsigned TagSpec, SourceLocation TagLoc,
10686 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010687 IdentifierInfo *Name,
10688 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010689 AttributeList *Attr,
10690 MultiTemplateParamsArg TempParamLists) {
10691 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10692
10693 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010694 bool Invalid = false;
10695
10696 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010697 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010698 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010699 TempParamLists.size(),
10700 /*friend*/ true,
10701 isExplicitSpecialization,
10702 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010703 if (TemplateParams->size() > 0) {
10704 // This is a declaration of a class template.
10705 if (Invalid)
10706 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010707
Eric Christopher4110e132011-07-21 05:34:24 +000010708 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10709 SS, Name, NameLoc, Attr,
10710 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010711 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010712 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010713 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010714 } else {
10715 // The "template<>" header is extraneous.
10716 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10717 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10718 isExplicitSpecialization = true;
10719 }
10720 }
10721
10722 if (Invalid) return 0;
10723
John McCall9a34edb2010-10-19 01:40:49 +000010724 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010725 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010726 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010727 isAllExplicitSpecializations = false;
10728 break;
10729 }
10730 }
10731
10732 // FIXME: don't ignore attributes.
10733
10734 // If it's explicit specializations all the way down, just forget
10735 // about the template header and build an appropriate non-templated
10736 // friend. TODO: for source fidelity, remember the headers.
10737 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010738 if (SS.isEmpty()) {
10739 bool Owned = false;
10740 bool IsDependent = false;
10741 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10742 Attr, AS_public,
10743 /*ModulePrivateLoc=*/SourceLocation(),
10744 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010745 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010746 /*ScopedEnumUsesClassTag=*/false,
10747 /*UnderlyingType=*/TypeResult());
10748 }
10749
Douglas Gregor2494dd02011-03-01 01:34:45 +000010750 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010751 ElaboratedTypeKeyword Keyword
10752 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010753 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010754 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010755 if (T.isNull())
10756 return 0;
10757
10758 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10759 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010760 DependentNameTypeLoc TL =
10761 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010762 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010763 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010764 TL.setNameLoc(NameLoc);
10765 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010766 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010767 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010768 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010769 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010770 }
10771
10772 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010773 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010774 Friend->setAccess(AS_public);
10775 CurContext->addDecl(Friend);
10776 return Friend;
10777 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010778
10779 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10780
10781
John McCall9a34edb2010-10-19 01:40:49 +000010782
10783 // Handle the case of a templated-scope friend class. e.g.
10784 // template <class T> class A<T>::B;
10785 // FIXME: we don't support these right now.
10786 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10787 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10788 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000010789 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010790 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010791 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010792 TL.setNameLoc(NameLoc);
10793
10794 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010795 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010796 Friend->setAccess(AS_public);
10797 Friend->setUnsupportedFriend(true);
10798 CurContext->addDecl(Friend);
10799 return Friend;
10800}
10801
10802
John McCalldd4a3b02009-09-16 22:47:08 +000010803/// Handle a friend type declaration. This works in tandem with
10804/// ActOnTag.
10805///
10806/// Notes on friend class templates:
10807///
10808/// We generally treat friend class declarations as if they were
10809/// declaring a class. So, for example, the elaborated type specifier
10810/// in a friend declaration is required to obey the restrictions of a
10811/// class-head (i.e. no typedefs in the scope chain), template
10812/// parameters are required to match up with simple template-ids, &c.
10813/// However, unlike when declaring a template specialization, it's
10814/// okay to refer to a template specialization without an empty
10815/// template parameter declaration, e.g.
10816/// friend class A<T>::B<unsigned>;
10817/// We permit this as a special case; if there are any template
10818/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010819/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010820Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010821 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010822 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010823
10824 assert(DS.isFriendSpecified());
10825 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10826
John McCalldd4a3b02009-09-16 22:47:08 +000010827 // Try to convert the decl specifier to a type. This works for
10828 // friend templates because ActOnTag never produces a ClassTemplateDecl
10829 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010830 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010831 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10832 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010833 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010834 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010835
Douglas Gregor6ccab972010-12-16 01:14:37 +000010836 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10837 return 0;
10838
John McCalldd4a3b02009-09-16 22:47:08 +000010839 // This is definitely an error in C++98. It's probably meant to
10840 // be forbidden in C++0x, too, but the specification is just
10841 // poorly written.
10842 //
10843 // The problem is with declarations like the following:
10844 // template <T> friend A<T>::foo;
10845 // where deciding whether a class C is a friend or not now hinges
10846 // on whether there exists an instantiation of A that causes
10847 // 'foo' to equal C. There are restrictions on class-heads
10848 // (which we declare (by fiat) elaborated friend declarations to
10849 // be) that makes this tractable.
10850 //
10851 // FIXME: handle "template <> friend class A<T>;", which
10852 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010853 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010854 Diag(Loc, diag::err_tagless_friend_type_template)
10855 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010856 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010857 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010858
John McCall02cace72009-08-28 07:59:38 +000010859 // C++98 [class.friend]p1: A friend of a class is a function
10860 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010861 // This is fixed in DR77, which just barely didn't make the C++03
10862 // deadline. It's also a very silly restriction that seriously
10863 // affects inner classes and which nobody else seems to implement;
10864 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010865 //
10866 // But note that we could warn about it: it's always useless to
10867 // friend one of your own members (it's not, however, worthless to
10868 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010869
John McCalldd4a3b02009-09-16 22:47:08 +000010870 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010871 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010872 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010873 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010874 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010875 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010876 DS.getFriendSpecLoc());
10877 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010878 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010879
10880 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010881 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010882
John McCalldd4a3b02009-09-16 22:47:08 +000010883 D->setAccess(AS_public);
10884 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010885
John McCalld226f652010-08-21 09:40:31 +000010886 return D;
John McCall02cace72009-08-28 07:59:38 +000010887}
10888
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000010889NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10890 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010891 const DeclSpec &DS = D.getDeclSpec();
10892
10893 assert(DS.isFriendSpecified());
10894 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10895
10896 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010897 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010898
10899 // C++ [class.friend]p1
10900 // A friend of a class is a function or class....
10901 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010902 // It *doesn't* see through dependent types, which is correct
10903 // according to [temp.arg.type]p3:
10904 // If a declaration acquires a function type through a
10905 // type dependent on a template-parameter and this causes
10906 // a declaration that does not use the syntactic form of a
10907 // function declarator to have a function type, the program
10908 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010909 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010910 Diag(Loc, diag::err_unexpected_friend);
10911
10912 // It might be worthwhile to try to recover by creating an
10913 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010914 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010915 }
10916
10917 // C++ [namespace.memdef]p3
10918 // - If a friend declaration in a non-local class first declares a
10919 // class or function, the friend class or function is a member
10920 // of the innermost enclosing namespace.
10921 // - The name of the friend is not found by simple name lookup
10922 // until a matching declaration is provided in that namespace
10923 // scope (either before or after the class declaration granting
10924 // friendship).
10925 // - If a friend function is called, its name may be found by the
10926 // name lookup that considers functions from namespaces and
10927 // classes associated with the types of the function arguments.
10928 // - When looking for a prior declaration of a class or a function
10929 // declared as a friend, scopes outside the innermost enclosing
10930 // namespace scope are not considered.
10931
John McCall337ec3d2010-10-12 23:13:28 +000010932 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010933 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10934 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010935 assert(Name);
10936
Douglas Gregor6ccab972010-12-16 01:14:37 +000010937 // Check for unexpanded parameter packs.
10938 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10939 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10940 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10941 return 0;
10942
John McCall67d1a672009-08-06 02:15:43 +000010943 // The context we found the declaration in, or in which we should
10944 // create the declaration.
10945 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010946 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010947 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010948 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010949
John McCall337ec3d2010-10-12 23:13:28 +000010950 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010951
John McCall337ec3d2010-10-12 23:13:28 +000010952 // There are four cases here.
10953 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010954 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010955 // there as appropriate.
10956 // Recover from invalid scope qualifiers as if they just weren't there.
10957 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010958 // C++0x [namespace.memdef]p3:
10959 // If the name in a friend declaration is neither qualified nor
10960 // a template-id and the declaration is a function or an
10961 // elaborated-type-specifier, the lookup to determine whether
10962 // the entity has been previously declared shall not consider
10963 // any scopes outside the innermost enclosing namespace.
10964 // C++0x [class.friend]p11:
10965 // If a friend declaration appears in a local class and the name
10966 // specified is an unqualified name, a prior declaration is
10967 // looked up without considering scopes that are outside the
10968 // innermost enclosing non-class scope. For a friend function
10969 // declaration, if there is no prior declaration, the program is
10970 // ill-formed.
10971 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010972 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010973
John McCall29ae6e52010-10-13 05:45:15 +000010974 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010975 DC = CurContext;
10976 while (true) {
10977 // Skip class contexts. If someone can cite chapter and verse
10978 // for this behavior, that would be nice --- it's what GCC and
10979 // EDG do, and it seems like a reasonable intent, but the spec
10980 // really only says that checks for unqualified existing
10981 // declarations should stop at the nearest enclosing namespace,
10982 // not that they should only consider the nearest enclosing
10983 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010984 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010985 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010986
John McCall68263142009-11-18 22:49:29 +000010987 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010988
10989 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010990 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010991 break;
John McCall29ae6e52010-10-13 05:45:15 +000010992
John McCall8a407372010-10-14 22:22:28 +000010993 if (isTemplateId) {
10994 if (isa<TranslationUnitDecl>(DC)) break;
10995 } else {
10996 if (DC->isFileContext()) break;
10997 }
John McCall67d1a672009-08-06 02:15:43 +000010998 DC = DC->getParent();
10999 }
11000
John McCall380aaa42010-10-13 06:22:15 +000011001 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011002
Douglas Gregor883af832011-10-10 01:11:59 +000011003 // C++ [class.friend]p6:
11004 // A function can be defined in a friend declaration of a class if and
11005 // only if the class is a non-local class (9.8), the function name is
11006 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011007 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011008 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11009 }
11010
John McCall337ec3d2010-10-12 23:13:28 +000011011 // - There's a non-dependent scope specifier, in which case we
11012 // compute it and do a previous lookup there for a function
11013 // or function template.
11014 } else if (!SS.getScopeRep()->isDependent()) {
11015 DC = computeDeclContext(SS);
11016 if (!DC) return 0;
11017
11018 if (RequireCompleteDeclContext(SS, DC)) return 0;
11019
11020 LookupQualifiedName(Previous, DC);
11021
11022 // Ignore things found implicitly in the wrong scope.
11023 // TODO: better diagnostics for this case. Suggesting the right
11024 // qualified scope would be nice...
11025 LookupResult::Filter F = Previous.makeFilter();
11026 while (F.hasNext()) {
11027 NamedDecl *D = F.next();
11028 if (!DC->InEnclosingNamespaceSetOf(
11029 D->getDeclContext()->getRedeclContext()))
11030 F.erase();
11031 }
11032 F.done();
11033
11034 if (Previous.empty()) {
11035 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011036 Diag(Loc, diag::err_qualified_friend_not_found)
11037 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011038 return 0;
11039 }
11040
11041 // C++ [class.friend]p1: A friend of a class is a function or
11042 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011043 if (DC->Equals(CurContext))
11044 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011045 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011046 diag::warn_cxx98_compat_friend_is_member :
11047 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011048
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011049 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011050 // C++ [class.friend]p6:
11051 // A function can be defined in a friend declaration of a class if and
11052 // only if the class is a non-local class (9.8), the function name is
11053 // unqualified, and the function has namespace scope.
11054 SemaDiagnosticBuilder DB
11055 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11056
11057 DB << SS.getScopeRep();
11058 if (DC->isFileContext())
11059 DB << FixItHint::CreateRemoval(SS.getRange());
11060 SS.clear();
11061 }
John McCall337ec3d2010-10-12 23:13:28 +000011062
11063 // - There's a scope specifier that does not match any template
11064 // parameter lists, in which case we use some arbitrary context,
11065 // create a method or method template, and wait for instantiation.
11066 // - There's a scope specifier that does match some template
11067 // parameter lists, which we don't handle right now.
11068 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011069 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011070 // C++ [class.friend]p6:
11071 // A function can be defined in a friend declaration of a class if and
11072 // only if the class is a non-local class (9.8), the function name is
11073 // unqualified, and the function has namespace scope.
11074 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11075 << SS.getScopeRep();
11076 }
11077
John McCall337ec3d2010-10-12 23:13:28 +000011078 DC = CurContext;
11079 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011080 }
Douglas Gregor883af832011-10-10 01:11:59 +000011081
John McCall29ae6e52010-10-13 05:45:15 +000011082 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011083 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011084 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11085 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11086 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011087 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011088 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11089 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011090 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011091 }
John McCall67d1a672009-08-06 02:15:43 +000011092 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011093
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011094 // FIXME: This is an egregious hack to cope with cases where the scope stack
11095 // does not contain the declaration context, i.e., in an out-of-line
11096 // definition of a class.
11097 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11098 if (!DCScope) {
11099 FakeDCScope.setEntity(DC);
11100 DCScope = &FakeDCScope;
11101 }
11102
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011103 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011104 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011105 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011106 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011107
Douglas Gregor182ddf02009-09-28 00:08:27 +000011108 assert(ND->getDeclContext() == DC);
11109 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011110
John McCallab88d972009-08-31 22:39:49 +000011111 // Add the function declaration to the appropriate lookup tables,
11112 // adjusting the redeclarations list as necessary. We don't
11113 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011114 //
John McCallab88d972009-08-31 22:39:49 +000011115 // Also update the scope-based lookup if the target context's
11116 // lookup context is in lexical scope.
11117 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011118 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011119 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011120 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011121 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011122 }
John McCall02cace72009-08-28 07:59:38 +000011123
11124 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011125 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011126 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011127 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011128 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011129
John McCall1f2e1a92012-08-10 03:15:35 +000011130 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011131 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011132 } else {
11133 if (DC->isRecord()) CheckFriendAccess(ND);
11134
John McCall6102ca12010-10-16 06:59:13 +000011135 FunctionDecl *FD;
11136 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11137 FD = FTD->getTemplatedDecl();
11138 else
11139 FD = cast<FunctionDecl>(ND);
11140
11141 // Mark templated-scope function declarations as unsupported.
11142 if (FD->getNumTemplateParameterLists())
11143 FrD->setUnsupportedFriend(true);
11144 }
John McCall337ec3d2010-10-12 23:13:28 +000011145
John McCalld226f652010-08-21 09:40:31 +000011146 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011147}
11148
John McCalld226f652010-08-21 09:40:31 +000011149void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11150 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011151
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011152 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011153 if (!Fn) {
11154 Diag(DelLoc, diag::err_deleted_non_function);
11155 return;
11156 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011157
Douglas Gregoref96ee02012-01-14 16:38:05 +000011158 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011159 // Don't consider the implicit declaration we generate for explicit
11160 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011161 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11162 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011163 Diag(DelLoc, diag::err_deleted_decl_not_first);
11164 Diag(Prev->getLocation(), diag::note_previous_declaration);
11165 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011166 // If the declaration wasn't the first, we delete the function anyway for
11167 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011168 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011169 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011170
11171 if (Fn->isDeleted())
11172 return;
11173
11174 // See if we're deleting a function which is already known to override a
11175 // non-deleted virtual function.
11176 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11177 bool IssuedDiagnostic = false;
11178 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11179 E = MD->end_overridden_methods();
11180 I != E; ++I) {
11181 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11182 if (!IssuedDiagnostic) {
11183 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11184 IssuedDiagnostic = true;
11185 }
11186 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11187 }
11188 }
11189 }
11190
Sean Hunt10620eb2011-05-06 20:44:56 +000011191 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011192}
Sebastian Redl13e88542009-04-27 21:33:24 +000011193
Sean Hunte4246a62011-05-12 06:15:49 +000011194void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011195 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011196
11197 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011198 if (MD->getParent()->isDependentType()) {
11199 MD->setDefaulted();
11200 MD->setExplicitlyDefaulted();
11201 return;
11202 }
11203
Sean Hunte4246a62011-05-12 06:15:49 +000011204 CXXSpecialMember Member = getSpecialMember(MD);
11205 if (Member == CXXInvalid) {
11206 Diag(DefaultLoc, diag::err_default_special_members);
11207 return;
11208 }
11209
11210 MD->setDefaulted();
11211 MD->setExplicitlyDefaulted();
11212
Sean Huntcd10dec2011-05-23 23:14:04 +000011213 // If this definition appears within the record, do the checking when
11214 // the record is complete.
11215 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011216 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011217 // Find the uninstantiated declaration that actually had the '= default'
11218 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011219 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011220
Richard Smith12fef492013-03-27 00:22:47 +000011221 // If the method was defaulted on its first declaration, we will have
11222 // already performed the checking in CheckCompletedCXXClass. Such a
11223 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011224 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011225 return;
11226
Richard Smithb9d0b762012-07-27 04:22:15 +000011227 CheckExplicitlyDefaultedSpecialMember(MD);
11228
Richard Smith1d28caf2012-12-11 01:14:52 +000011229 // The exception specification is needed because we are defining the
11230 // function.
11231 ResolveExceptionSpec(DefaultLoc,
11232 MD->getType()->castAs<FunctionProtoType>());
11233
Sean Hunte4246a62011-05-12 06:15:49 +000011234 switch (Member) {
11235 case CXXDefaultConstructor: {
11236 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011237 if (!CD->isInvalidDecl())
11238 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11239 break;
11240 }
11241
11242 case CXXCopyConstructor: {
11243 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011244 if (!CD->isInvalidDecl())
11245 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011246 break;
11247 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011248
Sean Hunt2b188082011-05-14 05:23:28 +000011249 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011250 if (!MD->isInvalidDecl())
11251 DefineImplicitCopyAssignment(DefaultLoc, MD);
11252 break;
11253 }
11254
Sean Huntcb45a0f2011-05-12 22:46:25 +000011255 case CXXDestructor: {
11256 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011257 if (!DD->isInvalidDecl())
11258 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011259 break;
11260 }
11261
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011262 case CXXMoveConstructor: {
11263 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011264 if (!CD->isInvalidDecl())
11265 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011266 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011267 }
Sean Hunt82713172011-05-25 23:16:36 +000011268
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011269 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011270 if (!MD->isInvalidDecl())
11271 DefineImplicitMoveAssignment(DefaultLoc, MD);
11272 break;
11273 }
11274
11275 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011276 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011277 }
11278 } else {
11279 Diag(DefaultLoc, diag::err_default_special_members);
11280 }
11281}
11282
Sebastian Redl13e88542009-04-27 21:33:24 +000011283static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011284 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011285 Stmt *SubStmt = *CI;
11286 if (!SubStmt)
11287 continue;
11288 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011289 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011290 diag::err_return_in_constructor_handler);
11291 if (!isa<Expr>(SubStmt))
11292 SearchForReturnInStmt(Self, SubStmt);
11293 }
11294}
11295
11296void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11297 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11298 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11299 SearchForReturnInStmt(*this, Handler);
11300 }
11301}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011302
David Blaikie299adab2013-01-18 23:03:15 +000011303bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011304 const CXXMethodDecl *Old) {
11305 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11306 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11307
11308 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11309
11310 // If the calling conventions match, everything is fine
11311 if (NewCC == OldCC)
11312 return false;
11313
11314 // If either of the calling conventions are set to "default", we need to pick
11315 // something more sensible based on the target. This supports code where the
11316 // one method explicitly sets thiscall, and another has no explicit calling
11317 // convention.
11318 CallingConv Default =
11319 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11320 if (NewCC == CC_Default)
11321 NewCC = Default;
11322 if (OldCC == CC_Default)
11323 OldCC = Default;
11324
11325 // If the calling conventions still don't match, then report the error
11326 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011327 Diag(New->getLocation(),
11328 diag::err_conflicting_overriding_cc_attributes)
11329 << New->getDeclName() << New->getType() << Old->getType();
11330 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11331 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011332 }
11333
11334 return false;
11335}
11336
Mike Stump1eb44332009-09-09 15:08:12 +000011337bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011338 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011339 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11340 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011341
Chandler Carruth73857792010-02-15 11:53:20 +000011342 if (Context.hasSameType(NewTy, OldTy) ||
11343 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011344 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011345
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011346 // Check if the return types are covariant
11347 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011348
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011349 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011350 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11351 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011352 NewClassTy = NewPT->getPointeeType();
11353 OldClassTy = OldPT->getPointeeType();
11354 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011355 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11356 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11357 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11358 NewClassTy = NewRT->getPointeeType();
11359 OldClassTy = OldRT->getPointeeType();
11360 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011361 }
11362 }
Mike Stump1eb44332009-09-09 15:08:12 +000011363
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011364 // The return types aren't either both pointers or references to a class type.
11365 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011366 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011367 diag::err_different_return_type_for_overriding_virtual_function)
11368 << New->getDeclName() << NewTy << OldTy;
11369 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011370
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011371 return true;
11372 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011373
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011374 // C++ [class.virtual]p6:
11375 // If the return type of D::f differs from the return type of B::f, the
11376 // class type in the return type of D::f shall be complete at the point of
11377 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011378 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11379 if (!RT->isBeingDefined() &&
11380 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011381 diag::err_covariant_return_incomplete,
11382 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011383 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011384 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011385
Douglas Gregora4923eb2009-11-16 21:35:15 +000011386 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011387 // Check if the new class derives from the old class.
11388 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11389 Diag(New->getLocation(),
11390 diag::err_covariant_return_not_derived)
11391 << New->getDeclName() << NewTy << OldTy;
11392 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11393 return true;
11394 }
Mike Stump1eb44332009-09-09 15:08:12 +000011395
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011396 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011397 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011398 diag::err_covariant_return_inaccessible_base,
11399 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11400 // FIXME: Should this point to the return type?
11401 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011402 // FIXME: this note won't trigger for delayed access control
11403 // diagnostics, and it's impossible to get an undelayed error
11404 // here from access control during the original parse because
11405 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011406 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11407 return true;
11408 }
11409 }
Mike Stump1eb44332009-09-09 15:08:12 +000011410
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011411 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011412 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011413 Diag(New->getLocation(),
11414 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011415 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011416 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11417 return true;
11418 };
Mike Stump1eb44332009-09-09 15:08:12 +000011419
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011420
11421 // The new class type must have the same or less qualifiers as the old type.
11422 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11423 Diag(New->getLocation(),
11424 diag::err_covariant_return_type_class_type_more_qualified)
11425 << New->getDeclName() << NewTy << OldTy;
11426 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11427 return true;
11428 };
Mike Stump1eb44332009-09-09 15:08:12 +000011429
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011430 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011431}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011432
Douglas Gregor4ba31362009-12-01 17:24:26 +000011433/// \brief Mark the given method pure.
11434///
11435/// \param Method the method to be marked pure.
11436///
11437/// \param InitRange the source range that covers the "0" initializer.
11438bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011439 SourceLocation EndLoc = InitRange.getEnd();
11440 if (EndLoc.isValid())
11441 Method->setRangeEnd(EndLoc);
11442
Douglas Gregor4ba31362009-12-01 17:24:26 +000011443 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11444 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011445 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011446 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011447
11448 if (!Method->isInvalidDecl())
11449 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11450 << Method->getDeclName() << InitRange;
11451 return true;
11452}
11453
Douglas Gregor552e2992012-02-21 02:22:07 +000011454/// \brief Determine whether the given declaration is a static data member.
11455static bool isStaticDataMember(Decl *D) {
11456 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11457 if (!Var)
11458 return false;
11459
11460 return Var->isStaticDataMember();
11461}
John McCall731ad842009-12-19 09:28:58 +000011462/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11463/// an initializer for the out-of-line declaration 'Dcl'. The scope
11464/// is a fresh scope pushed for just this purpose.
11465///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011466/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11467/// static data member of class X, names should be looked up in the scope of
11468/// class X.
John McCalld226f652010-08-21 09:40:31 +000011469void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011470 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011471 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011472
John McCall731ad842009-12-19 09:28:58 +000011473 // We should only get called for declarations with scope specifiers, like:
11474 // int foo::bar;
11475 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011476 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011477
11478 // If we are parsing the initializer for a static data member, push a
11479 // new expression evaluation context that is associated with this static
11480 // data member.
11481 if (isStaticDataMember(D))
11482 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011483}
11484
11485/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011486/// initializer for the out-of-line declaration 'D'.
11487void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011488 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011489 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011490
Douglas Gregor552e2992012-02-21 02:22:07 +000011491 if (isStaticDataMember(D))
11492 PopExpressionEvaluationContext();
11493
John McCall731ad842009-12-19 09:28:58 +000011494 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011495 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011496}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011497
11498/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11499/// C++ if/switch/while/for statement.
11500/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011501DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011502 // C++ 6.4p2:
11503 // The declarator shall not specify a function or an array.
11504 // The type-specifier-seq shall not contain typedef and shall not declare a
11505 // new class or enumeration.
11506 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11507 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011508
11509 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011510 if (!Dcl)
11511 return true;
11512
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011513 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11514 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011515 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011516 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011517 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011518
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011519 return Dcl;
11520}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011521
Douglas Gregordfe65432011-07-28 19:11:31 +000011522void Sema::LoadExternalVTableUses() {
11523 if (!ExternalSource)
11524 return;
11525
11526 SmallVector<ExternalVTableUse, 4> VTables;
11527 ExternalSource->ReadUsedVTables(VTables);
11528 SmallVector<VTableUse, 4> NewUses;
11529 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11530 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11531 = VTablesUsed.find(VTables[I].Record);
11532 // Even if a definition wasn't required before, it may be required now.
11533 if (Pos != VTablesUsed.end()) {
11534 if (!Pos->second && VTables[I].DefinitionRequired)
11535 Pos->second = true;
11536 continue;
11537 }
11538
11539 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11540 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11541 }
11542
11543 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11544}
11545
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011546void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11547 bool DefinitionRequired) {
11548 // Ignore any vtable uses in unevaluated operands or for classes that do
11549 // not have a vtable.
11550 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11551 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011552 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011553 return;
11554
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011555 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011556 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011557 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11558 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11559 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11560 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011561 // If we already had an entry, check to see if we are promoting this vtable
11562 // to required a definition. If so, we need to reappend to the VTableUses
11563 // list, since we may have already processed the first entry.
11564 if (DefinitionRequired && !Pos.first->second) {
11565 Pos.first->second = true;
11566 } else {
11567 // Otherwise, we can early exit.
11568 return;
11569 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011570 }
11571
11572 // Local classes need to have their virtual members marked
11573 // immediately. For all other classes, we mark their virtual members
11574 // at the end of the translation unit.
11575 if (Class->isLocalClass())
11576 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011577 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011578 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011579}
11580
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011581bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011582 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011583 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011584 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011585
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011586 // Note: The VTableUses vector could grow as a result of marking
11587 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011588 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011589 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011590 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011591 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011592 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011593 if (!Class)
11594 continue;
11595
11596 SourceLocation Loc = VTableUses[I].second;
11597
Richard Smithb9d0b762012-07-27 04:22:15 +000011598 bool DefineVTable = true;
11599
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011600 // If this class has a key function, but that key function is
11601 // defined in another translation unit, we don't need to emit the
11602 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011603 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011604 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011605 switch (KeyFunction->getTemplateSpecializationKind()) {
11606 case TSK_Undeclared:
11607 case TSK_ExplicitSpecialization:
11608 case TSK_ExplicitInstantiationDeclaration:
11609 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011610 DefineVTable = false;
11611 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011612
11613 case TSK_ExplicitInstantiationDefinition:
11614 case TSK_ImplicitInstantiation:
11615 // We will be instantiating the key function.
11616 break;
11617 }
11618 } else if (!KeyFunction) {
11619 // If we have a class with no key function that is the subject
11620 // of an explicit instantiation declaration, suppress the
11621 // vtable; it will live with the explicit instantiation
11622 // definition.
11623 bool IsExplicitInstantiationDeclaration
11624 = Class->getTemplateSpecializationKind()
11625 == TSK_ExplicitInstantiationDeclaration;
11626 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11627 REnd = Class->redecls_end();
11628 R != REnd; ++R) {
11629 TemplateSpecializationKind TSK
11630 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11631 if (TSK == TSK_ExplicitInstantiationDeclaration)
11632 IsExplicitInstantiationDeclaration = true;
11633 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11634 IsExplicitInstantiationDeclaration = false;
11635 break;
11636 }
11637 }
11638
11639 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011640 DefineVTable = false;
11641 }
11642
11643 // The exception specifications for all virtual members may be needed even
11644 // if we are not providing an authoritative form of the vtable in this TU.
11645 // We may choose to emit it available_externally anyway.
11646 if (!DefineVTable) {
11647 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11648 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011649 }
11650
11651 // Mark all of the virtual members of this class as referenced, so
11652 // that we can build a vtable. Then, tell the AST consumer that a
11653 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011654 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011655 MarkVirtualMembersReferenced(Loc, Class);
11656 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11657 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11658
11659 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola531db822013-03-07 02:00:27 +000011660 if (Class->hasExternalLinkage() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011661 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011662 const FunctionDecl *KeyFunctionDef = 0;
11663 if (!KeyFunction ||
11664 (KeyFunction->hasBody(KeyFunctionDef) &&
11665 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011666 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11667 TSK_ExplicitInstantiationDefinition
11668 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11669 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011670 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011671 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011672 VTableUses.clear();
11673
Douglas Gregor78844032011-04-22 22:25:37 +000011674 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011675}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011676
Richard Smithb9d0b762012-07-27 04:22:15 +000011677void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11678 const CXXRecordDecl *RD) {
11679 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11680 E = RD->method_end(); I != E; ++I)
11681 if ((*I)->isVirtual() && !(*I)->isPure())
11682 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11683}
11684
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011685void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11686 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011687 // Mark all functions which will appear in RD's vtable as used.
11688 CXXFinalOverriderMap FinalOverriders;
11689 RD->getFinalOverriders(FinalOverriders);
11690 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11691 E = FinalOverriders.end();
11692 I != E; ++I) {
11693 for (OverridingMethods::const_iterator OI = I->second.begin(),
11694 OE = I->second.end();
11695 OI != OE; ++OI) {
11696 assert(OI->second.size() > 0 && "no final overrider");
11697 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011698
Richard Smithff817f72012-07-07 06:59:51 +000011699 // C++ [basic.def.odr]p2:
11700 // [...] A virtual member function is used if it is not pure. [...]
11701 if (!Overrider->isPure())
11702 MarkFunctionReferenced(Loc, Overrider);
11703 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011704 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011705
11706 // Only classes that have virtual bases need a VTT.
11707 if (RD->getNumVBases() == 0)
11708 return;
11709
11710 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11711 e = RD->bases_end(); i != e; ++i) {
11712 const CXXRecordDecl *Base =
11713 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011714 if (Base->getNumVBases() == 0)
11715 continue;
11716 MarkVirtualMembersReferenced(Loc, Base);
11717 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011718}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011719
11720/// SetIvarInitializers - This routine builds initialization ASTs for the
11721/// Objective-C implementation whose ivars need be initialized.
11722void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011723 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011724 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011725 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011726 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011727 CollectIvarsToConstructOrDestruct(OID, ivars);
11728 if (ivars.empty())
11729 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011730 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011731 for (unsigned i = 0; i < ivars.size(); i++) {
11732 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011733 if (Field->isInvalidDecl())
11734 continue;
11735
Sean Huntcbb67482011-01-08 20:30:50 +000011736 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011737 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11738 InitializationKind InitKind =
11739 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11740
11741 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011742 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011743 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011744 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011745 // Note, MemberInit could actually come back empty if no initialization
11746 // is required (e.g., because it would call a trivial default constructor)
11747 if (!MemberInit.get() || MemberInit.isInvalid())
11748 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011749
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011750 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011751 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11752 SourceLocation(),
11753 MemberInit.takeAs<Expr>(),
11754 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011755 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011756
11757 // Be sure that the destructor is accessible and is marked as referenced.
11758 if (const RecordType *RecordTy
11759 = Context.getBaseElementType(Field->getType())
11760 ->getAs<RecordType>()) {
11761 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011762 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011763 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011764 CheckDestructorAccess(Field->getLocation(), Destructor,
11765 PDiag(diag::err_access_dtor_ivar)
11766 << Context.getBaseElementType(Field->getType()));
11767 }
11768 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011769 }
11770 ObjCImplementation->setIvarInitializers(Context,
11771 AllToInit.data(), AllToInit.size());
11772 }
11773}
Sean Huntfe57eef2011-05-04 05:57:24 +000011774
Sean Huntebcbe1d2011-05-04 23:29:54 +000011775static
11776void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11777 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11778 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11779 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11780 Sema &S) {
11781 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11782 CE = Current.end();
11783 if (Ctor->isInvalidDecl())
11784 return;
11785
Richard Smitha8eaf002012-08-23 06:16:52 +000011786 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11787
11788 // Target may not be determinable yet, for instance if this is a dependent
11789 // call in an uninstantiated template.
11790 if (Target) {
11791 const FunctionDecl *FNTarget = 0;
11792 (void)Target->hasBody(FNTarget);
11793 Target = const_cast<CXXConstructorDecl*>(
11794 cast_or_null<CXXConstructorDecl>(FNTarget));
11795 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011796
11797 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11798 // Avoid dereferencing a null pointer here.
11799 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11800
11801 if (!Current.insert(Canonical))
11802 return;
11803
11804 // We know that beyond here, we aren't chaining into a cycle.
11805 if (!Target || !Target->isDelegatingConstructor() ||
11806 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11807 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11808 Valid.insert(*CI);
11809 Current.clear();
11810 // We've hit a cycle.
11811 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11812 Current.count(TCanonical)) {
11813 // If we haven't diagnosed this cycle yet, do so now.
11814 if (!Invalid.count(TCanonical)) {
11815 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011816 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011817 << Ctor;
11818
Richard Smitha8eaf002012-08-23 06:16:52 +000011819 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011820 if (TCanonical != Canonical)
11821 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11822
11823 CXXConstructorDecl *C = Target;
11824 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011825 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011826 (void)C->getTargetConstructor()->hasBody(FNTarget);
11827 assert(FNTarget && "Ctor cycle through bodiless function");
11828
Richard Smitha8eaf002012-08-23 06:16:52 +000011829 C = const_cast<CXXConstructorDecl*>(
11830 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011831 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11832 }
11833 }
11834
11835 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11836 Invalid.insert(*CI);
11837 Current.clear();
11838 } else {
11839 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11840 }
11841}
11842
11843
Sean Huntfe57eef2011-05-04 05:57:24 +000011844void Sema::CheckDelegatingCtorCycles() {
11845 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11846
Sean Huntebcbe1d2011-05-04 23:29:54 +000011847 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11848 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011849
Douglas Gregor0129b562011-07-27 21:57:17 +000011850 for (DelegatingCtorDeclsType::iterator
11851 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011852 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011853 I != E; ++I)
11854 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011855
11856 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11857 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011858}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011859
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011860namespace {
11861 /// \brief AST visitor that finds references to the 'this' expression.
11862 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11863 Sema &S;
11864
11865 public:
11866 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11867
11868 bool VisitCXXThisExpr(CXXThisExpr *E) {
11869 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11870 << E->isImplicit();
11871 return false;
11872 }
11873 };
11874}
11875
11876bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11877 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11878 if (!TSInfo)
11879 return false;
11880
11881 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011882 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011883 if (!ProtoTL)
11884 return false;
11885
11886 // C++11 [expr.prim.general]p3:
11887 // [The expression this] shall not appear before the optional
11888 // cv-qualifier-seq and it shall not appear within the declaration of a
11889 // static member function (although its type and value category are defined
11890 // within a static member function as they are within a non-static member
11891 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011892 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000011893 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011894 FindCXXThisExpr Finder(*this);
11895
11896 // If the return type came after the cv-qualifier-seq, check it now.
11897 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000011898 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011899 return true;
11900
11901 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011902 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11903 return true;
11904
11905 return checkThisInStaticMemberFunctionAttributes(Method);
11906}
11907
11908bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11909 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11910 if (!TSInfo)
11911 return false;
11912
11913 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011914 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011915 if (!ProtoTL)
11916 return false;
11917
David Blaikie39e6ab42013-02-18 22:06:02 +000011918 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011919 FindCXXThisExpr Finder(*this);
11920
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011921 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011922 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011923 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011924 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011925 case EST_DynamicNone:
11926 case EST_MSAny:
11927 case EST_None:
11928 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011929
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011930 case EST_ComputedNoexcept:
11931 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11932 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011933
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011934 case EST_Dynamic:
11935 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011936 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011937 E != EEnd; ++E) {
11938 if (!Finder.TraverseType(*E))
11939 return true;
11940 }
11941 break;
11942 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011943
11944 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011945}
11946
11947bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11948 FindCXXThisExpr Finder(*this);
11949
11950 // Check attributes.
11951 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11952 A != AEnd; ++A) {
11953 // FIXME: This should be emitted by tblgen.
11954 Expr *Arg = 0;
11955 ArrayRef<Expr *> Args;
11956 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11957 Arg = G->getArg();
11958 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11959 Arg = G->getArg();
11960 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11961 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11962 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11963 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11964 else if (ExclusiveLockFunctionAttr *ELF
11965 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11966 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11967 else if (SharedLockFunctionAttr *SLF
11968 = dyn_cast<SharedLockFunctionAttr>(*A))
11969 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11970 else if (ExclusiveTrylockFunctionAttr *ETLF
11971 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11972 Arg = ETLF->getSuccessValue();
11973 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11974 } else if (SharedTrylockFunctionAttr *STLF
11975 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11976 Arg = STLF->getSuccessValue();
11977 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11978 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11979 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11980 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11981 Arg = LR->getArg();
11982 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11983 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11984 else if (ExclusiveLocksRequiredAttr *ELR
11985 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11986 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11987 else if (SharedLocksRequiredAttr *SLR
11988 = dyn_cast<SharedLocksRequiredAttr>(*A))
11989 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11990
11991 if (Arg && !Finder.TraverseStmt(Arg))
11992 return true;
11993
11994 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11995 if (!Finder.TraverseStmt(Args[I]))
11996 return true;
11997 }
11998 }
11999
12000 return false;
12001}
12002
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012003void
12004Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12005 ArrayRef<ParsedType> DynamicExceptions,
12006 ArrayRef<SourceRange> DynamicExceptionRanges,
12007 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012008 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012009 FunctionProtoType::ExtProtoInfo &EPI) {
12010 Exceptions.clear();
12011 EPI.ExceptionSpecType = EST;
12012 if (EST == EST_Dynamic) {
12013 Exceptions.reserve(DynamicExceptions.size());
12014 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12015 // FIXME: Preserve type source info.
12016 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12017
12018 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12019 collectUnexpandedParameterPacks(ET, Unexpanded);
12020 if (!Unexpanded.empty()) {
12021 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12022 UPPC_ExceptionType,
12023 Unexpanded);
12024 continue;
12025 }
12026
12027 // Check that the type is valid for an exception spec, and
12028 // drop it if not.
12029 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12030 Exceptions.push_back(ET);
12031 }
12032 EPI.NumExceptions = Exceptions.size();
12033 EPI.Exceptions = Exceptions.data();
12034 return;
12035 }
12036
12037 if (EST == EST_ComputedNoexcept) {
12038 // If an error occurred, there's no expression here.
12039 if (NoexceptExpr) {
12040 assert((NoexceptExpr->isTypeDependent() ||
12041 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12042 Context.BoolTy) &&
12043 "Parser should have made sure that the expression is boolean");
12044 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12045 EPI.ExceptionSpecType = EST_BasicNoexcept;
12046 return;
12047 }
12048
12049 if (!NoexceptExpr->isValueDependent())
12050 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012051 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012052 /*AllowFold*/ false).take();
12053 EPI.NoexceptExpr = NoexceptExpr;
12054 }
12055 return;
12056 }
12057}
12058
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012059/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12060Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12061 // Implicitly declared functions (e.g. copy constructors) are
12062 // __host__ __device__
12063 if (D->isImplicit())
12064 return CFT_HostDevice;
12065
12066 if (D->hasAttr<CUDAGlobalAttr>())
12067 return CFT_Global;
12068
12069 if (D->hasAttr<CUDADeviceAttr>()) {
12070 if (D->hasAttr<CUDAHostAttr>())
12071 return CFT_HostDevice;
12072 else
12073 return CFT_Device;
12074 }
12075
12076 return CFT_Host;
12077}
12078
12079bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12080 CUDAFunctionTarget CalleeTarget) {
12081 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12082 // Callable from the device only."
12083 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12084 return true;
12085
12086 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12087 // Callable from the host only."
12088 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12089 // Callable from the host only."
12090 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12091 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12092 return true;
12093
12094 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12095 return true;
12096
12097 return false;
12098}