blob: b5fb85856c8103fac0c5075f4a5785b4fdb21ec4 [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
636 // Find first parameter with a default argument
637 for (p = 0; p < NumParams; ++p) {
638 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000639 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000640 break;
641 }
642
643 // C++ [dcl.fct.default]p4:
644 // In a given function declaration, all parameters
645 // subsequent to a parameter with a default argument shall
646 // have default arguments supplied in this or previous
647 // declarations. A default argument shall not be redefined
648 // by a later declaration (not even to the same value).
649 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000650 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000651 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000652 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000653 if (Param->isInvalidDecl())
654 /* We already complained about this parameter. */;
655 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000656 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000657 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000658 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000659 else
Mike Stump1eb44332009-09-09 15:08:12 +0000660 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000661 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Chris Lattner3d1cee32008-04-08 05:04:30 +0000663 LastMissingDefaultArg = p;
664 }
665 }
666
667 if (LastMissingDefaultArg > 0) {
668 // Some default arguments were missing. Clear out all of the
669 // default arguments up to (and including) the last missing
670 // default argument, so that we leave the function parameters
671 // in a semantically valid state.
672 for (p = 0; p <= LastMissingDefaultArg; ++p) {
673 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000674 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000675 Param->setDefaultArg(0);
676 }
677 }
678 }
679}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000680
Richard Smith9f569cc2011-10-01 02:31:28 +0000681// CheckConstexprParameterTypes - Check whether a function's parameter types
682// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000683// diagnostic and return false.
684static bool CheckConstexprParameterTypes(Sema &SemaRef,
685 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000686 unsigned ArgIndex = 0;
687 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
688 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
689 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
690 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
691 SourceLocation ParamLoc = PD->getLocation();
692 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000693 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000694 diag::err_constexpr_non_literal_param,
695 ArgIndex+1, PD->getSourceRange(),
696 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000697 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000698 }
Joao Matos17d35c32012-08-31 22:18:20 +0000699 return true;
700}
701
702/// \brief Get diagnostic %select index for tag kind for
703/// record diagnostic message.
704/// WARNING: Indexes apply to particular diagnostics only!
705///
706/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000707static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000708 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000709 case TTK_Struct: return 0;
710 case TTK_Interface: return 1;
711 case TTK_Class: return 2;
712 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000713 }
Joao Matos17d35c32012-08-31 22:18:20 +0000714}
715
716// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
717// the requirements of a constexpr function definition or a constexpr
718// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000719// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000720//
Richard Smith86c3ae42012-02-13 03:54:03 +0000721// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
722bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000723 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
724 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000725 // C++11 [dcl.constexpr]p4:
726 // The definition of a constexpr constructor shall satisfy the following
727 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000728 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000729 const CXXRecordDecl *RD = MD->getParent();
730 if (RD->getNumVBases()) {
731 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
732 << isa<CXXConstructorDecl>(NewFD)
733 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
734 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
735 E = RD->vbases_end(); I != E; ++I)
736 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000737 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000738 return false;
739 }
Richard Smith35340502012-01-13 04:54:00 +0000740 }
741
742 if (!isa<CXXConstructorDecl>(NewFD)) {
743 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000744 // The definition of a constexpr function shall satisfy the following
745 // constraints:
746 // - it shall not be virtual;
747 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
748 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000749 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000750
Richard Smith86c3ae42012-02-13 03:54:03 +0000751 // If it's not obvious why this function is virtual, find an overridden
752 // function which uses the 'virtual' keyword.
753 const CXXMethodDecl *WrittenVirtual = Method;
754 while (!WrittenVirtual->isVirtualAsWritten())
755 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
756 if (WrittenVirtual != Method)
757 Diag(WrittenVirtual->getLocation(),
758 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000759 return false;
760 }
761
762 // - its return type shall be a literal type;
763 QualType RT = NewFD->getResultType();
764 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000765 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000766 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000767 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000768 }
769
Richard Smith35340502012-01-13 04:54:00 +0000770 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000771 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000772 return false;
773
Richard Smith9f569cc2011-10-01 02:31:28 +0000774 return true;
775}
776
777/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000778/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000779///
Richard Smitha10b9782013-04-22 15:31:51 +0000780/// \return true if the body is OK (maybe only as an extension), false if we
781/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000782static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000783 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
784 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000785 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
786 // contain only
787 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
788 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
789 switch ((*DclIt)->getKind()) {
790 case Decl::StaticAssert:
791 case Decl::Using:
792 case Decl::UsingShadow:
793 case Decl::UsingDirective:
794 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000795 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000796 // - static_assert-declarations
797 // - using-declarations,
798 // - using-directives,
799 continue;
800
801 case Decl::Typedef:
802 case Decl::TypeAlias: {
803 // - typedef declarations and alias-declarations that do not define
804 // classes or enumerations,
805 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
806 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
807 // Don't allow variably-modified types in constexpr functions.
808 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
809 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
810 << TL.getSourceRange() << TL.getType()
811 << isa<CXXConstructorDecl>(Dcl);
812 return false;
813 }
814 continue;
815 }
816
817 case Decl::Enum:
818 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000819 // C++1y allows types to be defined, not just declared.
820 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
821 SemaRef.Diag(DS->getLocStart(),
822 SemaRef.getLangOpts().CPlusPlus1y
823 ? diag::warn_cxx11_compat_constexpr_type_definition
824 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000825 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000826 continue;
827
Richard Smitha10b9782013-04-22 15:31:51 +0000828 case Decl::EnumConstant:
829 case Decl::IndirectField:
830 case Decl::ParmVar:
831 // These can only appear with other declarations which are banned in
832 // C++11 and permitted in C++1y, so ignore them.
833 continue;
834
835 case Decl::Var: {
836 // C++1y [dcl.constexpr]p3 allows anything except:
837 // a definition of a variable of non-literal type or of static or
838 // thread storage duration or for which no initialization is performed.
839 VarDecl *VD = cast<VarDecl>(*DclIt);
840 if (VD->isThisDeclarationADefinition()) {
841 if (VD->isStaticLocal()) {
842 SemaRef.Diag(VD->getLocation(),
843 diag::err_constexpr_local_var_static)
844 << isa<CXXConstructorDecl>(Dcl)
845 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
846 return false;
847 }
848 if (SemaRef.RequireLiteralType(
849 VD->getLocation(), VD->getType(),
850 diag::err_constexpr_local_var_non_literal_type,
851 isa<CXXConstructorDecl>(Dcl)))
852 return false;
853 if (!VD->hasInit()) {
854 SemaRef.Diag(VD->getLocation(),
855 diag::err_constexpr_local_var_no_init)
856 << isa<CXXConstructorDecl>(Dcl);
857 return false;
858 }
859 }
860 SemaRef.Diag(VD->getLocation(),
861 SemaRef.getLangOpts().CPlusPlus1y
862 ? diag::warn_cxx11_compat_constexpr_local_var
863 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000864 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000865 continue;
866 }
867
868 case Decl::NamespaceAlias:
869 case Decl::Function:
870 // These are disallowed in C++11 and permitted in C++1y. Allow them
871 // everywhere as an extension.
872 if (!Cxx1yLoc.isValid())
873 Cxx1yLoc = DS->getLocStart();
874 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000875
876 default:
877 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
878 << isa<CXXConstructorDecl>(Dcl);
879 return false;
880 }
881 }
882
883 return true;
884}
885
886/// Check that the given field is initialized within a constexpr constructor.
887///
888/// \param Dcl The constexpr constructor being checked.
889/// \param Field The field being checked. This may be a member of an anonymous
890/// struct or union nested within the class being checked.
891/// \param Inits All declarations, including anonymous struct/union members and
892/// indirect members, for which any initialization was provided.
893/// \param Diagnosed Set to true if an error is produced.
894static void CheckConstexprCtorInitializer(Sema &SemaRef,
895 const FunctionDecl *Dcl,
896 FieldDecl *Field,
897 llvm::SmallSet<Decl*, 16> &Inits,
898 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000899 if (Field->isUnnamedBitfield())
900 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000901
902 if (Field->isAnonymousStructOrUnion() &&
903 Field->getType()->getAsCXXRecordDecl()->isEmpty())
904 return;
905
Richard Smith9f569cc2011-10-01 02:31:28 +0000906 if (!Inits.count(Field)) {
907 if (!Diagnosed) {
908 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
909 Diagnosed = true;
910 }
911 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
912 } else if (Field->isAnonymousStructOrUnion()) {
913 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
914 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
915 I != E; ++I)
916 // If an anonymous union contains an anonymous struct of which any member
917 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000918 if (!RD->isUnion() || Inits.count(*I))
919 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000920 }
921}
922
Richard Smitha10b9782013-04-22 15:31:51 +0000923/// Check the provided statement is allowed in a constexpr function
924/// definition.
925static bool
926CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
927 llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
928 SourceLocation &Cxx1yLoc) {
929 // - its function-body shall be [...] a compound-statement that contains only
930 switch (S->getStmtClass()) {
931 case Stmt::NullStmtClass:
932 // - null statements,
933 return true;
934
935 case Stmt::DeclStmtClass:
936 // - static_assert-declarations
937 // - using-declarations,
938 // - using-directives,
939 // - typedef declarations and alias-declarations that do not define
940 // classes or enumerations,
941 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
942 return false;
943 return true;
944
945 case Stmt::ReturnStmtClass:
946 // - and exactly one return statement;
947 if (isa<CXXConstructorDecl>(Dcl)) {
948 // C++1y allows return statements in constexpr constructors.
949 if (!Cxx1yLoc.isValid())
950 Cxx1yLoc = S->getLocStart();
951 return true;
952 }
953
954 ReturnStmts.push_back(S->getLocStart());
955 return true;
956
957 case Stmt::CompoundStmtClass: {
958 // C++1y allows compound-statements.
959 if (!Cxx1yLoc.isValid())
960 Cxx1yLoc = S->getLocStart();
961
962 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
963 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
964 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
965 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
966 Cxx1yLoc))
967 return false;
968 }
969 return true;
970 }
971
972 case Stmt::AttributedStmtClass:
973 if (!Cxx1yLoc.isValid())
974 Cxx1yLoc = S->getLocStart();
975 return true;
976
977 case Stmt::IfStmtClass: {
978 // C++1y allows if-statements.
979 if (!Cxx1yLoc.isValid())
980 Cxx1yLoc = S->getLocStart();
981
982 IfStmt *If = cast<IfStmt>(S);
983 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
984 Cxx1yLoc))
985 return false;
986 if (If->getElse() &&
987 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
988 Cxx1yLoc))
989 return false;
990 return true;
991 }
992
993 case Stmt::WhileStmtClass:
994 case Stmt::DoStmtClass:
995 case Stmt::ForStmtClass:
996 case Stmt::CXXForRangeStmtClass:
997 case Stmt::ContinueStmtClass:
998 // C++1y allows all of these. We don't allow them as extensions in C++11,
999 // because they don't make sense without variable mutation.
1000 if (!SemaRef.getLangOpts().CPlusPlus1y)
1001 break;
1002 if (!Cxx1yLoc.isValid())
1003 Cxx1yLoc = S->getLocStart();
1004 for (Stmt::child_range Children = S->children(); Children; ++Children)
1005 if (*Children &&
1006 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1007 Cxx1yLoc))
1008 return false;
1009 return true;
1010
1011 case Stmt::SwitchStmtClass:
1012 case Stmt::CaseStmtClass:
1013 case Stmt::DefaultStmtClass:
1014 case Stmt::BreakStmtClass:
1015 // C++1y allows switch-statements, and since they don't need variable
1016 // mutation, we can reasonably allow them in C++11 as an extension.
1017 if (!Cxx1yLoc.isValid())
1018 Cxx1yLoc = S->getLocStart();
1019 for (Stmt::child_range Children = S->children(); Children; ++Children)
1020 if (*Children &&
1021 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1022 Cxx1yLoc))
1023 return false;
1024 return true;
1025
1026 default:
1027 if (!isa<Expr>(S))
1028 break;
1029
1030 // C++1y allows expression-statements.
1031 if (!Cxx1yLoc.isValid())
1032 Cxx1yLoc = S->getLocStart();
1033 return true;
1034 }
1035
1036 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1037 << isa<CXXConstructorDecl>(Dcl);
1038 return false;
1039}
1040
Richard Smith9f569cc2011-10-01 02:31:28 +00001041/// Check the body for the given constexpr function declaration only contains
1042/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1043///
1044/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001045bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001046 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001047 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001048 // The definition of a constexpr function shall satisfy the following
1049 // constraints: [...]
1050 // - its function-body shall be = delete, = default, or a
1051 // compound-statement
1052 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001053 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001054 // In the definition of a constexpr constructor, [...]
1055 // - its function-body shall not be a function-try-block;
1056 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1057 << isa<CXXConstructorDecl>(Dcl);
1058 return false;
1059 }
1060
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001061 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001062
1063 // - its function-body shall be [...] a compound-statement that contains only
1064 // [... list of cases ...]
1065 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1066 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001067 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1068 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001069 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1070 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001071 }
1072
Richard Smitha10b9782013-04-22 15:31:51 +00001073 if (Cxx1yLoc.isValid())
1074 Diag(Cxx1yLoc,
1075 getLangOpts().CPlusPlus1y
1076 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1077 : diag::ext_constexpr_body_invalid_stmt)
1078 << isa<CXXConstructorDecl>(Dcl);
1079
Richard Smith9f569cc2011-10-01 02:31:28 +00001080 if (const CXXConstructorDecl *Constructor
1081 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1082 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001083 // DR1359:
1084 // - every non-variant non-static data member and base class sub-object
1085 // shall be initialized;
1086 // - if the class is a non-empty union, or for each non-empty anonymous
1087 // union member of a non-union class, exactly one non-static data member
1088 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001089 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001090 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001091 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1092 return false;
1093 }
Richard Smith6e433752011-10-10 16:38:04 +00001094 } else if (!Constructor->isDependentContext() &&
1095 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001096 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1097
1098 // Skip detailed checking if we have enough initializers, and we would
1099 // allow at most one initializer per member.
1100 bool AnyAnonStructUnionMembers = false;
1101 unsigned Fields = 0;
1102 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1103 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001104 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001105 AnyAnonStructUnionMembers = true;
1106 break;
1107 }
1108 }
1109 if (AnyAnonStructUnionMembers ||
1110 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1111 // Check initialization of non-static data members. Base classes are
1112 // always initialized so do not need to be checked. Dependent bases
1113 // might not have initializers in the member initializer list.
1114 llvm::SmallSet<Decl*, 16> Inits;
1115 for (CXXConstructorDecl::init_const_iterator
1116 I = Constructor->init_begin(), E = Constructor->init_end();
1117 I != E; ++I) {
1118 if (FieldDecl *FD = (*I)->getMember())
1119 Inits.insert(FD);
1120 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1121 Inits.insert(ID->chain_begin(), ID->chain_end());
1122 }
1123
1124 bool Diagnosed = false;
1125 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1126 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001127 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001128 if (Diagnosed)
1129 return false;
1130 }
1131 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001132 } else {
1133 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001134 // C++1y doesn't require constexpr functions to contain a 'return'
1135 // statement. We still do, unless the return type is void, because
1136 // otherwise if there's no return statement, the function cannot
1137 // be used in a core constant expression.
1138 Diag(Dcl->getLocation(),
1139 getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType()
1140 ? diag::warn_cxx11_compat_constexpr_body_no_return
1141 : diag::err_constexpr_body_no_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001142 return false;
1143 }
1144 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001145 Diag(ReturnStmts.back(),
1146 getLangOpts().CPlusPlus1y
1147 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1148 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001149 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1150 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001151 }
1152 }
1153
Richard Smith5ba73e12012-02-04 00:33:54 +00001154 // C++11 [dcl.constexpr]p5:
1155 // if no function argument values exist such that the function invocation
1156 // substitution would produce a constant expression, the program is
1157 // ill-formed; no diagnostic required.
1158 // C++11 [dcl.constexpr]p3:
1159 // - every constructor call and implicit conversion used in initializing the
1160 // return value shall be one of those allowed in a constant expression.
1161 // C++11 [dcl.constexpr]p4:
1162 // - every constructor involved in initializing non-static data members and
1163 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001164 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001165 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001166 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001167 << isa<CXXConstructorDecl>(Dcl);
1168 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1169 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001170 // Don't return false here: we allow this for compatibility in
1171 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001172 }
1173
Richard Smith9f569cc2011-10-01 02:31:28 +00001174 return true;
1175}
1176
Douglas Gregorb48fe382008-10-31 09:07:45 +00001177/// isCurrentClassName - Determine whether the identifier II is the
1178/// name of the class type currently being defined. In the case of
1179/// nested classes, this will only return true if II is the name of
1180/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001181bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1182 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001183 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001184
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001185 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001186 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001187 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001188 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1189 } else
1190 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1191
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001192 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001193 return &II == CurDecl->getIdentifier();
1194 else
1195 return false;
1196}
1197
Douglas Gregor229d47a2012-11-10 07:24:09 +00001198/// \brief Determine whether the given class is a base class of the given
1199/// class, including looking at dependent bases.
1200static bool findCircularInheritance(const CXXRecordDecl *Class,
1201 const CXXRecordDecl *Current) {
1202 SmallVector<const CXXRecordDecl*, 8> Queue;
1203
1204 Class = Class->getCanonicalDecl();
1205 while (true) {
1206 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1207 E = Current->bases_end();
1208 I != E; ++I) {
1209 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1210 if (!Base)
1211 continue;
1212
1213 Base = Base->getDefinition();
1214 if (!Base)
1215 continue;
1216
1217 if (Base->getCanonicalDecl() == Class)
1218 return true;
1219
1220 Queue.push_back(Base);
1221 }
1222
1223 if (Queue.empty())
1224 return false;
1225
1226 Current = Queue.back();
1227 Queue.pop_back();
1228 }
1229
1230 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001231}
1232
Mike Stump1eb44332009-09-09 15:08:12 +00001233/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001234///
1235/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1236/// and returns NULL otherwise.
1237CXXBaseSpecifier *
1238Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1239 SourceRange SpecifierRange,
1240 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001241 TypeSourceInfo *TInfo,
1242 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001243 QualType BaseType = TInfo->getType();
1244
Douglas Gregor2943aed2009-03-03 04:44:36 +00001245 // C++ [class.union]p1:
1246 // A union shall not have base classes.
1247 if (Class->isUnion()) {
1248 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1249 << SpecifierRange;
1250 return 0;
1251 }
1252
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001253 if (EllipsisLoc.isValid() &&
1254 !TInfo->getType()->containsUnexpandedParameterPack()) {
1255 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1256 << TInfo->getTypeLoc().getSourceRange();
1257 EllipsisLoc = SourceLocation();
1258 }
Douglas Gregord777e282012-11-10 01:18:17 +00001259
1260 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1261
1262 if (BaseType->isDependentType()) {
1263 // Make sure that we don't have circular inheritance among our dependent
1264 // bases. For non-dependent bases, the check for completeness below handles
1265 // this.
1266 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1267 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1268 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001269 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001270 Diag(BaseLoc, diag::err_circular_inheritance)
1271 << BaseType << Context.getTypeDeclType(Class);
1272
1273 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1274 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1275 << BaseType;
1276
1277 return 0;
1278 }
1279 }
1280
Mike Stump1eb44332009-09-09 15:08:12 +00001281 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001282 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001283 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001284 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001285
1286 // Base specifiers must be record types.
1287 if (!BaseType->isRecordType()) {
1288 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1289 return 0;
1290 }
1291
1292 // C++ [class.union]p1:
1293 // A union shall not be used as a base class.
1294 if (BaseType->isUnionType()) {
1295 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1296 return 0;
1297 }
1298
1299 // C++ [class.derived]p2:
1300 // The class-name in a base-specifier shall not be an incompletely
1301 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001302 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001303 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001304 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001305 return 0;
John McCall572fc622010-08-17 07:23:57 +00001306 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001307
Eli Friedman1d954f62009-08-15 21:55:26 +00001308 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001309 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001310 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001311 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001312 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001313 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1314 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001315
Anders Carlsson1d209272011-03-25 14:55:14 +00001316 // C++ [class]p3:
1317 // If a class is marked final and it appears as a base-type-specifier in
1318 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001319 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001320 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1321 << CXXBaseDecl->getDeclName();
1322 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1323 << CXXBaseDecl->getDeclName();
1324 return 0;
1325 }
1326
John McCall572fc622010-08-17 07:23:57 +00001327 if (BaseDecl->isInvalidDecl())
1328 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001329
1330 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001331 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001332 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001333 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001334}
1335
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001336/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1337/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001338/// example:
1339/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001340/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001341BaseResult
John McCalld226f652010-08-21 09:40:31 +00001342Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001343 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001344 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001345 ParsedType basetype, SourceLocation BaseLoc,
1346 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001347 if (!classdecl)
1348 return true;
1349
Douglas Gregor40808ce2009-03-09 23:48:35 +00001350 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001351 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001352 if (!Class)
1353 return true;
1354
Richard Smith05321402013-02-19 23:47:15 +00001355 // We do not support any C++11 attributes on base-specifiers yet.
1356 // Diagnose any attributes we see.
1357 if (!Attributes.empty()) {
1358 for (AttributeList *Attr = Attributes.getList(); Attr;
1359 Attr = Attr->getNext()) {
1360 if (Attr->isInvalid() ||
1361 Attr->getKind() == AttributeList::IgnoredAttribute)
1362 continue;
1363 Diag(Attr->getLoc(),
1364 Attr->getKind() == AttributeList::UnknownAttribute
1365 ? diag::warn_unknown_attribute_ignored
1366 : diag::err_base_specifier_attribute)
1367 << Attr->getName();
1368 }
1369 }
1370
Nick Lewycky56062202010-07-26 16:56:01 +00001371 TypeSourceInfo *TInfo = 0;
1372 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001373
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001374 if (EllipsisLoc.isInvalid() &&
1375 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001376 UPPC_BaseType))
1377 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001378
Douglas Gregor2943aed2009-03-03 04:44:36 +00001379 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001380 Virtual, Access, TInfo,
1381 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001382 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001383 else
1384 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001385
Douglas Gregor2943aed2009-03-03 04:44:36 +00001386 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001387}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001388
Douglas Gregor2943aed2009-03-03 04:44:36 +00001389/// \brief Performs the actual work of attaching the given base class
1390/// specifiers to a C++ class.
1391bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1392 unsigned NumBases) {
1393 if (NumBases == 0)
1394 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001395
1396 // Used to keep track of which base types we have already seen, so
1397 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001398 // that the key is always the unqualified canonical type of the base
1399 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001400 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1401
1402 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001403 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001404 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001405 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001406 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001407 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001408 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001409
1410 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1411 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001412 // C++ [class.mi]p3:
1413 // A class shall not be specified as a direct base class of a
1414 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001415 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001416 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001417 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001418 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001419
1420 // Delete the duplicate base class specifier; we're going to
1421 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001422 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001423
1424 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001425 } else {
1426 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001427 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001428 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001429 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1430 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1431 if (Class->isInterface() &&
1432 (!RD->isInterface() ||
1433 KnownBase->getAccessSpecifier() != AS_public)) {
1434 // The Microsoft extension __interface does not permit bases that
1435 // are not themselves public interfaces.
1436 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1437 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1438 << RD->getSourceRange();
1439 Invalid = true;
1440 }
1441 if (RD->hasAttr<WeakAttr>())
1442 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1443 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001444 }
1445 }
1446
1447 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001448 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001449
1450 // Delete the remaining (good) base class specifiers, since their
1451 // data has been copied into the CXXRecordDecl.
1452 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001453 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001454
1455 return Invalid;
1456}
1457
1458/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1459/// class, after checking whether there are any duplicate base
1460/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001461void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001462 unsigned NumBases) {
1463 if (!ClassDecl || !Bases || !NumBases)
1464 return;
1465
1466 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001467 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001468 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001469}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001470
Douglas Gregora8f32e02009-10-06 17:59:45 +00001471/// \brief Determine whether the type \p Derived is a C++ class that is
1472/// derived from the type \p Base.
1473bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001474 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001475 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001476
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001477 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001478 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001479 return false;
1480
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001481 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001482 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001483 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001484
1485 // If either the base or the derived type is invalid, don't try to
1486 // check whether one is derived from the other.
1487 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1488 return false;
1489
John McCall86ff3082010-02-04 22:26:26 +00001490 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1491 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001492}
1493
1494/// \brief Determine whether the type \p Derived is a C++ class that is
1495/// derived from the type \p Base.
1496bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001497 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001498 return false;
1499
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001500 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001501 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001502 return false;
1503
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001504 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001505 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001506 return false;
1507
Douglas Gregora8f32e02009-10-06 17:59:45 +00001508 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1509}
1510
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001511void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001512 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001513 assert(BasePathArray.empty() && "Base path array must be empty!");
1514 assert(Paths.isRecordingPaths() && "Must record paths!");
1515
1516 const CXXBasePath &Path = Paths.front();
1517
1518 // We first go backward and check if we have a virtual base.
1519 // FIXME: It would be better if CXXBasePath had the base specifier for
1520 // the nearest virtual base.
1521 unsigned Start = 0;
1522 for (unsigned I = Path.size(); I != 0; --I) {
1523 if (Path[I - 1].Base->isVirtual()) {
1524 Start = I - 1;
1525 break;
1526 }
1527 }
1528
1529 // Now add all bases.
1530 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001531 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001532}
1533
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001534/// \brief Determine whether the given base path includes a virtual
1535/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001536bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1537 for (CXXCastPath::const_iterator B = BasePath.begin(),
1538 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001539 B != BEnd; ++B)
1540 if ((*B)->isVirtual())
1541 return true;
1542
1543 return false;
1544}
1545
Douglas Gregora8f32e02009-10-06 17:59:45 +00001546/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1547/// conversion (where Derived and Base are class types) is
1548/// well-formed, meaning that the conversion is unambiguous (and
1549/// that all of the base classes are accessible). Returns true
1550/// and emits a diagnostic if the code is ill-formed, returns false
1551/// otherwise. Loc is the location where this routine should point to
1552/// if there is an error, and Range is the source range to highlight
1553/// if there is an error.
1554bool
1555Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001556 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001557 unsigned AmbigiousBaseConvID,
1558 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001559 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001560 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001561 // First, determine whether the path from Derived to Base is
1562 // ambiguous. This is slightly more expensive than checking whether
1563 // the Derived to Base conversion exists, because here we need to
1564 // explore multiple paths to determine if there is an ambiguity.
1565 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1566 /*DetectVirtual=*/false);
1567 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1568 assert(DerivationOkay &&
1569 "Can only be used with a derived-to-base conversion");
1570 (void)DerivationOkay;
1571
1572 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001573 if (InaccessibleBaseID) {
1574 // Check that the base class can be accessed.
1575 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1576 InaccessibleBaseID)) {
1577 case AR_inaccessible:
1578 return true;
1579 case AR_accessible:
1580 case AR_dependent:
1581 case AR_delayed:
1582 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001583 }
John McCall6b2accb2010-02-10 09:31:12 +00001584 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001585
1586 // Build a base path if necessary.
1587 if (BasePath)
1588 BuildBasePathArray(Paths, *BasePath);
1589 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001590 }
1591
1592 // We know that the derived-to-base conversion is ambiguous, and
1593 // we're going to produce a diagnostic. Perform the derived-to-base
1594 // search just one more time to compute all of the possible paths so
1595 // that we can print them out. This is more expensive than any of
1596 // the previous derived-to-base checks we've done, but at this point
1597 // performance isn't as much of an issue.
1598 Paths.clear();
1599 Paths.setRecordingPaths(true);
1600 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1601 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1602 (void)StillOkay;
1603
1604 // Build up a textual representation of the ambiguous paths, e.g.,
1605 // D -> B -> A, that will be used to illustrate the ambiguous
1606 // conversions in the diagnostic. We only print one of the paths
1607 // to each base class subobject.
1608 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1609
1610 Diag(Loc, AmbigiousBaseConvID)
1611 << Derived << Base << PathDisplayStr << Range << Name;
1612 return true;
1613}
1614
1615bool
1616Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001617 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001618 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001619 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001620 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001621 IgnoreAccess ? 0
1622 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001623 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001624 Loc, Range, DeclarationName(),
1625 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001626}
1627
1628
1629/// @brief Builds a string representing ambiguous paths from a
1630/// specific derived class to different subobjects of the same base
1631/// class.
1632///
1633/// This function builds a string that can be used in error messages
1634/// to show the different paths that one can take through the
1635/// inheritance hierarchy to go from the derived class to different
1636/// subobjects of a base class. The result looks something like this:
1637/// @code
1638/// struct D -> struct B -> struct A
1639/// struct D -> struct C -> struct A
1640/// @endcode
1641std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1642 std::string PathDisplayStr;
1643 std::set<unsigned> DisplayedPaths;
1644 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1645 Path != Paths.end(); ++Path) {
1646 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1647 // We haven't displayed a path to this particular base
1648 // class subobject yet.
1649 PathDisplayStr += "\n ";
1650 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1651 for (CXXBasePath::const_iterator Element = Path->begin();
1652 Element != Path->end(); ++Element)
1653 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1654 }
1655 }
1656
1657 return PathDisplayStr;
1658}
1659
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001660//===----------------------------------------------------------------------===//
1661// C++ class member Handling
1662//===----------------------------------------------------------------------===//
1663
Abramo Bagnara6206d532010-06-05 05:09:32 +00001664/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001665bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1666 SourceLocation ASLoc,
1667 SourceLocation ColonLoc,
1668 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001669 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001670 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001671 ASLoc, ColonLoc);
1672 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001673 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001674}
1675
Richard Smitha4b39652012-08-06 03:25:17 +00001676/// CheckOverrideControl - Check C++11 override control semantics.
1677void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001678 if (D->isInvalidDecl())
1679 return;
1680
Chris Lattner5f9e2722011-07-23 10:55:15 +00001681 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001682
Richard Smitha4b39652012-08-06 03:25:17 +00001683 // Do we know which functions this declaration might be overriding?
1684 bool OverridesAreKnown = !MD ||
1685 (!MD->getParent()->hasAnyDependentBases() &&
1686 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001687
Richard Smitha4b39652012-08-06 03:25:17 +00001688 if (!MD || !MD->isVirtual()) {
1689 if (OverridesAreKnown) {
1690 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1691 Diag(OA->getLocation(),
1692 diag::override_keyword_only_allowed_on_virtual_member_functions)
1693 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1694 D->dropAttr<OverrideAttr>();
1695 }
1696 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1697 Diag(FA->getLocation(),
1698 diag::override_keyword_only_allowed_on_virtual_member_functions)
1699 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1700 D->dropAttr<FinalAttr>();
1701 }
1702 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001703 return;
1704 }
Richard Smitha4b39652012-08-06 03:25:17 +00001705
1706 if (!OverridesAreKnown)
1707 return;
1708
1709 // C++11 [class.virtual]p5:
1710 // If a virtual function is marked with the virt-specifier override and
1711 // does not override a member function of a base class, the program is
1712 // ill-formed.
1713 bool HasOverriddenMethods =
1714 MD->begin_overridden_methods() != MD->end_overridden_methods();
1715 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1716 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1717 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001718}
1719
Richard Smitha4b39652012-08-06 03:25:17 +00001720/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001721/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001722/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001723bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1724 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001725 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001726 return false;
1727
1728 Diag(New->getLocation(), diag::err_final_function_overridden)
1729 << New->getDeclName();
1730 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1731 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001732}
1733
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001734static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001735 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1736 // FIXME: Destruction of ObjC lifetime types has side-effects.
1737 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1738 return !RD->isCompleteDefinition() ||
1739 !RD->hasTrivialDefaultConstructor() ||
1740 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001741 return false;
1742}
1743
John McCall76da55d2013-04-16 07:28:30 +00001744static AttributeList *getMSPropertyAttr(AttributeList *list) {
1745 for (AttributeList* it = list; it != 0; it = it->getNext())
1746 if (it->isDeclspecPropertyAttribute())
1747 return it;
1748 return 0;
1749}
1750
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001751/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1752/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001753/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001754/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1755/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001756NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001757Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001758 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001759 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001760 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001761 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001762 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1763 DeclarationName Name = NameInfo.getName();
1764 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001765
1766 // For anonymous bitfields, the location should point to the type.
1767 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001768 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001769
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001770 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001771
John McCall4bde1e12010-06-04 08:34:12 +00001772 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001773 assert(!DS.isFriendSpecified());
1774
Richard Smith1ab0d902011-06-25 02:28:38 +00001775 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001776
John McCalle402e722012-09-25 07:32:39 +00001777 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1778 // The Microsoft extension __interface only permits public member functions
1779 // and prohibits constructors, destructors, operators, non-public member
1780 // functions, static methods and data members.
1781 unsigned InvalidDecl;
1782 bool ShowDeclName = true;
1783 if (!isFunc)
1784 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1785 else if (AS != AS_public)
1786 InvalidDecl = 2;
1787 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1788 InvalidDecl = 3;
1789 else switch (Name.getNameKind()) {
1790 case DeclarationName::CXXConstructorName:
1791 InvalidDecl = 4;
1792 ShowDeclName = false;
1793 break;
1794
1795 case DeclarationName::CXXDestructorName:
1796 InvalidDecl = 5;
1797 ShowDeclName = false;
1798 break;
1799
1800 case DeclarationName::CXXOperatorName:
1801 case DeclarationName::CXXConversionFunctionName:
1802 InvalidDecl = 6;
1803 break;
1804
1805 default:
1806 InvalidDecl = 0;
1807 break;
1808 }
1809
1810 if (InvalidDecl) {
1811 if (ShowDeclName)
1812 Diag(Loc, diag::err_invalid_member_in_interface)
1813 << (InvalidDecl-1) << Name;
1814 else
1815 Diag(Loc, diag::err_invalid_member_in_interface)
1816 << (InvalidDecl-1) << "";
1817 return 0;
1818 }
1819 }
1820
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001821 // C++ 9.2p6: A member shall not be declared to have automatic storage
1822 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001823 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1824 // data members and cannot be applied to names declared const or static,
1825 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001826 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001827 case DeclSpec::SCS_unspecified:
1828 case DeclSpec::SCS_typedef:
1829 case DeclSpec::SCS_static:
1830 break;
1831 case DeclSpec::SCS_mutable:
1832 if (isFunc) {
1833 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Richard Smithec642442013-04-12 22:46:28 +00001835 // FIXME: It would be nicer if the keyword was ignored only for this
1836 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001837 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001838 }
1839 break;
1840 default:
1841 Diag(DS.getStorageClassSpecLoc(),
1842 diag::err_storageclass_invalid_for_member);
1843 D.getMutableDeclSpec().ClearStorageClassSpecs();
1844 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001845 }
1846
Sebastian Redl669d5d72008-11-14 23:42:31 +00001847 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1848 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001849 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001850
David Blaikie1d87fba2013-01-30 01:22:18 +00001851 if (DS.isConstexprSpecified() && isInstField) {
1852 SemaDiagnosticBuilder B =
1853 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1854 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1855 if (InitStyle == ICIS_NoInit) {
1856 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1857 D.getMutableDeclSpec().ClearConstexprSpec();
1858 const char *PrevSpec;
1859 unsigned DiagID;
1860 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1861 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001862 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001863 assert(!Failed && "Making a constexpr member const shouldn't fail");
1864 } else {
1865 B << 1;
1866 const char *PrevSpec;
1867 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001868 if (D.getMutableDeclSpec().SetStorageClassSpec(
1869 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001870 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001871 "This is the only DeclSpec that should fail to be applied");
1872 B << 1;
1873 } else {
1874 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1875 isInstField = false;
1876 }
1877 }
1878 }
1879
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001880 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001881 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001882 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001883
1884 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001885 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001886 Diag(Loc, diag::err_bad_variable_name)
1887 << Name;
1888 return 0;
1889 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001890
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001891 IdentifierInfo *II = Name.getAsIdentifierInfo();
1892
Douglas Gregorf2503652011-09-21 14:40:46 +00001893 // Member field could not be with "template" keyword.
1894 // So TemplateParameterLists should be empty in this case.
1895 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001896 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001897 if (TemplateParams->size()) {
1898 // There is no such thing as a member field template.
1899 Diag(D.getIdentifierLoc(), diag::err_template_member)
1900 << II
1901 << SourceRange(TemplateParams->getTemplateLoc(),
1902 TemplateParams->getRAngleLoc());
1903 } else {
1904 // There is an extraneous 'template<>' for this member.
1905 Diag(TemplateParams->getTemplateLoc(),
1906 diag::err_template_member_noparams)
1907 << II
1908 << SourceRange(TemplateParams->getTemplateLoc(),
1909 TemplateParams->getRAngleLoc());
1910 }
1911 return 0;
1912 }
1913
Douglas Gregor922fff22010-10-13 22:19:53 +00001914 if (SS.isSet() && !SS.isInvalid()) {
1915 // The user provided a superfluous scope specifier inside a class
1916 // definition:
1917 //
1918 // class X {
1919 // int X::member;
1920 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001921 if (DeclContext *DC = computeDeclContext(SS, false))
1922 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001923 else
1924 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1925 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001926
Douglas Gregor922fff22010-10-13 22:19:53 +00001927 SS.clear();
1928 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001929
John McCall76da55d2013-04-16 07:28:30 +00001930 AttributeList *MSPropertyAttr =
1931 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1932 if (MSPropertyAttr) {
1933 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1934 BitWidth, InitStyle, AS, MSPropertyAttr);
1935 isInstField = false;
1936 } else {
1937 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1938 BitWidth, InitStyle, AS);
1939 }
Chris Lattner6f8ce142009-03-05 23:03:49 +00001940 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001941 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001942 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001943
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001944 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001945 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001946 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001947 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001948
1949 // Non-instance-fields can't have a bitfield.
1950 if (BitWidth) {
1951 if (Member->isInvalidDecl()) {
1952 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001953 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001954 // C++ 9.6p3: A bit-field shall not be a static member.
1955 // "static member 'A' cannot be a bit-field"
1956 Diag(Loc, diag::err_static_not_bitfield)
1957 << Name << BitWidth->getSourceRange();
1958 } else if (isa<TypedefDecl>(Member)) {
1959 // "typedef member 'x' cannot be a bit-field"
1960 Diag(Loc, diag::err_typedef_not_bitfield)
1961 << Name << BitWidth->getSourceRange();
1962 } else {
1963 // A function typedef ("typedef int f(); f a;").
1964 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1965 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001966 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001967 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001968 }
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Chris Lattner8b963ef2009-03-05 23:01:03 +00001970 BitWidth = 0;
1971 Member->setInvalidDecl();
1972 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001973
1974 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Douglas Gregor37b372b2009-08-20 22:52:58 +00001976 // If we have declared a member function template, set the access of the
1977 // templated declaration as well.
1978 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1979 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001980 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001981
Richard Smitha4b39652012-08-06 03:25:17 +00001982 if (VS.isOverrideSpecified())
1983 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1984 if (VS.isFinalSpecified())
1985 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001986
Douglas Gregorf5251602011-03-08 17:10:18 +00001987 if (VS.getLastLocation().isValid()) {
1988 // Update the end location of a method that has a virt-specifiers.
1989 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1990 MD->setRangeEnd(VS.getLastLocation());
1991 }
Richard Smitha4b39652012-08-06 03:25:17 +00001992
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001993 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001994
Douglas Gregor10bd3682008-11-17 22:58:34 +00001995 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001996
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001997 if (isInstField) {
1998 FieldDecl *FD = cast<FieldDecl>(Member);
1999 FieldCollector->Add(FD);
2000
2001 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2002 FD->getLocation())
2003 != DiagnosticsEngine::Ignored) {
2004 // Remember all explicit private FieldDecls that have a name, no side
2005 // effects and are not part of a dependent type declaration.
2006 if (!FD->isImplicit() && FD->getDeclName() &&
2007 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002008 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002009 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002010 !InitializationHasSideEffects(*FD))
2011 UnusedPrivateFields.insert(FD);
2012 }
2013 }
2014
John McCalld226f652010-08-21 09:40:31 +00002015 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002016}
2017
Hans Wennborg471f9852012-09-18 15:58:06 +00002018namespace {
2019 class UninitializedFieldVisitor
2020 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2021 Sema &S;
2022 ValueDecl *VD;
2023 public:
2024 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2025 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002026 S(S) {
2027 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2028 this->VD = IFD->getAnonField();
2029 else
2030 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002031 }
2032
2033 void HandleExpr(Expr *E) {
2034 if (!E) return;
2035
2036 // Expressions like x(x) sometimes lack the surrounding expressions
2037 // but need to be checked anyways.
2038 HandleValue(E);
2039 Visit(E);
2040 }
2041
2042 void HandleValue(Expr *E) {
2043 E = E->IgnoreParens();
2044
2045 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2046 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002047 return;
2048
2049 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2050 // or union.
2051 MemberExpr *FieldME = ME;
2052
Hans Wennborg471f9852012-09-18 15:58:06 +00002053 Expr *Base = E;
2054 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002055 ME = cast<MemberExpr>(Base);
2056
2057 if (isa<VarDecl>(ME->getMemberDecl()))
2058 return;
2059
2060 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2061 if (!FD->isAnonymousStructOrUnion())
2062 FieldME = ME;
2063
Hans Wennborg471f9852012-09-18 15:58:06 +00002064 Base = ME->getBase();
2065 }
2066
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002067 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00002068 unsigned diag = VD->getType()->isReferenceType()
2069 ? diag::warn_reference_field_is_uninit
2070 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002071 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002072 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002073 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002074 }
2075
2076 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2077 HandleValue(CO->getTrueExpr());
2078 HandleValue(CO->getFalseExpr());
2079 return;
2080 }
2081
2082 if (BinaryConditionalOperator *BCO =
2083 dyn_cast<BinaryConditionalOperator>(E)) {
2084 HandleValue(BCO->getCommon());
2085 HandleValue(BCO->getFalseExpr());
2086 return;
2087 }
2088
2089 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2090 switch (BO->getOpcode()) {
2091 default:
2092 return;
2093 case(BO_PtrMemD):
2094 case(BO_PtrMemI):
2095 HandleValue(BO->getLHS());
2096 return;
2097 case(BO_Comma):
2098 HandleValue(BO->getRHS());
2099 return;
2100 }
2101 }
2102 }
2103
2104 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2105 if (E->getCastKind() == CK_LValueToRValue)
2106 HandleValue(E->getSubExpr());
2107
2108 Inherited::VisitImplicitCastExpr(E);
2109 }
2110
2111 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2112 Expr *Callee = E->getCallee();
2113 if (isa<MemberExpr>(Callee))
2114 HandleValue(Callee);
2115
2116 Inherited::VisitCXXMemberCallExpr(E);
2117 }
2118 };
2119 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2120 ValueDecl *VD) {
2121 UninitializedFieldVisitor(S, VD).HandleExpr(E);
2122 }
2123} // namespace
2124
Richard Smith7a614d82011-06-11 17:19:42 +00002125/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002126/// in-class initializer for a non-static C++ class member, and after
2127/// instantiating an in-class initializer in a class template. Such actions
2128/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002129void
Richard Smithca523302012-06-10 03:12:00 +00002130Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002131 Expr *InitExpr) {
2132 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002133 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2134 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002135
2136 if (!InitExpr) {
2137 FD->setInvalidDecl();
2138 FD->removeInClassInitializer();
2139 return;
2140 }
2141
Peter Collingbournefef21892011-10-23 18:59:44 +00002142 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2143 FD->setInvalidDecl();
2144 FD->removeInClassInitializer();
2145 return;
2146 }
2147
Hans Wennborg471f9852012-09-18 15:58:06 +00002148 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2149 != DiagnosticsEngine::Ignored) {
2150 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2151 }
2152
Richard Smith7a614d82011-06-11 17:19:42 +00002153 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002154 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00002155 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002156 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00002157 << /*at end of ctor*/1 << InitExpr->getSourceRange();
2158 }
Sebastian Redl33deb352012-02-22 10:50:08 +00002159 Expr **Inits = &InitExpr;
2160 unsigned NumInits = 1;
2161 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002162 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002163 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002164 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00002165 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
2166 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00002167 if (Init.isInvalid()) {
2168 FD->setInvalidDecl();
2169 return;
2170 }
Richard Smith7a614d82011-06-11 17:19:42 +00002171 }
2172
Richard Smith41956372013-01-14 22:39:08 +00002173 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002174 // The initialization of each base and member constitutes a
2175 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002176 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002177 if (Init.isInvalid()) {
2178 FD->setInvalidDecl();
2179 return;
2180 }
2181
2182 InitExpr = Init.release();
2183
2184 FD->setInClassInitializer(InitExpr);
2185}
2186
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002187/// \brief Find the direct and/or virtual base specifiers that
2188/// correspond to the given base type, for use in base initialization
2189/// within a constructor.
2190static bool FindBaseInitializer(Sema &SemaRef,
2191 CXXRecordDecl *ClassDecl,
2192 QualType BaseType,
2193 const CXXBaseSpecifier *&DirectBaseSpec,
2194 const CXXBaseSpecifier *&VirtualBaseSpec) {
2195 // First, check for a direct base class.
2196 DirectBaseSpec = 0;
2197 for (CXXRecordDecl::base_class_const_iterator Base
2198 = ClassDecl->bases_begin();
2199 Base != ClassDecl->bases_end(); ++Base) {
2200 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2201 // We found a direct base of this type. That's what we're
2202 // initializing.
2203 DirectBaseSpec = &*Base;
2204 break;
2205 }
2206 }
2207
2208 // Check for a virtual base class.
2209 // FIXME: We might be able to short-circuit this if we know in advance that
2210 // there are no virtual bases.
2211 VirtualBaseSpec = 0;
2212 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2213 // We haven't found a base yet; search the class hierarchy for a
2214 // virtual base class.
2215 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2216 /*DetectVirtual=*/false);
2217 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2218 BaseType, Paths)) {
2219 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2220 Path != Paths.end(); ++Path) {
2221 if (Path->back().Base->isVirtual()) {
2222 VirtualBaseSpec = Path->back().Base;
2223 break;
2224 }
2225 }
2226 }
2227 }
2228
2229 return DirectBaseSpec || VirtualBaseSpec;
2230}
2231
Sebastian Redl6df65482011-09-24 17:48:25 +00002232/// \brief Handle a C++ member initializer using braced-init-list syntax.
2233MemInitResult
2234Sema::ActOnMemInitializer(Decl *ConstructorD,
2235 Scope *S,
2236 CXXScopeSpec &SS,
2237 IdentifierInfo *MemberOrBase,
2238 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002239 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002240 SourceLocation IdLoc,
2241 Expr *InitList,
2242 SourceLocation EllipsisLoc) {
2243 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002244 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002245 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002246}
2247
2248/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002249MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002250Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002251 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002252 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002253 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002254 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002255 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002256 SourceLocation IdLoc,
2257 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002258 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002259 SourceLocation RParenLoc,
2260 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002261 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2262 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002263 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002264 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002265 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002266}
2267
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002268namespace {
2269
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002270// Callback to only accept typo corrections that can be a valid C++ member
2271// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002272class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2273 public:
2274 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2275 : ClassDecl(ClassDecl) {}
2276
2277 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2278 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2279 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2280 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2281 else
2282 return isa<TypeDecl>(ND);
2283 }
2284 return false;
2285 }
2286
2287 private:
2288 CXXRecordDecl *ClassDecl;
2289};
2290
2291}
2292
Sebastian Redl6df65482011-09-24 17:48:25 +00002293/// \brief Handle a C++ member initializer.
2294MemInitResult
2295Sema::BuildMemInitializer(Decl *ConstructorD,
2296 Scope *S,
2297 CXXScopeSpec &SS,
2298 IdentifierInfo *MemberOrBase,
2299 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002300 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002301 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002302 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002303 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002304 if (!ConstructorD)
2305 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002306
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002307 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002308
2309 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002310 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002311 if (!Constructor) {
2312 // The user wrote a constructor initializer on a function that is
2313 // not a C++ constructor. Ignore the error for now, because we may
2314 // have more member initializers coming; we'll diagnose it just
2315 // once in ActOnMemInitializers.
2316 return true;
2317 }
2318
2319 CXXRecordDecl *ClassDecl = Constructor->getParent();
2320
2321 // C++ [class.base.init]p2:
2322 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002323 // constructor's class and, if not found in that scope, are looked
2324 // up in the scope containing the constructor's definition.
2325 // [Note: if the constructor's class contains a member with the
2326 // same name as a direct or virtual base class of the class, a
2327 // mem-initializer-id naming the member or base class and composed
2328 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002329 // mem-initializer-id for the hidden base class may be specified
2330 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002331 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002332 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002333 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002334 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002335 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002336 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002337 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2338 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002339 if (EllipsisLoc.isValid())
2340 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002341 << MemberOrBase
2342 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002343
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002344 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002345 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002346 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002347 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002348 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002349 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002350 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002351
2352 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002353 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002354 } else if (DS.getTypeSpecType() == TST_decltype) {
2355 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002356 } else {
2357 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2358 LookupParsedName(R, S, &SS);
2359
2360 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2361 if (!TyD) {
2362 if (R.isAmbiguous()) return true;
2363
John McCallfd225442010-04-09 19:01:14 +00002364 // We don't want access-control diagnostics here.
2365 R.suppressDiagnostics();
2366
Douglas Gregor7a886e12010-01-19 06:46:48 +00002367 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2368 bool NotUnknownSpecialization = false;
2369 DeclContext *DC = computeDeclContext(SS, false);
2370 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2371 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2372
2373 if (!NotUnknownSpecialization) {
2374 // When the scope specifier can refer to a member of an unknown
2375 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002376 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2377 SS.getWithLocInContext(Context),
2378 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002379 if (BaseType.isNull())
2380 return true;
2381
Douglas Gregor7a886e12010-01-19 06:46:48 +00002382 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002383 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002384 }
2385 }
2386
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002387 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002388 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002389 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002390 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002391 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002392 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002393 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2394 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002395 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002396 // We have found a non-static data member with a similar
2397 // name to what was typed; complain and initialize that
2398 // member.
2399 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2400 << MemberOrBase << true << CorrectedQuotedStr
2401 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2402 Diag(Member->getLocation(), diag::note_previous_decl)
2403 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002404
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002405 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002406 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002407 const CXXBaseSpecifier *DirectBaseSpec;
2408 const CXXBaseSpecifier *VirtualBaseSpec;
2409 if (FindBaseInitializer(*this, ClassDecl,
2410 Context.getTypeDeclType(Type),
2411 DirectBaseSpec, VirtualBaseSpec)) {
2412 // We have found a direct or virtual base class with a
2413 // similar name to what was typed; complain and initialize
2414 // that base class.
2415 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002416 << MemberOrBase << false << CorrectedQuotedStr
2417 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002418
2419 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2420 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002421 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002422 diag::note_base_class_specified_here)
2423 << BaseSpec->getType()
2424 << BaseSpec->getSourceRange();
2425
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002426 TyD = Type;
2427 }
2428 }
2429 }
2430
Douglas Gregor7a886e12010-01-19 06:46:48 +00002431 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002432 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002433 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002434 return true;
2435 }
John McCall2b194412009-12-21 10:41:20 +00002436 }
2437
Douglas Gregor7a886e12010-01-19 06:46:48 +00002438 if (BaseType.isNull()) {
2439 BaseType = Context.getTypeDeclType(TyD);
2440 if (SS.isSet()) {
2441 NestedNameSpecifier *Qualifier =
2442 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002443
Douglas Gregor7a886e12010-01-19 06:46:48 +00002444 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002445 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002446 }
John McCall2b194412009-12-21 10:41:20 +00002447 }
2448 }
Mike Stump1eb44332009-09-09 15:08:12 +00002449
John McCalla93c9342009-12-07 02:54:59 +00002450 if (!TInfo)
2451 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002452
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002453 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002454}
2455
Chandler Carruth81c64772011-09-03 01:14:15 +00002456/// Checks a member initializer expression for cases where reference (or
2457/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002458static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2459 Expr *Init,
2460 SourceLocation IdLoc) {
2461 QualType MemberTy = Member->getType();
2462
2463 // We only handle pointers and references currently.
2464 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2465 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2466 return;
2467
2468 const bool IsPointer = MemberTy->isPointerType();
2469 if (IsPointer) {
2470 if (const UnaryOperator *Op
2471 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2472 // The only case we're worried about with pointers requires taking the
2473 // address.
2474 if (Op->getOpcode() != UO_AddrOf)
2475 return;
2476
2477 Init = Op->getSubExpr();
2478 } else {
2479 // We only handle address-of expression initializers for pointers.
2480 return;
2481 }
2482 }
2483
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002484 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2485 // Taking the address of a temporary will be diagnosed as a hard error.
2486 if (IsPointer)
2487 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002488
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002489 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2490 << Member << Init->getSourceRange();
2491 } else if (const DeclRefExpr *DRE
2492 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2493 // We only warn when referring to a non-reference parameter declaration.
2494 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2495 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002496 return;
2497
2498 S.Diag(Init->getExprLoc(),
2499 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2500 : diag::warn_bind_ref_member_to_parameter)
2501 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002502 } else {
2503 // Other initializers are fine.
2504 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002505 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002506
2507 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2508 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002509}
2510
John McCallf312b1e2010-08-26 23:41:50 +00002511MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002512Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002513 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002514 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2515 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2516 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002517 "Member must be a FieldDecl or IndirectFieldDecl");
2518
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002519 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002520 return true;
2521
Douglas Gregor464b2f02010-11-05 22:21:31 +00002522 if (Member->isInvalidDecl())
2523 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002524
John McCallb4190042009-11-04 23:02:40 +00002525 // Diagnose value-uses of fields to initialize themselves, e.g.
2526 // foo(foo)
2527 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002528 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002529 Expr **Args;
2530 unsigned NumArgs;
2531 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2532 Args = ParenList->getExprs();
2533 NumArgs = ParenList->getNumExprs();
Richard Smithc83c2302012-12-19 01:39:02 +00002534 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002535 Args = InitList->getInits();
2536 NumArgs = InitList->getNumInits();
Richard Smithc83c2302012-12-19 01:39:02 +00002537 } else {
2538 // Template instantiation doesn't reconstruct ParenListExprs for us.
2539 Args = &Init;
2540 NumArgs = 1;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002541 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002542
Richard Trieude5e75c2012-06-14 23:11:34 +00002543 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2544 != DiagnosticsEngine::Ignored)
2545 for (unsigned i = 0; i < NumArgs; ++i)
2546 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002547 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002548 // initializing the i'th field, throw a warning if any of the >= i'th
2549 // fields are used, as they are not yet initialized.
2550 // Right now we are only handling the case where the i'th field uses
2551 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002552 // Also need to take into account that some fields may be initialized by
2553 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002554 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002555
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002556 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002557
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002558 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002559 // Can't check initialization for a member of dependent type or when
2560 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002561 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002562 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002563 bool InitList = false;
2564 if (isa<InitListExpr>(Init)) {
2565 InitList = true;
2566 Args = &Init;
2567 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002568
2569 if (isStdInitializerList(Member->getType(), 0)) {
2570 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2571 << /*at end of ctor*/1 << InitRange;
2572 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002573 }
2574
Chandler Carruth894aed92010-12-06 09:23:57 +00002575 // Initialize the member.
2576 InitializedEntity MemberEntity =
2577 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2578 : InitializedEntity::InitializeMember(IndirectMember, 0);
2579 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002580 InitList ? InitializationKind::CreateDirectList(IdLoc)
2581 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2582 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002583
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002584 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2585 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002586 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002587 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002588 if (MemberInit.isInvalid())
2589 return true;
2590
Richard Smith41956372013-01-14 22:39:08 +00002591 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002592 // The initialization of each base and member constitutes a
2593 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002594 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002595 if (MemberInit.isInvalid())
2596 return true;
2597
Richard Smithc83c2302012-12-19 01:39:02 +00002598 Init = MemberInit.get();
2599 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002600 }
2601
Chandler Carruth894aed92010-12-06 09:23:57 +00002602 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002603 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2604 InitRange.getBegin(), Init,
2605 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002606 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002607 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2608 InitRange.getBegin(), Init,
2609 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002610 }
Eli Friedman59c04372009-07-29 19:44:27 +00002611}
2612
John McCallf312b1e2010-08-26 23:41:50 +00002613MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002614Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002615 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002616 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002617 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002618 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002619 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002620 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002621
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002622 bool InitList = true;
2623 Expr **Args = &Init;
2624 unsigned NumArgs = 1;
2625 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2626 InitList = false;
2627 Args = ParenList->getExprs();
2628 NumArgs = ParenList->getNumExprs();
2629 }
2630
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002631 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002632 // Initialize the object.
2633 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2634 QualType(ClassDecl->getTypeForDecl(), 0));
2635 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002636 InitList ? InitializationKind::CreateDirectList(NameLoc)
2637 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2638 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002639 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2640 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002641 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002642 0);
Sean Hunt41717662011-02-26 19:13:13 +00002643 if (DelegationInit.isInvalid())
2644 return true;
2645
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002646 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2647 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002648
Richard Smith41956372013-01-14 22:39:08 +00002649 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002650 // The initialization of each base and member constitutes a
2651 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002652 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2653 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002654 if (DelegationInit.isInvalid())
2655 return true;
2656
Eli Friedmand21016f2012-05-19 23:35:23 +00002657 // If we are in a dependent context, template instantiation will
2658 // perform this type-checking again. Just save the arguments that we
2659 // received in a ParenListExpr.
2660 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2661 // of the information that we have about the base
2662 // initializer. However, deconstructing the ASTs is a dicey process,
2663 // and this approach is far more likely to get the corner cases right.
2664 if (CurContext->isDependentContext())
2665 DelegationInit = Owned(Init);
2666
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002667 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002668 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002669 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002670}
2671
2672MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002673Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002674 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002675 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002676 SourceLocation BaseLoc
2677 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002678
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002679 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2680 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2681 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2682
2683 // C++ [class.base.init]p2:
2684 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002685 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002686 // of that class, the mem-initializer is ill-formed. A
2687 // mem-initializer-list can initialize a base class using any
2688 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002689 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002690
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002691 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002692 if (EllipsisLoc.isValid()) {
2693 // This is a pack expansion.
2694 if (!BaseType->containsUnexpandedParameterPack()) {
2695 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002696 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002697
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002698 EllipsisLoc = SourceLocation();
2699 }
2700 } else {
2701 // Check for any unexpanded parameter packs.
2702 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2703 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002704
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002705 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002706 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002707 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002708
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002709 // Check for direct and virtual base classes.
2710 const CXXBaseSpecifier *DirectBaseSpec = 0;
2711 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2712 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002713 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2714 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002715 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002716
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002717 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2718 VirtualBaseSpec);
2719
2720 // C++ [base.class.init]p2:
2721 // Unless the mem-initializer-id names a nonstatic data member of the
2722 // constructor's class or a direct or virtual base of that class, the
2723 // mem-initializer is ill-formed.
2724 if (!DirectBaseSpec && !VirtualBaseSpec) {
2725 // If the class has any dependent bases, then it's possible that
2726 // one of those types will resolve to the same type as
2727 // BaseType. Therefore, just treat this as a dependent base
2728 // class initialization. FIXME: Should we try to check the
2729 // initialization anyway? It seems odd.
2730 if (ClassDecl->hasAnyDependentBases())
2731 Dependent = true;
2732 else
2733 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2734 << BaseType << Context.getTypeDeclType(ClassDecl)
2735 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2736 }
2737 }
2738
2739 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002740 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Sebastian Redl6df65482011-09-24 17:48:25 +00002742 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2743 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002744 InitRange.getBegin(), Init,
2745 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002746 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002747
2748 // C++ [base.class.init]p2:
2749 // If a mem-initializer-id is ambiguous because it designates both
2750 // a direct non-virtual base class and an inherited virtual base
2751 // class, the mem-initializer is ill-formed.
2752 if (DirectBaseSpec && VirtualBaseSpec)
2753 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002754 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002755
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002756 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002757 if (!BaseSpec)
2758 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2759
2760 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002761 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002762 Expr **Args = &Init;
2763 unsigned NumArgs = 1;
2764 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002765 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002766 Args = ParenList->getExprs();
2767 NumArgs = ParenList->getNumExprs();
2768 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002769
2770 InitializedEntity BaseEntity =
2771 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2772 InitializationKind Kind =
2773 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2774 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2775 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002776 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2777 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002778 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002779 if (BaseInit.isInvalid())
2780 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002781
Richard Smith41956372013-01-14 22:39:08 +00002782 // C++11 [class.base.init]p7:
2783 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002784 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002785 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002786 if (BaseInit.isInvalid())
2787 return true;
2788
2789 // If we are in a dependent context, template instantiation will
2790 // perform this type-checking again. Just save the arguments that we
2791 // received in a ParenListExpr.
2792 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2793 // of the information that we have about the base
2794 // initializer. However, deconstructing the ASTs is a dicey process,
2795 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002796 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002797 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002798
Sean Huntcbb67482011-01-08 20:30:50 +00002799 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002800 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002801 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002802 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002803 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002804}
2805
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002806// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002807static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2808 if (T.isNull()) T = E->getType();
2809 QualType TargetType = SemaRef.BuildReferenceType(
2810 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002811 SourceLocation ExprLoc = E->getLocStart();
2812 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2813 TargetType, ExprLoc);
2814
2815 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2816 SourceRange(ExprLoc, ExprLoc),
2817 E->getSourceRange()).take();
2818}
2819
Anders Carlssone5ef7402010-04-23 03:10:23 +00002820/// ImplicitInitializerKind - How an implicit base or member initializer should
2821/// initialize its base or member.
2822enum ImplicitInitializerKind {
2823 IIK_Default,
2824 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002825 IIK_Move,
2826 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002827};
2828
Anders Carlssondefefd22010-04-23 02:00:02 +00002829static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002830BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002831 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002832 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002833 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002834 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002835 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002836 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2837 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002838
John McCall60d7b3a2010-08-24 06:29:42 +00002839 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002840
2841 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002842 case IIK_Inherit: {
2843 const CXXRecordDecl *Inherited =
2844 Constructor->getInheritedConstructor()->getParent();
2845 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2846 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2847 // C++11 [class.inhctor]p8:
2848 // Each expression in the expression-list is of the form
2849 // static_cast<T&&>(p), where p is the name of the corresponding
2850 // constructor parameter and T is the declared type of p.
2851 SmallVector<Expr*, 16> Args;
2852 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2853 ParmVarDecl *PD = Constructor->getParamDecl(I);
2854 ExprResult ArgExpr =
2855 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2856 VK_LValue, SourceLocation());
2857 if (ArgExpr.isInvalid())
2858 return true;
2859 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2860 }
2861
2862 InitializationKind InitKind = InitializationKind::CreateDirect(
2863 Constructor->getLocation(), SourceLocation(), SourceLocation());
2864 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2865 Args.data(), Args.size());
2866 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2867 break;
2868 }
2869 }
2870 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002871 case IIK_Default: {
2872 InitializationKind InitKind
2873 = InitializationKind::CreateDefault(Constructor->getLocation());
2874 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002875 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002876 break;
2877 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002878
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002879 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002880 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002881 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002882 ParmVarDecl *Param = Constructor->getParamDecl(0);
2883 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002884
Anders Carlssone5ef7402010-04-23 03:10:23 +00002885 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002886 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002887 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002888 Constructor->getLocation(), ParamType,
2889 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002890
Eli Friedman5f2987c2012-02-02 03:46:19 +00002891 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2892
Anders Carlssonc7957502010-04-24 22:02:54 +00002893 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002894 QualType ArgTy =
2895 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2896 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002897
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002898 if (Moving) {
2899 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2900 }
2901
John McCallf871d0c2010-08-07 06:22:56 +00002902 CXXCastPath BasePath;
2903 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002904 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2905 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002906 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002907 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002908
Anders Carlssone5ef7402010-04-23 03:10:23 +00002909 InitializationKind InitKind
2910 = InitializationKind::CreateDirect(Constructor->getLocation(),
2911 SourceLocation(), SourceLocation());
2912 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2913 &CopyCtorArg, 1);
2914 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002915 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002916 break;
2917 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002918 }
John McCall9ae2f072010-08-23 23:25:46 +00002919
Douglas Gregor53c374f2010-12-07 00:41:46 +00002920 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002921 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002922 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002923
Anders Carlssondefefd22010-04-23 02:00:02 +00002924 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002925 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002926 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2927 SourceLocation()),
2928 BaseSpec->isVirtual(),
2929 SourceLocation(),
2930 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002931 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002932 SourceLocation());
2933
Anders Carlssondefefd22010-04-23 02:00:02 +00002934 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002935}
2936
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002937static bool RefersToRValueRef(Expr *MemRef) {
2938 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2939 return Referenced->getType()->isRValueReferenceType();
2940}
2941
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002942static bool
2943BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002944 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002945 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002946 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002947 if (Field->isInvalidDecl())
2948 return true;
2949
Chandler Carruthf186b542010-06-29 23:50:44 +00002950 SourceLocation Loc = Constructor->getLocation();
2951
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002952 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2953 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002954 ParmVarDecl *Param = Constructor->getParamDecl(0);
2955 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002956
2957 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002958 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2959 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002960
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002961 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002962 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002963 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002964 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002965
Eli Friedman5f2987c2012-02-02 03:46:19 +00002966 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2967
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002968 if (Moving) {
2969 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2970 }
2971
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002972 // Build a reference to this field within the parameter.
2973 CXXScopeSpec SS;
2974 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2975 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002976 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2977 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002978 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002979 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002980 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002981 ParamType, Loc,
2982 /*IsArrow=*/false,
2983 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002984 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002985 /*FirstQualifierInScope=*/0,
2986 MemberLookup,
2987 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002988 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002989 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002990
2991 // C++11 [class.copy]p15:
2992 // - if a member m has rvalue reference type T&&, it is direct-initialized
2993 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002994 if (RefersToRValueRef(CtorArg.get())) {
2995 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002996 }
2997
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002998 // When the field we are copying is an array, create index variables for
2999 // each dimension of the array. We use these index variables to subscript
3000 // the source array, and other clients (e.g., CodeGen) will perform the
3001 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003002 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003003 QualType BaseType = Field->getType();
3004 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003005 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003006 while (const ConstantArrayType *Array
3007 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003008 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003009 // Create the iteration variable for this array index.
3010 IdentifierInfo *IterationVarName = 0;
3011 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003012 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003013 llvm::raw_svector_ostream OS(Str);
3014 OS << "__i" << IndexVariables.size();
3015 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3016 }
3017 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003018 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003019 IterationVarName, SizeType,
3020 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003021 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003022 IndexVariables.push_back(IterationVar);
3023
3024 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003025 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003026 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003027 assert(!IterationVarRef.isInvalid() &&
3028 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003029 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3030 assert(!IterationVarRef.isInvalid() &&
3031 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003032
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003033 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003034 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003035 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003036 Loc);
3037 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003038 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003039
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003040 BaseType = Array->getElementType();
3041 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003042
3043 // The array subscript expression is an lvalue, which is wrong for moving.
3044 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003045 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003046
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003047 // Construct the entity that we will be initializing. For an array, this
3048 // will be first element in the array, which may require several levels
3049 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003050 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003051 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003052 if (Indirect)
3053 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3054 else
3055 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003056 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3057 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3058 0,
3059 Entities.back()));
3060
3061 // Direct-initialize to use the copy constructor.
3062 InitializationKind InitKind =
3063 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3064
Sebastian Redl74e611a2011-09-04 18:14:28 +00003065 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003066 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003067 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003068
John McCall60d7b3a2010-08-24 06:29:42 +00003069 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003070 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003071 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003072 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003073 if (MemberInit.isInvalid())
3074 return true;
3075
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003076 if (Indirect) {
3077 assert(IndexVariables.size() == 0 &&
3078 "Indirect field improperly initialized");
3079 CXXMemberInit
3080 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3081 Loc, Loc,
3082 MemberInit.takeAs<Expr>(),
3083 Loc);
3084 } else
3085 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3086 Loc, MemberInit.takeAs<Expr>(),
3087 Loc,
3088 IndexVariables.data(),
3089 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003090 return false;
3091 }
3092
Richard Smith07b0fdc2013-03-18 21:12:30 +00003093 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3094 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003095
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003096 QualType FieldBaseElementType =
3097 SemaRef.Context.getBaseElementType(Field->getType());
3098
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003099 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003100 InitializedEntity InitEntity
3101 = Indirect? InitializedEntity::InitializeMember(Indirect)
3102 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003103 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003104 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003105
3106 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00003107 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00003108 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00003109
Douglas Gregor53c374f2010-12-07 00:41:46 +00003110 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003111 if (MemberInit.isInvalid())
3112 return true;
3113
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003114 if (Indirect)
3115 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3116 Indirect, Loc,
3117 Loc,
3118 MemberInit.get(),
3119 Loc);
3120 else
3121 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3122 Field, Loc, Loc,
3123 MemberInit.get(),
3124 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003125 return false;
3126 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003127
Sean Hunt1f2f3842011-05-17 00:19:05 +00003128 if (!Field->getParent()->isUnion()) {
3129 if (FieldBaseElementType->isReferenceType()) {
3130 SemaRef.Diag(Constructor->getLocation(),
3131 diag::err_uninitialized_member_in_ctor)
3132 << (int)Constructor->isImplicit()
3133 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3134 << 0 << Field->getDeclName();
3135 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3136 return true;
3137 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003138
Sean Hunt1f2f3842011-05-17 00:19:05 +00003139 if (FieldBaseElementType.isConstQualified()) {
3140 SemaRef.Diag(Constructor->getLocation(),
3141 diag::err_uninitialized_member_in_ctor)
3142 << (int)Constructor->isImplicit()
3143 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3144 << 1 << Field->getDeclName();
3145 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3146 return true;
3147 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003148 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003149
David Blaikie4e4d0842012-03-11 07:00:24 +00003150 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003151 FieldBaseElementType->isObjCRetainableType() &&
3152 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3153 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003154 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003155 // Default-initialize Objective-C pointers to NULL.
3156 CXXMemberInit
3157 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3158 Loc, Loc,
3159 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3160 Loc);
3161 return false;
3162 }
3163
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003164 // Nothing to initialize.
3165 CXXMemberInit = 0;
3166 return false;
3167}
John McCallf1860e52010-05-20 23:23:51 +00003168
3169namespace {
3170struct BaseAndFieldInfo {
3171 Sema &S;
3172 CXXConstructorDecl *Ctor;
3173 bool AnyErrorsInInits;
3174 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003175 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003176 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003177
3178 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3179 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003180 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3181 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003182 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003183 else if (Generated && Ctor->isMoveConstructor())
3184 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003185 else if (Ctor->getInheritedConstructor())
3186 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003187 else
3188 IIK = IIK_Default;
3189 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003190
3191 bool isImplicitCopyOrMove() const {
3192 switch (IIK) {
3193 case IIK_Copy:
3194 case IIK_Move:
3195 return true;
3196
3197 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003198 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003199 return false;
3200 }
David Blaikie30263482012-01-20 21:50:17 +00003201
3202 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003203 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003204
3205 bool addFieldInitializer(CXXCtorInitializer *Init) {
3206 AllToInit.push_back(Init);
3207
3208 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003209 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003210 S.UnusedPrivateFields.remove(Init->getAnyMember());
3211
3212 return false;
3213 }
John McCallf1860e52010-05-20 23:23:51 +00003214};
3215}
3216
Richard Smitha4950662011-09-19 13:34:43 +00003217/// \brief Determine whether the given indirect field declaration is somewhere
3218/// within an anonymous union.
3219static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3220 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3221 CEnd = F->chain_end();
3222 C != CEnd; ++C)
3223 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3224 if (Record->isUnion())
3225 return true;
3226
3227 return false;
3228}
3229
Douglas Gregorddb21472011-11-02 23:04:16 +00003230/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3231/// array type.
3232static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3233 if (T->isIncompleteArrayType())
3234 return true;
3235
3236 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3237 if (!ArrayT->getSize())
3238 return true;
3239
3240 T = ArrayT->getElementType();
3241 }
3242
3243 return false;
3244}
3245
Richard Smith7a614d82011-06-11 17:19:42 +00003246static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003247 FieldDecl *Field,
3248 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003249
Chandler Carruthe861c602010-06-30 02:59:29 +00003250 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003251 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3252 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003253
Richard Smith0b8220a2012-08-07 21:30:42 +00003254 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003255 // has a brace-or-equal-initializer, the entity is initialized as specified
3256 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003257 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003258 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3259 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003260 CXXCtorInitializer *Init;
3261 if (Indirect)
3262 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3263 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003264 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003265 SourceLocation());
3266 else
3267 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3268 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003269 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003270 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003271 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003272 }
3273
Richard Smithc115f632011-09-18 11:14:50 +00003274 // Don't build an implicit initializer for union members if none was
3275 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003276 if (Field->getParent()->isUnion() ||
3277 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003278 return false;
3279
Douglas Gregorddb21472011-11-02 23:04:16 +00003280 // Don't initialize incomplete or zero-length arrays.
3281 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3282 return false;
3283
John McCallf1860e52010-05-20 23:23:51 +00003284 // Don't try to build an implicit initializer if there were semantic
3285 // errors in any of the initializers (and therefore we might be
3286 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003287 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003288 return false;
3289
Sean Huntcbb67482011-01-08 20:30:50 +00003290 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003291 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3292 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003293 return true;
John McCallf1860e52010-05-20 23:23:51 +00003294
Richard Smith0b8220a2012-08-07 21:30:42 +00003295 if (!Init)
3296 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003297
Richard Smith0b8220a2012-08-07 21:30:42 +00003298 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003299}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003300
3301bool
3302Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3303 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003304 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003305 Constructor->setNumCtorInitializers(1);
3306 CXXCtorInitializer **initializer =
3307 new (Context) CXXCtorInitializer*[1];
3308 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3309 Constructor->setCtorInitializers(initializer);
3310
Sean Huntb76af9c2011-05-03 23:05:34 +00003311 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003312 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003313 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3314 }
3315
Sean Huntc1598702011-05-05 00:05:47 +00003316 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003317
Sean Hunt059ce0d2011-05-01 07:04:31 +00003318 return false;
3319}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003320
David Blaikie93c86172013-01-17 05:26:25 +00003321bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3322 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003323 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003324 // Just store the initializers as written, they will be checked during
3325 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003326 if (!Initializers.empty()) {
3327 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003328 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003329 new (Context) CXXCtorInitializer*[Initializers.size()];
3330 memcpy(baseOrMemberInitializers, Initializers.data(),
3331 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003332 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003333 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003334
3335 // Let template instantiation know whether we had errors.
3336 if (AnyErrors)
3337 Constructor->setInvalidDecl();
3338
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003339 return false;
3340 }
3341
John McCallf1860e52010-05-20 23:23:51 +00003342 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003343
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003344 // We need to build the initializer AST according to order of construction
3345 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003346 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003347 if (!ClassDecl)
3348 return true;
3349
Eli Friedman80c30da2009-11-09 19:20:36 +00003350 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003351
David Blaikie93c86172013-01-17 05:26:25 +00003352 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003353 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003354
3355 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003356 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003357 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003358 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003359 }
3360
Anders Carlsson711f34a2010-04-21 19:52:01 +00003361 // Keep track of the direct virtual bases.
3362 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3363 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3364 E = ClassDecl->bases_end(); I != E; ++I) {
3365 if (I->isVirtual())
3366 DirectVBases.insert(I);
3367 }
3368
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003369 // Push virtual bases before others.
3370 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3371 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3372
Sean Huntcbb67482011-01-08 20:30:50 +00003373 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003374 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3375 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003376 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003377 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003378 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003379 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003380 VBase, IsInheritedVirtualBase,
3381 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003382 HadError = true;
3383 continue;
3384 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003385
John McCallf1860e52010-05-20 23:23:51 +00003386 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003387 }
3388 }
Mike Stump1eb44332009-09-09 15:08:12 +00003389
John McCallf1860e52010-05-20 23:23:51 +00003390 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003391 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3392 E = ClassDecl->bases_end(); Base != E; ++Base) {
3393 // Virtuals are in the virtual base list and already constructed.
3394 if (Base->isVirtual())
3395 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003396
Sean Huntcbb67482011-01-08 20:30:50 +00003397 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003398 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3399 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003400 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003401 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003402 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003403 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003404 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003405 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003406 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003407 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003408
John McCallf1860e52010-05-20 23:23:51 +00003409 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003410 }
3411 }
Mike Stump1eb44332009-09-09 15:08:12 +00003412
John McCallf1860e52010-05-20 23:23:51 +00003413 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003414 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3415 MemEnd = ClassDecl->decls_end();
3416 Mem != MemEnd; ++Mem) {
3417 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003418 // C++ [class.bit]p2:
3419 // A declaration for a bit-field that omits the identifier declares an
3420 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3421 // initialized.
3422 if (F->isUnnamedBitfield())
3423 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003424
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003425 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003426 // handle anonymous struct/union fields based on their individual
3427 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003428 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003429 continue;
3430
3431 if (CollectFieldInitializer(*this, Info, F))
3432 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003433 continue;
3434 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003435
3436 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003437 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003438 continue;
3439
3440 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3441 if (F->getType()->isIncompleteArrayType()) {
3442 assert(ClassDecl->hasFlexibleArrayMember() &&
3443 "Incomplete array type is not valid");
3444 continue;
3445 }
3446
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003447 // Initialize each field of an anonymous struct individually.
3448 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3449 HadError = true;
3450
3451 continue;
3452 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003453 }
Mike Stump1eb44332009-09-09 15:08:12 +00003454
David Blaikie93c86172013-01-17 05:26:25 +00003455 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003456 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003457 Constructor->setNumCtorInitializers(NumInitializers);
3458 CXXCtorInitializer **baseOrMemberInitializers =
3459 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003460 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003461 NumInitializers * sizeof(CXXCtorInitializer*));
3462 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003463
John McCallef027fe2010-03-16 21:39:52 +00003464 // Constructors implicitly reference the base and member
3465 // destructors.
3466 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3467 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003468 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003469
3470 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003471}
3472
David Blaikieee000bb2013-01-17 08:49:22 +00003473static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003474 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003475 const RecordDecl *RD = RT->getDecl();
3476 if (RD->isAnonymousStructOrUnion()) {
3477 for (RecordDecl::field_iterator Field = RD->field_begin(),
3478 E = RD->field_end(); Field != E; ++Field)
3479 PopulateKeysForFields(*Field, IdealInits);
3480 return;
3481 }
Eli Friedman6347f422009-07-21 19:28:10 +00003482 }
David Blaikieee000bb2013-01-17 08:49:22 +00003483 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003484}
3485
Anders Carlssonea356fb2010-04-02 05:42:15 +00003486static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003487 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003488}
3489
Anders Carlssonea356fb2010-04-02 05:42:15 +00003490static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003491 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003492 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003493 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003494
David Blaikieee000bb2013-01-17 08:49:22 +00003495 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003496}
3497
David Blaikie93c86172013-01-17 05:26:25 +00003498static void DiagnoseBaseOrMemInitializerOrder(
3499 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3500 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003501 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003502 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003503
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003504 // Don't check initializers order unless the warning is enabled at the
3505 // location of at least one initializer.
3506 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003507 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003508 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003509 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3510 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003511 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003512 ShouldCheckOrder = true;
3513 break;
3514 }
3515 }
3516 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003517 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003518
John McCalld6ca8da2010-04-10 07:37:23 +00003519 // Build the list of bases and members in the order that they'll
3520 // actually be initialized. The explicit initializers should be in
3521 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003522 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003523
Anders Carlsson071d6102010-04-02 03:38:04 +00003524 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3525
John McCalld6ca8da2010-04-10 07:37:23 +00003526 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003527 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003528 ClassDecl->vbases_begin(),
3529 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003530 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003531
John McCalld6ca8da2010-04-10 07:37:23 +00003532 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003533 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003534 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003535 if (Base->isVirtual())
3536 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003537 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003538 }
Mike Stump1eb44332009-09-09 15:08:12 +00003539
John McCalld6ca8da2010-04-10 07:37:23 +00003540 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003541 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003542 E = ClassDecl->field_end(); Field != E; ++Field) {
3543 if (Field->isUnnamedBitfield())
3544 continue;
3545
David Blaikieee000bb2013-01-17 08:49:22 +00003546 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003547 }
3548
John McCalld6ca8da2010-04-10 07:37:23 +00003549 unsigned NumIdealInits = IdealInitKeys.size();
3550 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003551
Sean Huntcbb67482011-01-08 20:30:50 +00003552 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003553 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003554 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003555 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003556
3557 // Scan forward to try to find this initializer in the idealized
3558 // initializers list.
3559 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3560 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003561 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003562
3563 // If we didn't find this initializer, it must be because we
3564 // scanned past it on a previous iteration. That can only
3565 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003566 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003567 Sema::SemaDiagnosticBuilder D =
3568 SemaRef.Diag(PrevInit->getSourceLocation(),
3569 diag::warn_initializer_out_of_order);
3570
Francois Pichet00eb3f92010-12-04 09:14:42 +00003571 if (PrevInit->isAnyMemberInitializer())
3572 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003573 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003574 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003575
Francois Pichet00eb3f92010-12-04 09:14:42 +00003576 if (Init->isAnyMemberInitializer())
3577 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003578 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003579 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003580
3581 // Move back to the initializer's location in the ideal list.
3582 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3583 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003584 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003585
3586 assert(IdealIndex != NumIdealInits &&
3587 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003588 }
John McCalld6ca8da2010-04-10 07:37:23 +00003589
3590 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003591 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003592}
3593
John McCall3c3ccdb2010-04-10 09:28:51 +00003594namespace {
3595bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003596 CXXCtorInitializer *Init,
3597 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003598 if (!PrevInit) {
3599 PrevInit = Init;
3600 return false;
3601 }
3602
Douglas Gregordc392c12013-03-25 23:28:23 +00003603 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003604 S.Diag(Init->getSourceLocation(),
3605 diag::err_multiple_mem_initialization)
3606 << Field->getDeclName()
3607 << Init->getSourceRange();
3608 else {
John McCallf4c73712011-01-19 06:33:43 +00003609 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003610 assert(BaseClass && "neither field nor base");
3611 S.Diag(Init->getSourceLocation(),
3612 diag::err_multiple_base_initialization)
3613 << QualType(BaseClass, 0)
3614 << Init->getSourceRange();
3615 }
3616 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3617 << 0 << PrevInit->getSourceRange();
3618
3619 return true;
3620}
3621
Sean Huntcbb67482011-01-08 20:30:50 +00003622typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003623typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3624
3625bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003626 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003627 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003628 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003629 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003630 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003631
3632 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003633 if (Parent->isUnion()) {
3634 UnionEntry &En = Unions[Parent];
3635 if (En.first && En.first != Child) {
3636 S.Diag(Init->getSourceLocation(),
3637 diag::err_multiple_mem_union_initialization)
3638 << Field->getDeclName()
3639 << Init->getSourceRange();
3640 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3641 << 0 << En.second->getSourceRange();
3642 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003643 }
3644 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003645 En.first = Child;
3646 En.second = Init;
3647 }
David Blaikie6fe29652011-11-17 06:01:57 +00003648 if (!Parent->isAnonymousStructOrUnion())
3649 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003650 }
3651
3652 Child = Parent;
3653 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003654 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003655
3656 return false;
3657}
3658}
3659
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003660/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003661void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003662 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003663 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003664 bool AnyErrors) {
3665 if (!ConstructorDecl)
3666 return;
3667
3668 AdjustDeclIfTemplate(ConstructorDecl);
3669
3670 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003671 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003672
3673 if (!Constructor) {
3674 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3675 return;
3676 }
3677
John McCall3c3ccdb2010-04-10 09:28:51 +00003678 // Mapping for the duplicate initializers check.
3679 // For member initializers, this is keyed with a FieldDecl*.
3680 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003681 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003682
3683 // Mapping for the inconsistent anonymous-union initializers check.
3684 RedundantUnionMap MemberUnions;
3685
Anders Carlssonea356fb2010-04-02 05:42:15 +00003686 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003687 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003688 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003689
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003690 // Set the source order index.
3691 Init->setSourceOrder(i);
3692
Francois Pichet00eb3f92010-12-04 09:14:42 +00003693 if (Init->isAnyMemberInitializer()) {
3694 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003695 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3696 CheckRedundantUnionInit(*this, Init, MemberUnions))
3697 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003698 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003699 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3700 if (CheckRedundantInit(*this, Init, Members[Key]))
3701 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003702 } else {
3703 assert(Init->isDelegatingInitializer());
3704 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003705 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003706 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003707 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003708 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003709 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003710 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003711 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003712 // Return immediately as the initializer is set.
3713 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003714 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003715 }
3716
Anders Carlssonea356fb2010-04-02 05:42:15 +00003717 if (HadError)
3718 return;
3719
David Blaikie93c86172013-01-17 05:26:25 +00003720 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003721
David Blaikie93c86172013-01-17 05:26:25 +00003722 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003723}
3724
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003725void
John McCallef027fe2010-03-16 21:39:52 +00003726Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3727 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003728 // Ignore dependent contexts. Also ignore unions, since their members never
3729 // have destructors implicitly called.
3730 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003731 return;
John McCall58e6f342010-03-16 05:22:47 +00003732
3733 // FIXME: all the access-control diagnostics are positioned on the
3734 // field/base declaration. That's probably good; that said, the
3735 // user might reasonably want to know why the destructor is being
3736 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003737
Anders Carlsson9f853df2009-11-17 04:44:12 +00003738 // Non-static data members.
3739 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3740 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003741 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003742 if (Field->isInvalidDecl())
3743 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003744
3745 // Don't destroy incomplete or zero-length arrays.
3746 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3747 continue;
3748
Anders Carlsson9f853df2009-11-17 04:44:12 +00003749 QualType FieldType = Context.getBaseElementType(Field->getType());
3750
3751 const RecordType* RT = FieldType->getAs<RecordType>();
3752 if (!RT)
3753 continue;
3754
3755 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003756 if (FieldClassDecl->isInvalidDecl())
3757 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003758 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003759 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003760 // The destructor for an implicit anonymous union member is never invoked.
3761 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3762 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003763
Douglas Gregordb89f282010-07-01 22:47:18 +00003764 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003765 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003766 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003767 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003768 << Field->getDeclName()
3769 << FieldType);
3770
Eli Friedman5f2987c2012-02-02 03:46:19 +00003771 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003772 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003773 }
3774
John McCall58e6f342010-03-16 05:22:47 +00003775 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3776
Anders Carlsson9f853df2009-11-17 04:44:12 +00003777 // Bases.
3778 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3779 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003780 // Bases are always records in a well-formed non-dependent class.
3781 const RecordType *RT = Base->getType()->getAs<RecordType>();
3782
3783 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003784 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003785 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003786
John McCall58e6f342010-03-16 05:22:47 +00003787 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003788 // If our base class is invalid, we probably can't get its dtor anyway.
3789 if (BaseClassDecl->isInvalidDecl())
3790 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003791 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003792 continue;
John McCall58e6f342010-03-16 05:22:47 +00003793
Douglas Gregordb89f282010-07-01 22:47:18 +00003794 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003795 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003796
3797 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003798 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003799 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003800 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003801 << Base->getSourceRange(),
3802 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003803
Eli Friedman5f2987c2012-02-02 03:46:19 +00003804 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003805 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003806 }
3807
3808 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003809 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3810 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003811
3812 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003813 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003814
3815 // Ignore direct virtual bases.
3816 if (DirectVirtualBases.count(RT))
3817 continue;
3818
John McCall58e6f342010-03-16 05:22:47 +00003819 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003820 // If our base class is invalid, we probably can't get its dtor anyway.
3821 if (BaseClassDecl->isInvalidDecl())
3822 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003823 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003824 continue;
John McCall58e6f342010-03-16 05:22:47 +00003825
Douglas Gregordb89f282010-07-01 22:47:18 +00003826 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003827 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003828 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003829 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003830 << VBase->getType(),
3831 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003832
Eli Friedman5f2987c2012-02-02 03:46:19 +00003833 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003834 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003835 }
3836}
3837
John McCalld226f652010-08-21 09:40:31 +00003838void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003839 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003840 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003841
Mike Stump1eb44332009-09-09 15:08:12 +00003842 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003843 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003844 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003845}
3846
Mike Stump1eb44332009-09-09 15:08:12 +00003847bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003848 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003849 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3850 unsigned DiagID;
3851 AbstractDiagSelID SelID;
3852
3853 public:
3854 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3855 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3856
3857 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003858 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003859 if (SelID == -1)
3860 S.Diag(Loc, DiagID) << T;
3861 else
3862 S.Diag(Loc, DiagID) << SelID << T;
3863 }
3864 } Diagnoser(DiagID, SelID);
3865
3866 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003867}
3868
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003869bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003870 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003871 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003872 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003873
Anders Carlsson11f21a02009-03-23 19:10:31 +00003874 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003875 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003876
Ted Kremenek6217b802009-07-29 21:53:49 +00003877 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003878 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003879 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003880 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003881
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003882 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003883 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003884 }
Mike Stump1eb44332009-09-09 15:08:12 +00003885
Ted Kremenek6217b802009-07-29 21:53:49 +00003886 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003887 if (!RT)
3888 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003889
John McCall86ff3082010-02-04 22:26:26 +00003890 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003891
John McCall94c3b562010-08-18 09:41:07 +00003892 // We can't answer whether something is abstract until it has a
3893 // definition. If it's currently being defined, we'll walk back
3894 // over all the declarations when we have a full definition.
3895 const CXXRecordDecl *Def = RD->getDefinition();
3896 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003897 return false;
3898
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003899 if (!RD->isAbstract())
3900 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003901
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003902 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003903 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003904
John McCall94c3b562010-08-18 09:41:07 +00003905 return true;
3906}
3907
3908void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3909 // Check if we've already emitted the list of pure virtual functions
3910 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003911 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003912 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003913
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003914 CXXFinalOverriderMap FinalOverriders;
3915 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003916
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003917 // Keep a set of seen pure methods so we won't diagnose the same method
3918 // more than once.
3919 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3920
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003921 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3922 MEnd = FinalOverriders.end();
3923 M != MEnd;
3924 ++M) {
3925 for (OverridingMethods::iterator SO = M->second.begin(),
3926 SOEnd = M->second.end();
3927 SO != SOEnd; ++SO) {
3928 // C++ [class.abstract]p4:
3929 // A class is abstract if it contains or inherits at least one
3930 // pure virtual function for which the final overrider is pure
3931 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003932
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003933 //
3934 if (SO->second.size() != 1)
3935 continue;
3936
3937 if (!SO->second.front().Method->isPure())
3938 continue;
3939
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003940 if (!SeenPureMethods.insert(SO->second.front().Method))
3941 continue;
3942
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003943 Diag(SO->second.front().Method->getLocation(),
3944 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003945 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003946 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003947 }
3948
3949 if (!PureVirtualClassDiagSet)
3950 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3951 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003952}
3953
Anders Carlsson8211eff2009-03-24 01:19:16 +00003954namespace {
John McCall94c3b562010-08-18 09:41:07 +00003955struct AbstractUsageInfo {
3956 Sema &S;
3957 CXXRecordDecl *Record;
3958 CanQualType AbstractType;
3959 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003960
John McCall94c3b562010-08-18 09:41:07 +00003961 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3962 : S(S), Record(Record),
3963 AbstractType(S.Context.getCanonicalType(
3964 S.Context.getTypeDeclType(Record))),
3965 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003966
John McCall94c3b562010-08-18 09:41:07 +00003967 void DiagnoseAbstractType() {
3968 if (Invalid) return;
3969 S.DiagnoseAbstractType(Record);
3970 Invalid = true;
3971 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003972
John McCall94c3b562010-08-18 09:41:07 +00003973 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3974};
3975
3976struct CheckAbstractUsage {
3977 AbstractUsageInfo &Info;
3978 const NamedDecl *Ctx;
3979
3980 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3981 : Info(Info), Ctx(Ctx) {}
3982
3983 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3984 switch (TL.getTypeLocClass()) {
3985#define ABSTRACT_TYPELOC(CLASS, PARENT)
3986#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003987 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003988#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003989 }
John McCall94c3b562010-08-18 09:41:07 +00003990 }
Mike Stump1eb44332009-09-09 15:08:12 +00003991
John McCall94c3b562010-08-18 09:41:07 +00003992 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3993 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3994 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003995 if (!TL.getArg(I))
3996 continue;
3997
John McCall94c3b562010-08-18 09:41:07 +00003998 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3999 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004000 }
John McCall94c3b562010-08-18 09:41:07 +00004001 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004002
John McCall94c3b562010-08-18 09:41:07 +00004003 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4004 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4005 }
Mike Stump1eb44332009-09-09 15:08:12 +00004006
John McCall94c3b562010-08-18 09:41:07 +00004007 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4008 // Visit the type parameters from a permissive context.
4009 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4010 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4011 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4012 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4013 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4014 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004015 }
John McCall94c3b562010-08-18 09:41:07 +00004016 }
Mike Stump1eb44332009-09-09 15:08:12 +00004017
John McCall94c3b562010-08-18 09:41:07 +00004018 // Visit pointee types from a permissive context.
4019#define CheckPolymorphic(Type) \
4020 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4021 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4022 }
4023 CheckPolymorphic(PointerTypeLoc)
4024 CheckPolymorphic(ReferenceTypeLoc)
4025 CheckPolymorphic(MemberPointerTypeLoc)
4026 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004027 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004028
John McCall94c3b562010-08-18 09:41:07 +00004029 /// Handle all the types we haven't given a more specific
4030 /// implementation for above.
4031 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4032 // Every other kind of type that we haven't called out already
4033 // that has an inner type is either (1) sugar or (2) contains that
4034 // inner type in some way as a subobject.
4035 if (TypeLoc Next = TL.getNextTypeLoc())
4036 return Visit(Next, Sel);
4037
4038 // If there's no inner type and we're in a permissive context,
4039 // don't diagnose.
4040 if (Sel == Sema::AbstractNone) return;
4041
4042 // Check whether the type matches the abstract type.
4043 QualType T = TL.getType();
4044 if (T->isArrayType()) {
4045 Sel = Sema::AbstractArrayType;
4046 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004047 }
John McCall94c3b562010-08-18 09:41:07 +00004048 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4049 if (CT != Info.AbstractType) return;
4050
4051 // It matched; do some magic.
4052 if (Sel == Sema::AbstractArrayType) {
4053 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4054 << T << TL.getSourceRange();
4055 } else {
4056 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4057 << Sel << T << TL.getSourceRange();
4058 }
4059 Info.DiagnoseAbstractType();
4060 }
4061};
4062
4063void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4064 Sema::AbstractDiagSelID Sel) {
4065 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4066}
4067
4068}
4069
4070/// Check for invalid uses of an abstract type in a method declaration.
4071static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4072 CXXMethodDecl *MD) {
4073 // No need to do the check on definitions, which require that
4074 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004075 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004076 return;
4077
4078 // For safety's sake, just ignore it if we don't have type source
4079 // information. This should never happen for non-implicit methods,
4080 // but...
4081 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4082 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4083}
4084
4085/// Check for invalid uses of an abstract type within a class definition.
4086static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4087 CXXRecordDecl *RD) {
4088 for (CXXRecordDecl::decl_iterator
4089 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4090 Decl *D = *I;
4091 if (D->isImplicit()) continue;
4092
4093 // Methods and method templates.
4094 if (isa<CXXMethodDecl>(D)) {
4095 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4096 } else if (isa<FunctionTemplateDecl>(D)) {
4097 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4098 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4099
4100 // Fields and static variables.
4101 } else if (isa<FieldDecl>(D)) {
4102 FieldDecl *FD = cast<FieldDecl>(D);
4103 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4104 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4105 } else if (isa<VarDecl>(D)) {
4106 VarDecl *VD = cast<VarDecl>(D);
4107 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4108 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4109
4110 // Nested classes and class templates.
4111 } else if (isa<CXXRecordDecl>(D)) {
4112 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4113 } else if (isa<ClassTemplateDecl>(D)) {
4114 CheckAbstractClassUsage(Info,
4115 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4116 }
4117 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004118}
4119
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004120/// \brief Perform semantic checks on a class definition that has been
4121/// completing, introducing implicitly-declared members, checking for
4122/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004123void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004124 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004125 return;
4126
John McCall94c3b562010-08-18 09:41:07 +00004127 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4128 AbstractUsageInfo Info(*this, Record);
4129 CheckAbstractClassUsage(Info, Record);
4130 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004131
4132 // If this is not an aggregate type and has no user-declared constructor,
4133 // complain about any non-static data members of reference or const scalar
4134 // type, since they will never get initializers.
4135 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004136 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4137 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004138 bool Complained = false;
4139 for (RecordDecl::field_iterator F = Record->field_begin(),
4140 FEnd = Record->field_end();
4141 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004142 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004143 continue;
4144
Douglas Gregor325e5932010-04-15 00:00:53 +00004145 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004146 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004147 if (!Complained) {
4148 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4149 << Record->getTagKind() << Record;
4150 Complained = true;
4151 }
4152
4153 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4154 << F->getType()->isReferenceType()
4155 << F->getDeclName();
4156 }
4157 }
4158 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004159
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004160 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004161 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004162
4163 if (Record->getIdentifier()) {
4164 // C++ [class.mem]p13:
4165 // If T is the name of a class, then each of the following shall have a
4166 // name different from T:
4167 // - every member of every anonymous union that is a member of class T.
4168 //
4169 // C++ [class.mem]p14:
4170 // In addition, if class T has a user-declared constructor (12.1), every
4171 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004172 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4173 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4174 ++I) {
4175 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004176 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4177 isa<IndirectFieldDecl>(D)) {
4178 Diag(D->getLocation(), diag::err_member_name_of_class)
4179 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004180 break;
4181 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004182 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004183 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004184
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004185 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004186 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004187 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004188 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004189 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4190 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4191 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004192
David Blaikieb6b5b972012-09-21 03:21:07 +00004193 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4194 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4195 DiagnoseAbstractType(Record);
4196 }
4197
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004198 if (!Record->isDependentType()) {
4199 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4200 MEnd = Record->method_end();
4201 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004202 // See if a method overloads virtual methods in a base
4203 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004204 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004205 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004206
4207 // Check whether the explicitly-defaulted special members are valid.
4208 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4209 CheckExplicitlyDefaultedSpecialMember(*M);
4210
4211 // For an explicitly defaulted or deleted special member, we defer
4212 // determining triviality until the class is complete. That time is now!
4213 if (!M->isImplicit() && !M->isUserProvided()) {
4214 CXXSpecialMember CSM = getSpecialMember(*M);
4215 if (CSM != CXXInvalid) {
4216 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4217
4218 // Inform the class that we've finished declaring this member.
4219 Record->finishedDefaultedOrDeletedMember(*M);
4220 }
4221 }
4222 }
4223 }
4224
4225 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4226 // function that is not a constructor declares that member function to be
4227 // const. [...] The class of which that function is a member shall be
4228 // a literal type.
4229 //
4230 // If the class has virtual bases, any constexpr members will already have
4231 // been diagnosed by the checks performed on the member declaration, so
4232 // suppress this (less useful) diagnostic.
4233 //
4234 // We delay this until we know whether an explicitly-defaulted (or deleted)
4235 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004236 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004237 !Record->isLiteral() && !Record->getNumVBases()) {
4238 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4239 MEnd = Record->method_end();
4240 M != MEnd; ++M) {
4241 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4242 switch (Record->getTemplateSpecializationKind()) {
4243 case TSK_ImplicitInstantiation:
4244 case TSK_ExplicitInstantiationDeclaration:
4245 case TSK_ExplicitInstantiationDefinition:
4246 // If a template instantiates to a non-literal type, but its members
4247 // instantiate to constexpr functions, the template is technically
4248 // ill-formed, but we allow it for sanity.
4249 continue;
4250
4251 case TSK_Undeclared:
4252 case TSK_ExplicitSpecialization:
4253 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4254 diag::err_constexpr_method_non_literal);
4255 break;
4256 }
4257
4258 // Only produce one error per class.
4259 break;
4260 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004261 }
4262 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004263
Richard Smith07b0fdc2013-03-18 21:12:30 +00004264 // Declare inheriting constructors. We do this eagerly here because:
4265 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004266 // constructors from different classes.
4267 // - The lazy declaration of the other implicit constructors is so as to not
4268 // waste space and performance on classes that are not meant to be
4269 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004270 // have inheriting constructors.
4271 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004272}
4273
Richard Smith7756afa2012-06-10 05:43:50 +00004274/// Is the special member function which would be selected to perform the
4275/// specified operation on the specified class type a constexpr constructor?
4276static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4277 Sema::CXXSpecialMember CSM,
4278 bool ConstArg) {
4279 Sema::SpecialMemberOverloadResult *SMOR =
4280 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4281 false, false, false, false);
4282 if (!SMOR || !SMOR->getMethod())
4283 // A constructor we wouldn't select can't be "involved in initializing"
4284 // anything.
4285 return true;
4286 return SMOR->getMethod()->isConstexpr();
4287}
4288
4289/// Determine whether the specified special member function would be constexpr
4290/// if it were implicitly defined.
4291static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4292 Sema::CXXSpecialMember CSM,
4293 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004294 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004295 return false;
4296
4297 // C++11 [dcl.constexpr]p4:
4298 // In the definition of a constexpr constructor [...]
4299 switch (CSM) {
4300 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004301 // Since default constructor lookup is essentially trivial (and cannot
4302 // involve, for instance, template instantiation), we compute whether a
4303 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4304 //
4305 // This is important for performance; we need to know whether the default
4306 // constructor is constexpr to determine whether the type is a literal type.
4307 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4308
Richard Smith7756afa2012-06-10 05:43:50 +00004309 case Sema::CXXCopyConstructor:
4310 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004311 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004312 break;
4313
4314 case Sema::CXXCopyAssignment:
4315 case Sema::CXXMoveAssignment:
4316 case Sema::CXXDestructor:
4317 case Sema::CXXInvalid:
4318 return false;
4319 }
4320
4321 // -- if the class is a non-empty union, or for each non-empty anonymous
4322 // union member of a non-union class, exactly one non-static data member
4323 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004324 //
4325 // If we squint, this is guaranteed, since exactly one non-static data member
4326 // will be initialized (if the constructor isn't deleted), we just don't know
4327 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004328 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004329 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004330
4331 // -- the class shall not have any virtual base classes;
4332 if (ClassDecl->getNumVBases())
4333 return false;
4334
4335 // -- every constructor involved in initializing [...] base class
4336 // sub-objects shall be a constexpr constructor;
4337 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4338 BEnd = ClassDecl->bases_end();
4339 B != BEnd; ++B) {
4340 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4341 if (!BaseType) continue;
4342
4343 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4344 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4345 return false;
4346 }
4347
4348 // -- every constructor involved in initializing non-static data members
4349 // [...] shall be a constexpr constructor;
4350 // -- every non-static data member and base class sub-object shall be
4351 // initialized
4352 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4353 FEnd = ClassDecl->field_end();
4354 F != FEnd; ++F) {
4355 if (F->isInvalidDecl())
4356 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004357 if (const RecordType *RecordTy =
4358 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004359 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4360 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4361 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004362 }
4363 }
4364
4365 // All OK, it's constexpr!
4366 return true;
4367}
4368
Richard Smithb9d0b762012-07-27 04:22:15 +00004369static Sema::ImplicitExceptionSpecification
4370computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4371 switch (S.getSpecialMember(MD)) {
4372 case Sema::CXXDefaultConstructor:
4373 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4374 case Sema::CXXCopyConstructor:
4375 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4376 case Sema::CXXCopyAssignment:
4377 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4378 case Sema::CXXMoveConstructor:
4379 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4380 case Sema::CXXMoveAssignment:
4381 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4382 case Sema::CXXDestructor:
4383 return S.ComputeDefaultedDtorExceptionSpec(MD);
4384 case Sema::CXXInvalid:
4385 break;
4386 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004387 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4388 "only special members have implicit exception specs");
4389 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004390}
4391
Richard Smithdd25e802012-07-30 23:48:14 +00004392static void
4393updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4394 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4395 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4396 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004397 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4398 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004399}
4400
Richard Smithb9d0b762012-07-27 04:22:15 +00004401void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4402 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4403 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4404 return;
4405
Richard Smithdd25e802012-07-30 23:48:14 +00004406 // Evaluate the exception specification.
4407 ImplicitExceptionSpecification ExceptSpec =
4408 computeImplicitExceptionSpec(*this, Loc, MD);
4409
4410 // Update the type of the special member to use it.
4411 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4412
4413 // A user-provided destructor can be defined outside the class. When that
4414 // happens, be sure to update the exception specification on both
4415 // declarations.
4416 const FunctionProtoType *CanonicalFPT =
4417 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4418 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4419 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4420 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004421}
4422
Richard Smith3003e1d2012-05-15 04:39:51 +00004423void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4424 CXXRecordDecl *RD = MD->getParent();
4425 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004426
Richard Smith3003e1d2012-05-15 04:39:51 +00004427 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4428 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004429
4430 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004431 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004432 bool First = MD == MD->getCanonicalDecl();
4433
4434 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004435
4436 // C++11 [dcl.fct.def.default]p1:
4437 // A function that is explicitly defaulted shall
4438 // -- be a special member function (checked elsewhere),
4439 // -- have the same type (except for ref-qualifiers, and except that a
4440 // copy operation can take a non-const reference) as an implicit
4441 // declaration, and
4442 // -- not have default arguments.
4443 unsigned ExpectedParams = 1;
4444 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4445 ExpectedParams = 0;
4446 if (MD->getNumParams() != ExpectedParams) {
4447 // This also checks for default arguments: a copy or move constructor with a
4448 // default argument is classified as a default constructor, and assignment
4449 // operations and destructors can't have default arguments.
4450 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4451 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004452 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004453 } else if (MD->isVariadic()) {
4454 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4455 << CSM << MD->getSourceRange();
4456 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004457 }
4458
Richard Smith3003e1d2012-05-15 04:39:51 +00004459 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004460
Richard Smith7756afa2012-06-10 05:43:50 +00004461 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004462 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004463 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004464 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004465 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004466
Richard Smith3003e1d2012-05-15 04:39:51 +00004467 QualType ReturnType = Context.VoidTy;
4468 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4469 // Check for return type matching.
4470 ReturnType = Type->getResultType();
4471 QualType ExpectedReturnType =
4472 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4473 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4474 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4475 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4476 HadError = true;
4477 }
4478
4479 // A defaulted special member cannot have cv-qualifiers.
4480 if (Type->getTypeQuals()) {
4481 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4482 << (CSM == CXXMoveAssignment);
4483 HadError = true;
4484 }
4485 }
4486
4487 // Check for parameter type matching.
4488 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004489 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004490 if (ExpectedParams && ArgType->isReferenceType()) {
4491 // Argument must be reference to possibly-const T.
4492 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004493 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004494
4495 if (ReferentType.isVolatileQualified()) {
4496 Diag(MD->getLocation(),
4497 diag::err_defaulted_special_member_volatile_param) << CSM;
4498 HadError = true;
4499 }
4500
Richard Smith7756afa2012-06-10 05:43:50 +00004501 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004502 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4503 Diag(MD->getLocation(),
4504 diag::err_defaulted_special_member_copy_const_param)
4505 << (CSM == CXXCopyAssignment);
4506 // FIXME: Explain why this special member can't be const.
4507 } else {
4508 Diag(MD->getLocation(),
4509 diag::err_defaulted_special_member_move_const_param)
4510 << (CSM == CXXMoveAssignment);
4511 }
4512 HadError = true;
4513 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004514 } else if (ExpectedParams) {
4515 // A copy assignment operator can take its argument by value, but a
4516 // defaulted one cannot.
4517 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004518 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004519 HadError = true;
4520 }
Sean Huntbe631222011-05-17 20:44:43 +00004521
Richard Smith61802452011-12-22 02:22:31 +00004522 // C++11 [dcl.fct.def.default]p2:
4523 // An explicitly-defaulted function may be declared constexpr only if it
4524 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004525 // Do not apply this rule to members of class templates, since core issue 1358
4526 // makes such functions always instantiate to constexpr functions. For
4527 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004528 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4529 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004530 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4531 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4532 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004533 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004534 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004535 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004536
Richard Smith61802452011-12-22 02:22:31 +00004537 // and may have an explicit exception-specification only if it is compatible
4538 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004539 if (Type->hasExceptionSpec()) {
4540 // Delay the check if this is the first declaration of the special member,
4541 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004542 if (First) {
4543 // If the exception specification needs to be instantiated, do so now,
4544 // before we clobber it with an EST_Unevaluated specification below.
4545 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4546 InstantiateExceptionSpec(MD->getLocStart(), MD);
4547 Type = MD->getType()->getAs<FunctionProtoType>();
4548 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004549 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004550 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004551 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4552 }
Richard Smith61802452011-12-22 02:22:31 +00004553
4554 // If a function is explicitly defaulted on its first declaration,
4555 if (First) {
4556 // -- it is implicitly considered to be constexpr if the implicit
4557 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004558 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004559
Richard Smith3003e1d2012-05-15 04:39:51 +00004560 // -- it is implicitly considered to have the same exception-specification
4561 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004562 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4563 EPI.ExceptionSpecType = EST_Unevaluated;
4564 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004565 MD->setType(Context.getFunctionType(ReturnType,
4566 ArrayRef<QualType>(&ArgType,
4567 ExpectedParams),
4568 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004569 }
4570
Richard Smith3003e1d2012-05-15 04:39:51 +00004571 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004572 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004573 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004574 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004575 // C++11 [dcl.fct.def.default]p4:
4576 // [For a] user-provided explicitly-defaulted function [...] if such a
4577 // function is implicitly defined as deleted, the program is ill-formed.
4578 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4579 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004580 }
4581 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004582
Richard Smith3003e1d2012-05-15 04:39:51 +00004583 if (HadError)
4584 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004585}
4586
Richard Smith1d28caf2012-12-11 01:14:52 +00004587/// Check whether the exception specification provided for an
4588/// explicitly-defaulted special member matches the exception specification
4589/// that would have been generated for an implicit special member, per
4590/// C++11 [dcl.fct.def.default]p2.
4591void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4592 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4593 // Compute the implicit exception specification.
4594 FunctionProtoType::ExtProtoInfo EPI;
4595 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4596 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Jordan Rosebea522f2013-03-08 21:51:21 +00004597 Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004598
4599 // Ensure that it matches.
4600 CheckEquivalentExceptionSpec(
4601 PDiag(diag::err_incorrect_defaulted_exception_spec)
4602 << getSpecialMember(MD), PDiag(),
4603 ImplicitType, SourceLocation(),
4604 SpecifiedType, MD->getLocation());
4605}
4606
4607void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4608 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4609 I != N; ++I)
4610 CheckExplicitlyDefaultedMemberExceptionSpec(
4611 DelayedDefaultedMemberExceptionSpecs[I].first,
4612 DelayedDefaultedMemberExceptionSpecs[I].second);
4613
4614 DelayedDefaultedMemberExceptionSpecs.clear();
4615}
4616
Richard Smith7d5088a2012-02-18 02:02:13 +00004617namespace {
4618struct SpecialMemberDeletionInfo {
4619 Sema &S;
4620 CXXMethodDecl *MD;
4621 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004622 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004623
4624 // Properties of the special member, computed for convenience.
4625 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4626 SourceLocation Loc;
4627
4628 bool AllFieldsAreConst;
4629
4630 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004631 Sema::CXXSpecialMember CSM, bool Diagnose)
4632 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004633 IsConstructor(false), IsAssignment(false), IsMove(false),
4634 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4635 AllFieldsAreConst(true) {
4636 switch (CSM) {
4637 case Sema::CXXDefaultConstructor:
4638 case Sema::CXXCopyConstructor:
4639 IsConstructor = true;
4640 break;
4641 case Sema::CXXMoveConstructor:
4642 IsConstructor = true;
4643 IsMove = true;
4644 break;
4645 case Sema::CXXCopyAssignment:
4646 IsAssignment = true;
4647 break;
4648 case Sema::CXXMoveAssignment:
4649 IsAssignment = true;
4650 IsMove = true;
4651 break;
4652 case Sema::CXXDestructor:
4653 break;
4654 case Sema::CXXInvalid:
4655 llvm_unreachable("invalid special member kind");
4656 }
4657
4658 if (MD->getNumParams()) {
4659 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4660 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4661 }
4662 }
4663
4664 bool inUnion() const { return MD->getParent()->isUnion(); }
4665
4666 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004667 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4668 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004669 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004670 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4671 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4672 Quals = 0;
4673 return S.LookupSpecialMember(Class, CSM,
4674 ConstArg || (Quals & Qualifiers::Const),
4675 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004676 MD->getRefQualifier() == RQ_RValue,
4677 TQ & Qualifiers::Const,
4678 TQ & Qualifiers::Volatile);
4679 }
4680
Richard Smith6c4c36c2012-03-30 20:53:28 +00004681 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004682
Richard Smith6c4c36c2012-03-30 20:53:28 +00004683 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004684 bool shouldDeleteForField(FieldDecl *FD);
4685 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004686
Richard Smith517bb842012-07-18 03:51:16 +00004687 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4688 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004689 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4690 Sema::SpecialMemberOverloadResult *SMOR,
4691 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004692
4693 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004694};
4695}
4696
John McCall12d8d802012-04-09 20:53:23 +00004697/// Is the given special member inaccessible when used on the given
4698/// sub-object.
4699bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4700 CXXMethodDecl *target) {
4701 /// If we're operating on a base class, the object type is the
4702 /// type of this special member.
4703 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004704 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004705 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4706 objectTy = S.Context.getTypeDeclType(MD->getParent());
4707 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4708
4709 // If we're operating on a field, the object type is the type of the field.
4710 } else {
4711 objectTy = S.Context.getTypeDeclType(target->getParent());
4712 }
4713
4714 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4715}
4716
Richard Smith6c4c36c2012-03-30 20:53:28 +00004717/// Check whether we should delete a special member due to the implicit
4718/// definition containing a call to a special member of a subobject.
4719bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4720 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4721 bool IsDtorCallInCtor) {
4722 CXXMethodDecl *Decl = SMOR->getMethod();
4723 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4724
4725 int DiagKind = -1;
4726
4727 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4728 DiagKind = !Decl ? 0 : 1;
4729 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4730 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004731 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004732 DiagKind = 3;
4733 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4734 !Decl->isTrivial()) {
4735 // A member of a union must have a trivial corresponding special member.
4736 // As a weird special case, a destructor call from a union's constructor
4737 // must be accessible and non-deleted, but need not be trivial. Such a
4738 // destructor is never actually called, but is semantically checked as
4739 // if it were.
4740 DiagKind = 4;
4741 }
4742
4743 if (DiagKind == -1)
4744 return false;
4745
4746 if (Diagnose) {
4747 if (Field) {
4748 S.Diag(Field->getLocation(),
4749 diag::note_deleted_special_member_class_subobject)
4750 << CSM << MD->getParent() << /*IsField*/true
4751 << Field << DiagKind << IsDtorCallInCtor;
4752 } else {
4753 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4754 S.Diag(Base->getLocStart(),
4755 diag::note_deleted_special_member_class_subobject)
4756 << CSM << MD->getParent() << /*IsField*/false
4757 << Base->getType() << DiagKind << IsDtorCallInCtor;
4758 }
4759
4760 if (DiagKind == 1)
4761 S.NoteDeletedFunction(Decl);
4762 // FIXME: Explain inaccessibility if DiagKind == 3.
4763 }
4764
4765 return true;
4766}
4767
Richard Smith9a561d52012-02-26 09:11:52 +00004768/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004769/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004770bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004771 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004772 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004773
4774 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004775 // -- any direct or virtual base class, or non-static data member with no
4776 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004777 // either M has no default constructor or overload resolution as applied
4778 // to M's default constructor results in an ambiguity or in a function
4779 // that is deleted or inaccessible
4780 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4781 // -- a direct or virtual base class B that cannot be copied/moved because
4782 // overload resolution, as applied to B's corresponding special member,
4783 // results in an ambiguity or a function that is deleted or inaccessible
4784 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004785 // C++11 [class.dtor]p5:
4786 // -- any direct or virtual base class [...] has a type with a destructor
4787 // that is deleted or inaccessible
4788 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004789 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004790 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004791 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004792
Richard Smith6c4c36c2012-03-30 20:53:28 +00004793 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4794 // -- any direct or virtual base class or non-static data member has a
4795 // type with a destructor that is deleted or inaccessible
4796 if (IsConstructor) {
4797 Sema::SpecialMemberOverloadResult *SMOR =
4798 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4799 false, false, false, false, false);
4800 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4801 return true;
4802 }
4803
Richard Smith9a561d52012-02-26 09:11:52 +00004804 return false;
4805}
4806
4807/// Check whether we should delete a special member function due to the class
4808/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004809bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004810 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004811 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004812}
4813
4814/// Check whether we should delete a special member function due to the class
4815/// having a particular non-static data member.
4816bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4817 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4818 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4819
4820 if (CSM == Sema::CXXDefaultConstructor) {
4821 // For a default constructor, all references must be initialized in-class
4822 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004823 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4824 if (Diagnose)
4825 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4826 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004827 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004828 }
Richard Smith79363f52012-02-27 06:07:25 +00004829 // C++11 [class.ctor]p5: any non-variant non-static data member of
4830 // const-qualified type (or array thereof) with no
4831 // brace-or-equal-initializer does not have a user-provided default
4832 // constructor.
4833 if (!inUnion() && FieldType.isConstQualified() &&
4834 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004835 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4836 if (Diagnose)
4837 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004838 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004839 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004840 }
4841
4842 if (inUnion() && !FieldType.isConstQualified())
4843 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004844 } else if (CSM == Sema::CXXCopyConstructor) {
4845 // For a copy constructor, data members must not be of rvalue reference
4846 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004847 if (FieldType->isRValueReferenceType()) {
4848 if (Diagnose)
4849 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4850 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004851 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004852 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004853 } else if (IsAssignment) {
4854 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004855 if (FieldType->isReferenceType()) {
4856 if (Diagnose)
4857 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4858 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004859 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004860 }
4861 if (!FieldRecord && FieldType.isConstQualified()) {
4862 // C++11 [class.copy]p23:
4863 // -- a non-static data member of const non-class type (or array thereof)
4864 if (Diagnose)
4865 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004866 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004867 return true;
4868 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004869 }
4870
4871 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004872 // Some additional restrictions exist on the variant members.
4873 if (!inUnion() && FieldRecord->isUnion() &&
4874 FieldRecord->isAnonymousStructOrUnion()) {
4875 bool AllVariantFieldsAreConst = true;
4876
Richard Smithdf8dc862012-03-29 19:00:10 +00004877 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004878 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4879 UE = FieldRecord->field_end();
4880 UI != UE; ++UI) {
4881 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004882
4883 if (!UnionFieldType.isConstQualified())
4884 AllVariantFieldsAreConst = false;
4885
Richard Smith9a561d52012-02-26 09:11:52 +00004886 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4887 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004888 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4889 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004890 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004891 }
4892
4893 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004894 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004895 FieldRecord->field_begin() != FieldRecord->field_end()) {
4896 if (Diagnose)
4897 S.Diag(FieldRecord->getLocation(),
4898 diag::note_deleted_default_ctor_all_const)
4899 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004900 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004901 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004902
Richard Smithdf8dc862012-03-29 19:00:10 +00004903 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004904 // This is technically non-conformant, but sanity demands it.
4905 return false;
4906 }
4907
Richard Smith517bb842012-07-18 03:51:16 +00004908 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4909 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004910 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004911 }
4912
4913 return false;
4914}
4915
4916/// C++11 [class.ctor] p5:
4917/// A defaulted default constructor for a class X is defined as deleted if
4918/// X is a union and all of its variant members are of const-qualified type.
4919bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004920 // This is a silly definition, because it gives an empty union a deleted
4921 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004922 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4923 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4924 if (Diagnose)
4925 S.Diag(MD->getParent()->getLocation(),
4926 diag::note_deleted_default_ctor_all_const)
4927 << MD->getParent() << /*not anonymous union*/0;
4928 return true;
4929 }
4930 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004931}
4932
4933/// Determine whether a defaulted special member function should be defined as
4934/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4935/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004936bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4937 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004938 if (MD->isInvalidDecl())
4939 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004940 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004941 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004942 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004943 return false;
4944
Richard Smith7d5088a2012-02-18 02:02:13 +00004945 // C++11 [expr.lambda.prim]p19:
4946 // The closure type associated with a lambda-expression has a
4947 // deleted (8.4.3) default constructor and a deleted copy
4948 // assignment operator.
4949 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004950 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4951 if (Diagnose)
4952 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004953 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004954 }
4955
Richard Smith5bdaac52012-04-02 20:59:25 +00004956 // For an anonymous struct or union, the copy and assignment special members
4957 // will never be used, so skip the check. For an anonymous union declared at
4958 // namespace scope, the constructor and destructor are used.
4959 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4960 RD->isAnonymousStructOrUnion())
4961 return false;
4962
Richard Smith6c4c36c2012-03-30 20:53:28 +00004963 // C++11 [class.copy]p7, p18:
4964 // If the class definition declares a move constructor or move assignment
4965 // operator, an implicitly declared copy constructor or copy assignment
4966 // operator is defined as deleted.
4967 if (MD->isImplicit() &&
4968 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4969 CXXMethodDecl *UserDeclaredMove = 0;
4970
4971 // In Microsoft mode, a user-declared move only causes the deletion of the
4972 // corresponding copy operation, not both copy operations.
4973 if (RD->hasUserDeclaredMoveConstructor() &&
4974 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4975 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004976
4977 // Find any user-declared move constructor.
4978 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4979 E = RD->ctor_end(); I != E; ++I) {
4980 if (I->isMoveConstructor()) {
4981 UserDeclaredMove = *I;
4982 break;
4983 }
4984 }
Richard Smith1c931be2012-04-02 18:40:40 +00004985 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004986 } else if (RD->hasUserDeclaredMoveAssignment() &&
4987 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4988 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004989
4990 // Find any user-declared move assignment operator.
4991 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4992 E = RD->method_end(); I != E; ++I) {
4993 if (I->isMoveAssignmentOperator()) {
4994 UserDeclaredMove = *I;
4995 break;
4996 }
4997 }
Richard Smith1c931be2012-04-02 18:40:40 +00004998 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004999 }
5000
5001 if (UserDeclaredMove) {
5002 Diag(UserDeclaredMove->getLocation(),
5003 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005004 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005005 << UserDeclaredMove->isMoveAssignmentOperator();
5006 return true;
5007 }
5008 }
Sean Hunte16da072011-10-10 06:18:57 +00005009
Richard Smith5bdaac52012-04-02 20:59:25 +00005010 // Do access control from the special member function
5011 ContextRAII MethodContext(*this, MD);
5012
Richard Smith9a561d52012-02-26 09:11:52 +00005013 // C++11 [class.dtor]p5:
5014 // -- for a virtual destructor, lookup of the non-array deallocation function
5015 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005016 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005017 FunctionDecl *OperatorDelete = 0;
5018 DeclarationName Name =
5019 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5020 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005021 OperatorDelete, false)) {
5022 if (Diagnose)
5023 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005024 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005025 }
Richard Smith9a561d52012-02-26 09:11:52 +00005026 }
5027
Richard Smith6c4c36c2012-03-30 20:53:28 +00005028 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005029
Sean Huntcdee3fe2011-05-11 22:34:38 +00005030 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005031 BE = RD->bases_end(); BI != BE; ++BI)
5032 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005033 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005034 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005035
5036 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005037 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00005038 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005039 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005040
5041 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005042 FE = RD->field_end(); FI != FE; ++FI)
5043 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005044 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005045 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005046
Richard Smith7d5088a2012-02-18 02:02:13 +00005047 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005048 return true;
5049
5050 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005051}
5052
Richard Smithac713512012-12-08 02:53:02 +00005053/// Perform lookup for a special member of the specified kind, and determine
5054/// whether it is trivial. If the triviality can be determined without the
5055/// lookup, skip it. This is intended for use when determining whether a
5056/// special member of a containing object is trivial, and thus does not ever
5057/// perform overload resolution for default constructors.
5058///
5059/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5060/// member that was most likely to be intended to be trivial, if any.
5061static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5062 Sema::CXXSpecialMember CSM, unsigned Quals,
5063 CXXMethodDecl **Selected) {
5064 if (Selected)
5065 *Selected = 0;
5066
5067 switch (CSM) {
5068 case Sema::CXXInvalid:
5069 llvm_unreachable("not a special member");
5070
5071 case Sema::CXXDefaultConstructor:
5072 // C++11 [class.ctor]p5:
5073 // A default constructor is trivial if:
5074 // - all the [direct subobjects] have trivial default constructors
5075 //
5076 // Note, no overload resolution is performed in this case.
5077 if (RD->hasTrivialDefaultConstructor())
5078 return true;
5079
5080 if (Selected) {
5081 // If there's a default constructor which could have been trivial, dig it
5082 // out. Otherwise, if there's any user-provided default constructor, point
5083 // to that as an example of why there's not a trivial one.
5084 CXXConstructorDecl *DefCtor = 0;
5085 if (RD->needsImplicitDefaultConstructor())
5086 S.DeclareImplicitDefaultConstructor(RD);
5087 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5088 CE = RD->ctor_end(); CI != CE; ++CI) {
5089 if (!CI->isDefaultConstructor())
5090 continue;
5091 DefCtor = *CI;
5092 if (!DefCtor->isUserProvided())
5093 break;
5094 }
5095
5096 *Selected = DefCtor;
5097 }
5098
5099 return false;
5100
5101 case Sema::CXXDestructor:
5102 // C++11 [class.dtor]p5:
5103 // A destructor is trivial if:
5104 // - all the direct [subobjects] have trivial destructors
5105 if (RD->hasTrivialDestructor())
5106 return true;
5107
5108 if (Selected) {
5109 if (RD->needsImplicitDestructor())
5110 S.DeclareImplicitDestructor(RD);
5111 *Selected = RD->getDestructor();
5112 }
5113
5114 return false;
5115
5116 case Sema::CXXCopyConstructor:
5117 // C++11 [class.copy]p12:
5118 // A copy constructor is trivial if:
5119 // - the constructor selected to copy each direct [subobject] is trivial
5120 if (RD->hasTrivialCopyConstructor()) {
5121 if (Quals == Qualifiers::Const)
5122 // We must either select the trivial copy constructor or reach an
5123 // ambiguity; no need to actually perform overload resolution.
5124 return true;
5125 } else if (!Selected) {
5126 return false;
5127 }
5128 // In C++98, we are not supposed to perform overload resolution here, but we
5129 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5130 // cases like B as having a non-trivial copy constructor:
5131 // struct A { template<typename T> A(T&); };
5132 // struct B { mutable A a; };
5133 goto NeedOverloadResolution;
5134
5135 case Sema::CXXCopyAssignment:
5136 // C++11 [class.copy]p25:
5137 // A copy assignment operator is trivial if:
5138 // - the assignment operator selected to copy each direct [subobject] is
5139 // trivial
5140 if (RD->hasTrivialCopyAssignment()) {
5141 if (Quals == Qualifiers::Const)
5142 return true;
5143 } else if (!Selected) {
5144 return false;
5145 }
5146 // In C++98, we are not supposed to perform overload resolution here, but we
5147 // treat that as a language defect.
5148 goto NeedOverloadResolution;
5149
5150 case Sema::CXXMoveConstructor:
5151 case Sema::CXXMoveAssignment:
5152 NeedOverloadResolution:
5153 Sema::SpecialMemberOverloadResult *SMOR =
5154 S.LookupSpecialMember(RD, CSM,
5155 Quals & Qualifiers::Const,
5156 Quals & Qualifiers::Volatile,
5157 /*RValueThis*/false, /*ConstThis*/false,
5158 /*VolatileThis*/false);
5159
5160 // The standard doesn't describe how to behave if the lookup is ambiguous.
5161 // We treat it as not making the member non-trivial, just like the standard
5162 // mandates for the default constructor. This should rarely matter, because
5163 // the member will also be deleted.
5164 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5165 return true;
5166
5167 if (!SMOR->getMethod()) {
5168 assert(SMOR->getKind() ==
5169 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5170 return false;
5171 }
5172
5173 // We deliberately don't check if we found a deleted special member. We're
5174 // not supposed to!
5175 if (Selected)
5176 *Selected = SMOR->getMethod();
5177 return SMOR->getMethod()->isTrivial();
5178 }
5179
5180 llvm_unreachable("unknown special method kind");
5181}
5182
Benjamin Kramera574c892013-02-15 12:30:38 +00005183static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005184 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5185 CI != CE; ++CI)
5186 if (!CI->isImplicit())
5187 return *CI;
5188
5189 // Look for constructor templates.
5190 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5191 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5192 if (CXXConstructorDecl *CD =
5193 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5194 return CD;
5195 }
5196
5197 return 0;
5198}
5199
5200/// The kind of subobject we are checking for triviality. The values of this
5201/// enumeration are used in diagnostics.
5202enum TrivialSubobjectKind {
5203 /// The subobject is a base class.
5204 TSK_BaseClass,
5205 /// The subobject is a non-static data member.
5206 TSK_Field,
5207 /// The object is actually the complete object.
5208 TSK_CompleteObject
5209};
5210
5211/// Check whether the special member selected for a given type would be trivial.
5212static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5213 QualType SubType,
5214 Sema::CXXSpecialMember CSM,
5215 TrivialSubobjectKind Kind,
5216 bool Diagnose) {
5217 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5218 if (!SubRD)
5219 return true;
5220
5221 CXXMethodDecl *Selected;
5222 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5223 Diagnose ? &Selected : 0))
5224 return true;
5225
5226 if (Diagnose) {
5227 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5228 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5229 << Kind << SubType.getUnqualifiedType();
5230 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5231 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5232 } else if (!Selected)
5233 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5234 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5235 else if (Selected->isUserProvided()) {
5236 if (Kind == TSK_CompleteObject)
5237 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5238 << Kind << SubType.getUnqualifiedType() << CSM;
5239 else {
5240 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5241 << Kind << SubType.getUnqualifiedType() << CSM;
5242 S.Diag(Selected->getLocation(), diag::note_declared_at);
5243 }
5244 } else {
5245 if (Kind != TSK_CompleteObject)
5246 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5247 << Kind << SubType.getUnqualifiedType() << CSM;
5248
5249 // Explain why the defaulted or deleted special member isn't trivial.
5250 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5251 }
5252 }
5253
5254 return false;
5255}
5256
5257/// Check whether the members of a class type allow a special member to be
5258/// trivial.
5259static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5260 Sema::CXXSpecialMember CSM,
5261 bool ConstArg, bool Diagnose) {
5262 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5263 FE = RD->field_end(); FI != FE; ++FI) {
5264 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5265 continue;
5266
5267 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5268
5269 // Pretend anonymous struct or union members are members of this class.
5270 if (FI->isAnonymousStructOrUnion()) {
5271 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5272 CSM, ConstArg, Diagnose))
5273 return false;
5274 continue;
5275 }
5276
5277 // C++11 [class.ctor]p5:
5278 // A default constructor is trivial if [...]
5279 // -- no non-static data member of its class has a
5280 // brace-or-equal-initializer
5281 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5282 if (Diagnose)
5283 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5284 return false;
5285 }
5286
5287 // Objective C ARC 4.3.5:
5288 // [...] nontrivally ownership-qualified types are [...] not trivially
5289 // default constructible, copy constructible, move constructible, copy
5290 // assignable, move assignable, or destructible [...]
5291 if (S.getLangOpts().ObjCAutoRefCount &&
5292 FieldType.hasNonTrivialObjCLifetime()) {
5293 if (Diagnose)
5294 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5295 << RD << FieldType.getObjCLifetime();
5296 return false;
5297 }
5298
5299 if (ConstArg && !FI->isMutable())
5300 FieldType.addConst();
5301 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5302 TSK_Field, Diagnose))
5303 return false;
5304 }
5305
5306 return true;
5307}
5308
5309/// Diagnose why the specified class does not have a trivial special member of
5310/// the given kind.
5311void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5312 QualType Ty = Context.getRecordType(RD);
5313 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5314 Ty.addConst();
5315
5316 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5317 TSK_CompleteObject, /*Diagnose*/true);
5318}
5319
5320/// Determine whether a defaulted or deleted special member function is trivial,
5321/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5322/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5323bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5324 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005325 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5326
5327 CXXRecordDecl *RD = MD->getParent();
5328
5329 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005330
5331 // C++11 [class.copy]p12, p25:
5332 // A [special member] is trivial if its declared parameter type is the same
5333 // as if it had been implicitly declared [...]
5334 switch (CSM) {
5335 case CXXDefaultConstructor:
5336 case CXXDestructor:
5337 // Trivial default constructors and destructors cannot have parameters.
5338 break;
5339
5340 case CXXCopyConstructor:
5341 case CXXCopyAssignment: {
5342 // Trivial copy operations always have const, non-volatile parameter types.
5343 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005344 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005345 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5346 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5347 if (Diagnose)
5348 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5349 << Param0->getSourceRange() << Param0->getType()
5350 << Context.getLValueReferenceType(
5351 Context.getRecordType(RD).withConst());
5352 return false;
5353 }
5354 break;
5355 }
5356
5357 case CXXMoveConstructor:
5358 case CXXMoveAssignment: {
5359 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005360 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005361 const RValueReferenceType *RT =
5362 Param0->getType()->getAs<RValueReferenceType>();
5363 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5364 if (Diagnose)
5365 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5366 << Param0->getSourceRange() << Param0->getType()
5367 << Context.getRValueReferenceType(Context.getRecordType(RD));
5368 return false;
5369 }
5370 break;
5371 }
5372
5373 case CXXInvalid:
5374 llvm_unreachable("not a special member");
5375 }
5376
5377 // FIXME: We require that the parameter-declaration-clause is equivalent to
5378 // that of an implicit declaration, not just that the declared parameter type
5379 // matches, in order to prevent absuridities like a function simultaneously
5380 // being a trivial copy constructor and a non-trivial default constructor.
5381 // This issue has not yet been assigned a core issue number.
5382 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5383 if (Diagnose)
5384 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5385 diag::note_nontrivial_default_arg)
5386 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5387 return false;
5388 }
5389 if (MD->isVariadic()) {
5390 if (Diagnose)
5391 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5392 return false;
5393 }
5394
5395 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5396 // A copy/move [constructor or assignment operator] is trivial if
5397 // -- the [member] selected to copy/move each direct base class subobject
5398 // is trivial
5399 //
5400 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5401 // A [default constructor or destructor] is trivial if
5402 // -- all the direct base classes have trivial [default constructors or
5403 // destructors]
5404 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5405 BE = RD->bases_end(); BI != BE; ++BI)
5406 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5407 ConstArg ? BI->getType().withConst()
5408 : BI->getType(),
5409 CSM, TSK_BaseClass, Diagnose))
5410 return false;
5411
5412 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5413 // A copy/move [constructor or assignment operator] for a class X is
5414 // trivial if
5415 // -- for each non-static data member of X that is of class type (or array
5416 // thereof), the constructor selected to copy/move that member is
5417 // trivial
5418 //
5419 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5420 // A [default constructor or destructor] is trivial if
5421 // -- for all of the non-static data members of its class that are of class
5422 // type (or array thereof), each such class has a trivial [default
5423 // constructor or destructor]
5424 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5425 return false;
5426
5427 // C++11 [class.dtor]p5:
5428 // A destructor is trivial if [...]
5429 // -- the destructor is not virtual
5430 if (CSM == CXXDestructor && MD->isVirtual()) {
5431 if (Diagnose)
5432 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5433 return false;
5434 }
5435
5436 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5437 // A [special member] for class X is trivial if [...]
5438 // -- class X has no virtual functions and no virtual base classes
5439 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5440 if (!Diagnose)
5441 return false;
5442
5443 if (RD->getNumVBases()) {
5444 // Check for virtual bases. We already know that the corresponding
5445 // member in all bases is trivial, so vbases must all be direct.
5446 CXXBaseSpecifier &BS = *RD->vbases_begin();
5447 assert(BS.isVirtual());
5448 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5449 return false;
5450 }
5451
5452 // Must have a virtual method.
5453 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5454 ME = RD->method_end(); MI != ME; ++MI) {
5455 if (MI->isVirtual()) {
5456 SourceLocation MLoc = MI->getLocStart();
5457 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5458 return false;
5459 }
5460 }
5461
5462 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5463 }
5464
5465 // Looks like it's trivial!
5466 return true;
5467}
5468
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005469/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005470namespace {
5471 struct FindHiddenVirtualMethodData {
5472 Sema *S;
5473 CXXMethodDecl *Method;
5474 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005475 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005476 };
5477}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005478
David Blaikie5f750682012-10-19 00:53:08 +00005479/// \brief Check whether any most overriden method from MD in Methods
5480static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5481 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5482 if (MD->size_overridden_methods() == 0)
5483 return Methods.count(MD->getCanonicalDecl());
5484 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5485 E = MD->end_overridden_methods();
5486 I != E; ++I)
5487 if (CheckMostOverridenMethods(*I, Methods))
5488 return true;
5489 return false;
5490}
5491
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005492/// \brief Member lookup function that determines whether a given C++
5493/// method overloads virtual methods in a base class without overriding any,
5494/// to be used with CXXRecordDecl::lookupInBases().
5495static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5496 CXXBasePath &Path,
5497 void *UserData) {
5498 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5499
5500 FindHiddenVirtualMethodData &Data
5501 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5502
5503 DeclarationName Name = Data.Method->getDeclName();
5504 assert(Name.getNameKind() == DeclarationName::Identifier);
5505
5506 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005507 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005508 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005509 !Path.Decls.empty();
5510 Path.Decls = Path.Decls.slice(1)) {
5511 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005512 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005513 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005514 foundSameNameMethod = true;
5515 // Interested only in hidden virtual methods.
5516 if (!MD->isVirtual())
5517 continue;
5518 // If the method we are checking overrides a method from its base
5519 // don't warn about the other overloaded methods.
5520 if (!Data.S->IsOverload(Data.Method, MD, false))
5521 return true;
5522 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005523 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005524 overloadedMethods.push_back(MD);
5525 }
5526 }
5527
5528 if (foundSameNameMethod)
5529 Data.OverloadedMethods.append(overloadedMethods.begin(),
5530 overloadedMethods.end());
5531 return foundSameNameMethod;
5532}
5533
David Blaikie5f750682012-10-19 00:53:08 +00005534/// \brief Add the most overriden methods from MD to Methods
5535static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5536 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5537 if (MD->size_overridden_methods() == 0)
5538 Methods.insert(MD->getCanonicalDecl());
5539 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5540 E = MD->end_overridden_methods();
5541 I != E; ++I)
5542 AddMostOverridenMethods(*I, Methods);
5543}
5544
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005545/// \brief See if a method overloads virtual methods in a base class without
5546/// overriding any.
5547void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5548 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005549 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005550 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005551 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005552 return;
5553
5554 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5555 /*bool RecordPaths=*/false,
5556 /*bool DetectVirtual=*/false);
5557 FindHiddenVirtualMethodData Data;
5558 Data.Method = MD;
5559 Data.S = this;
5560
5561 // Keep the base methods that were overriden or introduced in the subclass
5562 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005563 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5564 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5565 NamedDecl *ND = *I;
5566 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005567 ND = shad->getTargetDecl();
5568 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5569 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005570 }
5571
5572 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5573 !Data.OverloadedMethods.empty()) {
5574 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5575 << MD << (Data.OverloadedMethods.size() > 1);
5576
5577 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5578 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005579 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005580 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005581 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5582 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005583 }
5584 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005585}
5586
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005587void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005588 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005589 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005590 SourceLocation RBrac,
5591 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005592 if (!TagDecl)
5593 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005594
Douglas Gregor42af25f2009-05-11 19:58:34 +00005595 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005596
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005597 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5598 if (l->getKind() != AttributeList::AT_Visibility)
5599 continue;
5600 l->setInvalid();
5601 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5602 l->getName();
5603 }
5604
David Blaikie77b6de02011-09-22 02:58:26 +00005605 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005606 // strict aliasing violation!
5607 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005608 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005609
Douglas Gregor23c94db2010-07-02 17:43:08 +00005610 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005611 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005612}
5613
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005614/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5615/// special functions, such as the default constructor, copy
5616/// constructor, or destructor, to the given C++ class (C++
5617/// [special]p1). This routine can only be executed just before the
5618/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005619void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005620 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005621 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005622
Richard Smithbc2a35d2012-12-08 08:32:28 +00005623 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005624 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005625
Richard Smithbc2a35d2012-12-08 08:32:28 +00005626 // If the properties or semantics of the copy constructor couldn't be
5627 // determined while the class was being declared, force a declaration
5628 // of it now.
5629 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5630 DeclareImplicitCopyConstructor(ClassDecl);
5631 }
5632
Richard Smith80ad52f2013-01-02 11:42:31 +00005633 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005634 ++ASTContext::NumImplicitMoveConstructors;
5635
Richard Smithbc2a35d2012-12-08 08:32:28 +00005636 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5637 DeclareImplicitMoveConstructor(ClassDecl);
5638 }
5639
Douglas Gregora376d102010-07-02 21:50:04 +00005640 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5641 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005642
5643 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005644 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005645 // it shows up in the right place in the vtable and that we diagnose
5646 // problems with the implicit exception specification.
5647 if (ClassDecl->isDynamicClass() ||
5648 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005649 DeclareImplicitCopyAssignment(ClassDecl);
5650 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005651
Richard Smith80ad52f2013-01-02 11:42:31 +00005652 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005653 ++ASTContext::NumImplicitMoveAssignmentOperators;
5654
5655 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005656 if (ClassDecl->isDynamicClass() ||
5657 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005658 DeclareImplicitMoveAssignment(ClassDecl);
5659 }
5660
Douglas Gregor4923aa22010-07-02 20:37:36 +00005661 if (!ClassDecl->hasUserDeclaredDestructor()) {
5662 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005663
5664 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005665 // have to declare the destructor immediately. This ensures that, e.g., it
5666 // shows up in the right place in the vtable and that we diagnose problems
5667 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005668 if (ClassDecl->isDynamicClass() ||
5669 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005670 DeclareImplicitDestructor(ClassDecl);
5671 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005672}
5673
Francois Pichet8387e2a2011-04-22 22:18:13 +00005674void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5675 if (!D)
5676 return;
5677
5678 int NumParamList = D->getNumTemplateParameterLists();
5679 for (int i = 0; i < NumParamList; i++) {
5680 TemplateParameterList* Params = D->getTemplateParameterList(i);
5681 for (TemplateParameterList::iterator Param = Params->begin(),
5682 ParamEnd = Params->end();
5683 Param != ParamEnd; ++Param) {
5684 NamedDecl *Named = cast<NamedDecl>(*Param);
5685 if (Named->getDeclName()) {
5686 S->AddDecl(Named);
5687 IdResolver.AddDecl(Named);
5688 }
5689 }
5690 }
5691}
5692
John McCalld226f652010-08-21 09:40:31 +00005693void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005694 if (!D)
5695 return;
5696
5697 TemplateParameterList *Params = 0;
5698 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5699 Params = Template->getTemplateParameters();
5700 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5701 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5702 Params = PartialSpec->getTemplateParameters();
5703 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005704 return;
5705
Douglas Gregor6569d682009-05-27 23:11:45 +00005706 for (TemplateParameterList::iterator Param = Params->begin(),
5707 ParamEnd = Params->end();
5708 Param != ParamEnd; ++Param) {
5709 NamedDecl *Named = cast<NamedDecl>(*Param);
5710 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005711 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005712 IdResolver.AddDecl(Named);
5713 }
5714 }
5715}
5716
John McCalld226f652010-08-21 09:40:31 +00005717void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005718 if (!RecordD) return;
5719 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005720 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005721 PushDeclContext(S, Record);
5722}
5723
John McCalld226f652010-08-21 09:40:31 +00005724void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005725 if (!RecordD) return;
5726 PopDeclContext();
5727}
5728
Douglas Gregor72b505b2008-12-16 21:30:33 +00005729/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5730/// parsing a top-level (non-nested) C++ class, and we are now
5731/// parsing those parts of the given Method declaration that could
5732/// not be parsed earlier (C++ [class.mem]p2), such as default
5733/// arguments. This action should enter the scope of the given
5734/// Method declaration as if we had just parsed the qualified method
5735/// name. However, it should not bring the parameters into scope;
5736/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005737void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005738}
5739
5740/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5741/// C++ method declaration. We're (re-)introducing the given
5742/// function parameter into scope for use in parsing later parts of
5743/// the method declaration. For example, we could see an
5744/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005745void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005746 if (!ParamD)
5747 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005748
John McCalld226f652010-08-21 09:40:31 +00005749 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005750
5751 // If this parameter has an unparsed default argument, clear it out
5752 // to make way for the parsed default argument.
5753 if (Param->hasUnparsedDefaultArg())
5754 Param->setDefaultArg(0);
5755
John McCalld226f652010-08-21 09:40:31 +00005756 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005757 if (Param->getDeclName())
5758 IdResolver.AddDecl(Param);
5759}
5760
5761/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5762/// processing the delayed method declaration for Method. The method
5763/// declaration is now considered finished. There may be a separate
5764/// ActOnStartOfFunctionDef action later (not necessarily
5765/// immediately!) for this method, if it was also defined inside the
5766/// class body.
John McCalld226f652010-08-21 09:40:31 +00005767void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005768 if (!MethodD)
5769 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005770
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005771 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005772
John McCalld226f652010-08-21 09:40:31 +00005773 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005774
5775 // Now that we have our default arguments, check the constructor
5776 // again. It could produce additional diagnostics or affect whether
5777 // the class has implicitly-declared destructors, among other
5778 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005779 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5780 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005781
5782 // Check the default arguments, which we may have added.
5783 if (!Method->isInvalidDecl())
5784 CheckCXXDefaultArguments(Method);
5785}
5786
Douglas Gregor42a552f2008-11-05 20:51:48 +00005787/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005788/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005789/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005790/// emit diagnostics and set the invalid bit to true. In any case, the type
5791/// will be updated to reflect a well-formed type for the constructor and
5792/// returned.
5793QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005794 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005795 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005796
5797 // C++ [class.ctor]p3:
5798 // A constructor shall not be virtual (10.3) or static (9.4). A
5799 // constructor can be invoked for a const, volatile or const
5800 // volatile object. A constructor shall not be declared const,
5801 // volatile, or const volatile (9.3.2).
5802 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005803 if (!D.isInvalidType())
5804 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5805 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5806 << SourceRange(D.getIdentifierLoc());
5807 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005808 }
John McCalld931b082010-08-26 03:08:43 +00005809 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005810 if (!D.isInvalidType())
5811 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5812 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5813 << SourceRange(D.getIdentifierLoc());
5814 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005815 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005816 }
Mike Stump1eb44332009-09-09 15:08:12 +00005817
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005818 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005819 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005820 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005821 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5822 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005823 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005824 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5825 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005826 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005827 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5828 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005829 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005830 }
Mike Stump1eb44332009-09-09 15:08:12 +00005831
Douglas Gregorc938c162011-01-26 05:01:58 +00005832 // C++0x [class.ctor]p4:
5833 // A constructor shall not be declared with a ref-qualifier.
5834 if (FTI.hasRefQualifier()) {
5835 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5836 << FTI.RefQualifierIsLValueRef
5837 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5838 D.setInvalidType();
5839 }
5840
Douglas Gregor42a552f2008-11-05 20:51:48 +00005841 // Rebuild the function type "R" without any type qualifiers (in
5842 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005843 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005844 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005845 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5846 return R;
5847
5848 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5849 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005850 EPI.RefQualifier = RQ_None;
5851
Richard Smith07b0fdc2013-03-18 21:12:30 +00005852 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005853}
5854
Douglas Gregor72b505b2008-12-16 21:30:33 +00005855/// CheckConstructor - Checks a fully-formed constructor for
5856/// well-formedness, issuing any diagnostics required. Returns true if
5857/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005858void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005859 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005860 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5861 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005862 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005863
5864 // C++ [class.copy]p3:
5865 // A declaration of a constructor for a class X is ill-formed if
5866 // its first parameter is of type (optionally cv-qualified) X and
5867 // either there are no other parameters or else all other
5868 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005869 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005870 ((Constructor->getNumParams() == 1) ||
5871 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005872 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5873 Constructor->getTemplateSpecializationKind()
5874 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005875 QualType ParamType = Constructor->getParamDecl(0)->getType();
5876 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5877 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005878 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005879 const char *ConstRef
5880 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5881 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005882 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005883 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005884
5885 // FIXME: Rather that making the constructor invalid, we should endeavor
5886 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005887 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005888 }
5889 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005890}
5891
John McCall15442822010-08-04 01:04:25 +00005892/// CheckDestructor - Checks a fully-formed destructor definition for
5893/// well-formedness, issuing any diagnostics required. Returns true
5894/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005895bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005896 CXXRecordDecl *RD = Destructor->getParent();
5897
5898 if (Destructor->isVirtual()) {
5899 SourceLocation Loc;
5900
5901 if (!Destructor->isImplicit())
5902 Loc = Destructor->getLocation();
5903 else
5904 Loc = RD->getLocation();
5905
5906 // If we have a virtual destructor, look up the deallocation function
5907 FunctionDecl *OperatorDelete = 0;
5908 DeclarationName Name =
5909 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005910 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005911 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005912
Eli Friedman5f2987c2012-02-02 03:46:19 +00005913 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005914
5915 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005916 }
Anders Carlsson37909802009-11-30 21:24:50 +00005917
5918 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005919}
5920
Mike Stump1eb44332009-09-09 15:08:12 +00005921static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005922FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5923 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5924 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005925 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005926}
5927
Douglas Gregor42a552f2008-11-05 20:51:48 +00005928/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5929/// the well-formednes of the destructor declarator @p D with type @p
5930/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005931/// emit diagnostics and set the declarator to invalid. Even if this happens,
5932/// will be updated to reflect a well-formed type for the destructor and
5933/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005934QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005935 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005936 // C++ [class.dtor]p1:
5937 // [...] A typedef-name that names a class is a class-name
5938 // (7.1.3); however, a typedef-name that names a class shall not
5939 // be used as the identifier in the declarator for a destructor
5940 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005941 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005942 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005943 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005944 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005945 else if (const TemplateSpecializationType *TST =
5946 DeclaratorType->getAs<TemplateSpecializationType>())
5947 if (TST->isTypeAlias())
5948 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5949 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005950
5951 // C++ [class.dtor]p2:
5952 // A destructor is used to destroy objects of its class type. A
5953 // destructor takes no parameters, and no return type can be
5954 // specified for it (not even void). The address of a destructor
5955 // shall not be taken. A destructor shall not be static. A
5956 // destructor can be invoked for a const, volatile or const
5957 // volatile object. A destructor shall not be declared const,
5958 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005959 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005960 if (!D.isInvalidType())
5961 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5962 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005963 << SourceRange(D.getIdentifierLoc())
5964 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5965
John McCalld931b082010-08-26 03:08:43 +00005966 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005967 }
Chris Lattner65401802009-04-25 08:28:21 +00005968 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005969 // Destructors don't have return types, but the parser will
5970 // happily parse something like:
5971 //
5972 // class X {
5973 // float ~X();
5974 // };
5975 //
5976 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005977 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5978 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5979 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005980 }
Mike Stump1eb44332009-09-09 15:08:12 +00005981
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005982 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005983 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005984 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005985 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5986 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005987 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005988 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5989 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005990 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005991 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5992 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005993 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005994 }
5995
Douglas Gregorc938c162011-01-26 05:01:58 +00005996 // C++0x [class.dtor]p2:
5997 // A destructor shall not be declared with a ref-qualifier.
5998 if (FTI.hasRefQualifier()) {
5999 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6000 << FTI.RefQualifierIsLValueRef
6001 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6002 D.setInvalidType();
6003 }
6004
Douglas Gregor42a552f2008-11-05 20:51:48 +00006005 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006006 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006007 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6008
6009 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006010 FTI.freeArgs();
6011 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006012 }
6013
Mike Stump1eb44332009-09-09 15:08:12 +00006014 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006015 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006016 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006017 D.setInvalidType();
6018 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006019
6020 // Rebuild the function type "R" without any type qualifiers or
6021 // parameters (in case any of the errors above fired) and with
6022 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006023 // types.
John McCalle23cf432010-12-14 08:05:40 +00006024 if (!D.isInvalidType())
6025 return R;
6026
Douglas Gregord92ec472010-07-01 05:10:53 +00006027 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006028 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6029 EPI.Variadic = false;
6030 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006031 EPI.RefQualifier = RQ_None;
Jordan Rosebea522f2013-03-08 21:51:21 +00006032 return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006033}
6034
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006035/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6036/// well-formednes of the conversion function declarator @p D with
6037/// type @p R. If there are any errors in the declarator, this routine
6038/// will emit diagnostics and return true. Otherwise, it will return
6039/// false. Either way, the type @p R will be updated to reflect a
6040/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006041void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006042 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006043 // C++ [class.conv.fct]p1:
6044 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006045 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006046 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006047 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006048 if (!D.isInvalidType())
6049 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6050 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6051 << SourceRange(D.getIdentifierLoc());
6052 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006053 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006054 }
John McCalla3f81372010-04-13 00:04:31 +00006055
6056 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6057
Chris Lattner6e475012009-04-25 08:35:12 +00006058 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006059 // Conversion functions don't have return types, but the parser will
6060 // happily parse something like:
6061 //
6062 // class X {
6063 // float operator bool();
6064 // };
6065 //
6066 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006067 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6068 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6069 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006070 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006071 }
6072
John McCalla3f81372010-04-13 00:04:31 +00006073 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6074
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006075 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006076 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006077 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6078
6079 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006080 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006081 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006082 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006083 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006084 D.setInvalidType();
6085 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006086
John McCalla3f81372010-04-13 00:04:31 +00006087 // Diagnose "&operator bool()" and other such nonsense. This
6088 // is actually a gcc extension which we don't support.
6089 if (Proto->getResultType() != ConvType) {
6090 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6091 << Proto->getResultType();
6092 D.setInvalidType();
6093 ConvType = Proto->getResultType();
6094 }
6095
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006096 // C++ [class.conv.fct]p4:
6097 // The conversion-type-id shall not represent a function type nor
6098 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006099 if (ConvType->isArrayType()) {
6100 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6101 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006102 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006103 } else if (ConvType->isFunctionType()) {
6104 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6105 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006106 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006107 }
6108
6109 // Rebuild the function type "R" without any parameters (in case any
6110 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006111 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006112 if (D.isInvalidType())
Jordan Rosebea522f2013-03-08 21:51:21 +00006113 R = Context.getFunctionType(ConvType, ArrayRef<QualType>(),
6114 Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006115
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006116 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006117 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006118 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006119 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006120 diag::warn_cxx98_compat_explicit_conversion_functions :
6121 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006122 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006123}
6124
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006125/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6126/// the declaration of the given C++ conversion function. This routine
6127/// is responsible for recording the conversion function in the C++
6128/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006129Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006130 assert(Conversion && "Expected to receive a conversion function declaration");
6131
Douglas Gregor9d350972008-12-12 08:25:50 +00006132 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006133
6134 // Make sure we aren't redeclaring the conversion function.
6135 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006136
6137 // C++ [class.conv.fct]p1:
6138 // [...] A conversion function is never used to convert a
6139 // (possibly cv-qualified) object to the (possibly cv-qualified)
6140 // same object type (or a reference to it), to a (possibly
6141 // cv-qualified) base class of that type (or a reference to it),
6142 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006143 // FIXME: Suppress this warning if the conversion function ends up being a
6144 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006145 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006146 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006147 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006148 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006149 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6150 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006151 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006152 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006153 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6154 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006155 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006156 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006157 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006158 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006159 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006160 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006161 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006162 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006163 }
6164
Douglas Gregore80622f2010-09-29 04:25:11 +00006165 if (FunctionTemplateDecl *ConversionTemplate
6166 = Conversion->getDescribedFunctionTemplate())
6167 return ConversionTemplate;
6168
John McCalld226f652010-08-21 09:40:31 +00006169 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006170}
6171
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006172//===----------------------------------------------------------------------===//
6173// Namespace Handling
6174//===----------------------------------------------------------------------===//
6175
Richard Smithd1a55a62012-10-04 22:13:39 +00006176/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6177/// reopened.
6178static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6179 SourceLocation Loc,
6180 IdentifierInfo *II, bool *IsInline,
6181 NamespaceDecl *PrevNS) {
6182 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006183
Richard Smithc969e6a2012-10-05 01:46:25 +00006184 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6185 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6186 // inline namespaces, with the intention of bringing names into namespace std.
6187 //
6188 // We support this just well enough to get that case working; this is not
6189 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006190 if (*IsInline && II && II->getName().startswith("__atomic") &&
6191 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006192 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006193 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6194 NS = NS->getPreviousDecl())
6195 NS->setInline(*IsInline);
6196 // Patch up the lookup table for the containing namespace. This isn't really
6197 // correct, but it's good enough for this particular case.
6198 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6199 E = PrevNS->decls_end(); I != E; ++I)
6200 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6201 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6202 return;
6203 }
6204
6205 if (PrevNS->isInline())
6206 // The user probably just forgot the 'inline', so suggest that it
6207 // be added back.
6208 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6209 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6210 else
6211 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6212 << IsInline;
6213
6214 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6215 *IsInline = PrevNS->isInline();
6216}
John McCallea318642010-08-26 09:15:37 +00006217
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006218/// ActOnStartNamespaceDef - This is called at the start of a namespace
6219/// definition.
John McCalld226f652010-08-21 09:40:31 +00006220Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006221 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006222 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006223 SourceLocation IdentLoc,
6224 IdentifierInfo *II,
6225 SourceLocation LBrace,
6226 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006227 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6228 // For anonymous namespace, take the location of the left brace.
6229 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006230 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006231 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006232 bool IsStd = false;
6233 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006234 Scope *DeclRegionScope = NamespcScope->getParent();
6235
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006236 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006237 if (II) {
6238 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006239 // The identifier in an original-namespace-definition shall not
6240 // have been previously defined in the declarative region in
6241 // which the original-namespace-definition appears. The
6242 // identifier in an original-namespace-definition is the name of
6243 // the namespace. Subsequently in that declarative region, it is
6244 // treated as an original-namespace-name.
6245 //
6246 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006247 // look through using directives, just look for any ordinary names.
6248
6249 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006250 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6251 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006252 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006253 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6254 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6255 ++I) {
6256 if ((*I)->getIdentifierNamespace() & IDNS) {
6257 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006258 break;
6259 }
6260 }
6261
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006262 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6263
6264 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006265 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006266 if (IsInline != PrevNS->isInline())
6267 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6268 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006269 } else if (PrevDecl) {
6270 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006271 Diag(Loc, diag::err_redefinition_different_kind)
6272 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006273 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006274 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006275 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006276 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006277 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006278 // This is the first "real" definition of the namespace "std", so update
6279 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006280 PrevNS = getStdNamespace();
6281 IsStd = true;
6282 AddToKnown = !IsInline;
6283 } else {
6284 // We've seen this namespace for the first time.
6285 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006286 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006287 } else {
John McCall9aeed322009-10-01 00:25:31 +00006288 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006289
6290 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006291 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006292 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006293 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006294 } else {
6295 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006296 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006297 }
6298
Richard Smithd1a55a62012-10-04 22:13:39 +00006299 if (PrevNS && IsInline != PrevNS->isInline())
6300 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6301 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006302 }
6303
6304 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6305 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006306 if (IsInvalid)
6307 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006308
6309 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006310
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006311 // FIXME: Should we be merging attributes?
6312 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006313 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006314
6315 if (IsStd)
6316 StdNamespace = Namespc;
6317 if (AddToKnown)
6318 KnownNamespaces[Namespc] = false;
6319
6320 if (II) {
6321 PushOnScopeChains(Namespc, DeclRegionScope);
6322 } else {
6323 // Link the anonymous namespace into its parent.
6324 DeclContext *Parent = CurContext->getRedeclContext();
6325 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6326 TU->setAnonymousNamespace(Namespc);
6327 } else {
6328 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006329 }
John McCall9aeed322009-10-01 00:25:31 +00006330
Douglas Gregora4181472010-03-24 00:46:35 +00006331 CurContext->addDecl(Namespc);
6332
John McCall9aeed322009-10-01 00:25:31 +00006333 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6334 // behaves as if it were replaced by
6335 // namespace unique { /* empty body */ }
6336 // using namespace unique;
6337 // namespace unique { namespace-body }
6338 // where all occurrences of 'unique' in a translation unit are
6339 // replaced by the same identifier and this identifier differs
6340 // from all other identifiers in the entire program.
6341
6342 // We just create the namespace with an empty name and then add an
6343 // implicit using declaration, just like the standard suggests.
6344 //
6345 // CodeGen enforces the "universally unique" aspect by giving all
6346 // declarations semantically contained within an anonymous
6347 // namespace internal linkage.
6348
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006349 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006350 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006351 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006352 /* 'using' */ LBrace,
6353 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006354 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006355 /* identifier */ SourceLocation(),
6356 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006357 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006358 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006359 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006360 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006361 }
6362
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006363 ActOnDocumentableDecl(Namespc);
6364
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006365 // Although we could have an invalid decl (i.e. the namespace name is a
6366 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006367 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6368 // for the namespace has the declarations that showed up in that particular
6369 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006370 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006371 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006372}
6373
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006374/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6375/// is a namespace alias, returns the namespace it points to.
6376static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6377 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6378 return AD->getNamespace();
6379 return dyn_cast_or_null<NamespaceDecl>(D);
6380}
6381
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006382/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6383/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006384void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006385 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6386 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006387 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006388 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006389 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006390 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006391}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006392
John McCall384aff82010-08-25 07:42:41 +00006393CXXRecordDecl *Sema::getStdBadAlloc() const {
6394 return cast_or_null<CXXRecordDecl>(
6395 StdBadAlloc.get(Context.getExternalSource()));
6396}
6397
6398NamespaceDecl *Sema::getStdNamespace() const {
6399 return cast_or_null<NamespaceDecl>(
6400 StdNamespace.get(Context.getExternalSource()));
6401}
6402
Douglas Gregor66992202010-06-29 17:53:46 +00006403/// \brief Retrieve the special "std" namespace, which may require us to
6404/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006405NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006406 if (!StdNamespace) {
6407 // The "std" namespace has not yet been defined, so build one implicitly.
6408 StdNamespace = NamespaceDecl::Create(Context,
6409 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006410 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006411 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006412 &PP.getIdentifierTable().get("std"),
6413 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006414 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006415 }
6416
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006417 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006418}
6419
Sebastian Redl395e04d2012-01-17 22:49:33 +00006420bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006421 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006422 "Looking for std::initializer_list outside of C++.");
6423
6424 // We're looking for implicit instantiations of
6425 // template <typename E> class std::initializer_list.
6426
6427 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6428 return false;
6429
Sebastian Redl84760e32012-01-17 22:49:58 +00006430 ClassTemplateDecl *Template = 0;
6431 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006432
Sebastian Redl84760e32012-01-17 22:49:58 +00006433 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006434
Sebastian Redl84760e32012-01-17 22:49:58 +00006435 ClassTemplateSpecializationDecl *Specialization =
6436 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6437 if (!Specialization)
6438 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006439
Sebastian Redl84760e32012-01-17 22:49:58 +00006440 Template = Specialization->getSpecializedTemplate();
6441 Arguments = Specialization->getTemplateArgs().data();
6442 } else if (const TemplateSpecializationType *TST =
6443 Ty->getAs<TemplateSpecializationType>()) {
6444 Template = dyn_cast_or_null<ClassTemplateDecl>(
6445 TST->getTemplateName().getAsTemplateDecl());
6446 Arguments = TST->getArgs();
6447 }
6448 if (!Template)
6449 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006450
6451 if (!StdInitializerList) {
6452 // Haven't recognized std::initializer_list yet, maybe this is it.
6453 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6454 if (TemplateClass->getIdentifier() !=
6455 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006456 !getStdNamespace()->InEnclosingNamespaceSetOf(
6457 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006458 return false;
6459 // This is a template called std::initializer_list, but is it the right
6460 // template?
6461 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006462 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006463 return false;
6464 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6465 return false;
6466
6467 // It's the right template.
6468 StdInitializerList = Template;
6469 }
6470
6471 if (Template != StdInitializerList)
6472 return false;
6473
6474 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006475 if (Element)
6476 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006477 return true;
6478}
6479
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006480static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6481 NamespaceDecl *Std = S.getStdNamespace();
6482 if (!Std) {
6483 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6484 return 0;
6485 }
6486
6487 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6488 Loc, Sema::LookupOrdinaryName);
6489 if (!S.LookupQualifiedName(Result, Std)) {
6490 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6491 return 0;
6492 }
6493 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6494 if (!Template) {
6495 Result.suppressDiagnostics();
6496 // We found something weird. Complain about the first thing we found.
6497 NamedDecl *Found = *Result.begin();
6498 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6499 return 0;
6500 }
6501
6502 // We found some template called std::initializer_list. Now verify that it's
6503 // correct.
6504 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006505 if (Params->getMinRequiredArguments() != 1 ||
6506 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006507 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6508 return 0;
6509 }
6510
6511 return Template;
6512}
6513
6514QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6515 if (!StdInitializerList) {
6516 StdInitializerList = LookupStdInitializerList(*this, Loc);
6517 if (!StdInitializerList)
6518 return QualType();
6519 }
6520
6521 TemplateArgumentListInfo Args(Loc, Loc);
6522 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6523 Context.getTrivialTypeSourceInfo(Element,
6524 Loc)));
6525 return Context.getCanonicalType(
6526 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6527}
6528
Sebastian Redl98d36062012-01-17 22:50:14 +00006529bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6530 // C++ [dcl.init.list]p2:
6531 // A constructor is an initializer-list constructor if its first parameter
6532 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6533 // std::initializer_list<E> for some type E, and either there are no other
6534 // parameters or else all other parameters have default arguments.
6535 if (Ctor->getNumParams() < 1 ||
6536 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6537 return false;
6538
6539 QualType ArgType = Ctor->getParamDecl(0)->getType();
6540 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6541 ArgType = RT->getPointeeType().getUnqualifiedType();
6542
6543 return isStdInitializerList(ArgType, 0);
6544}
6545
Douglas Gregor9172aa62011-03-26 22:25:30 +00006546/// \brief Determine whether a using statement is in a context where it will be
6547/// apply in all contexts.
6548static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6549 switch (CurContext->getDeclKind()) {
6550 case Decl::TranslationUnit:
6551 return true;
6552 case Decl::LinkageSpec:
6553 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6554 default:
6555 return false;
6556 }
6557}
6558
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006559namespace {
6560
6561// Callback to only accept typo corrections that are namespaces.
6562class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6563 public:
6564 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6565 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6566 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6567 }
6568 return false;
6569 }
6570};
6571
6572}
6573
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006574static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6575 CXXScopeSpec &SS,
6576 SourceLocation IdentLoc,
6577 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006578 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006579 R.clear();
6580 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006581 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006582 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006583 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6584 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006585 if (DeclContext *DC = S.computeDeclContext(SS, false))
6586 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6587 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006588 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6589 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006590 else
6591 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6592 << Ident << CorrectedQuotedStr
6593 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006594
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006595 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6596 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006597
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006598 R.addDecl(Corrected.getCorrectionDecl());
6599 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006600 }
6601 return false;
6602}
6603
John McCalld226f652010-08-21 09:40:31 +00006604Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006605 SourceLocation UsingLoc,
6606 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006607 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006608 SourceLocation IdentLoc,
6609 IdentifierInfo *NamespcName,
6610 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006611 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6612 assert(NamespcName && "Invalid NamespcName.");
6613 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006614
6615 // This can only happen along a recovery path.
6616 while (S->getFlags() & Scope::TemplateParamScope)
6617 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006618 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006619
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006620 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006621 NestedNameSpecifier *Qualifier = 0;
6622 if (SS.isSet())
6623 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6624
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006625 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006626 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6627 LookupParsedName(R, S, &SS);
6628 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006629 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006630
Douglas Gregor66992202010-06-29 17:53:46 +00006631 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006632 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006633 // Allow "using namespace std;" or "using namespace ::std;" even if
6634 // "std" hasn't been defined yet, for GCC compatibility.
6635 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6636 NamespcName->isStr("std")) {
6637 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006638 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006639 R.resolveKind();
6640 }
6641 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006642 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006643 }
6644
John McCallf36e02d2009-10-09 21:13:30 +00006645 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006646 NamedDecl *Named = R.getFoundDecl();
6647 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6648 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006649 // C++ [namespace.udir]p1:
6650 // A using-directive specifies that the names in the nominated
6651 // namespace can be used in the scope in which the
6652 // using-directive appears after the using-directive. During
6653 // unqualified name lookup (3.4.1), the names appear as if they
6654 // were declared in the nearest enclosing namespace which
6655 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006656 // namespace. [Note: in this context, "contains" means "contains
6657 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006658
6659 // Find enclosing context containing both using-directive and
6660 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006661 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006662 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6663 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6664 CommonAncestor = CommonAncestor->getParent();
6665
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006666 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006667 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006668 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006669
Douglas Gregor9172aa62011-03-26 22:25:30 +00006670 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006671 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006672 Diag(IdentLoc, diag::warn_using_directive_in_header);
6673 }
6674
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006675 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006676 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006677 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006678 }
6679
Richard Smith6b3d3e52013-02-20 19:22:51 +00006680 if (UDir)
6681 ProcessDeclAttributeList(S, UDir, AttrList);
6682
John McCalld226f652010-08-21 09:40:31 +00006683 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006684}
6685
6686void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006687 // If the scope has an associated entity and the using directive is at
6688 // namespace or translation unit scope, add the UsingDirectiveDecl into
6689 // its lookup structure so qualified name lookup can find it.
6690 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6691 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006692 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006693 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006694 // Otherwise, it is at block sope. The using-directives will affect lookup
6695 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006696 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006697}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006698
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006699
John McCalld226f652010-08-21 09:40:31 +00006700Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006701 AccessSpecifier AS,
6702 bool HasUsingKeyword,
6703 SourceLocation UsingLoc,
6704 CXXScopeSpec &SS,
6705 UnqualifiedId &Name,
6706 AttributeList *AttrList,
6707 bool IsTypeName,
6708 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006709 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006710
Douglas Gregor12c118a2009-11-04 16:30:06 +00006711 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006712 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006713 case UnqualifiedId::IK_Identifier:
6714 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006715 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006716 case UnqualifiedId::IK_ConversionFunctionId:
6717 break;
6718
6719 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006720 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006721 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006722 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006723 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006724 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006725 diag::err_using_decl_constructor)
6726 << SS.getRange();
6727
Richard Smith80ad52f2013-01-02 11:42:31 +00006728 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006729
John McCalld226f652010-08-21 09:40:31 +00006730 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006731
6732 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006733 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006734 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006735 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006736
6737 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006738 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006739 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006740 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006741 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006742
6743 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6744 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006745 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006746 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006747
Richard Smith07b0fdc2013-03-18 21:12:30 +00006748 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006749 // TODO: store that the declaration was written without 'using' and
6750 // talk about access decls instead of using decls in the
6751 // diagnostics.
6752 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006753 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006754
6755 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006756 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006757 }
6758
Douglas Gregor56c04582010-12-16 00:46:58 +00006759 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6760 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6761 return 0;
6762
John McCall9488ea12009-11-17 05:59:44 +00006763 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006764 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006765 /* IsInstantiation */ false,
6766 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006767 if (UD)
6768 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006769
John McCalld226f652010-08-21 09:40:31 +00006770 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006771}
6772
Douglas Gregor09acc982010-07-07 23:08:52 +00006773/// \brief Determine whether a using declaration considers the given
6774/// declarations as "equivalent", e.g., if they are redeclarations of
6775/// the same entity or are both typedefs of the same type.
6776static bool
6777IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6778 bool &SuppressRedeclaration) {
6779 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6780 SuppressRedeclaration = false;
6781 return true;
6782 }
6783
Richard Smith162e1c12011-04-15 14:24:37 +00006784 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6785 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006786 SuppressRedeclaration = true;
6787 return Context.hasSameType(TD1->getUnderlyingType(),
6788 TD2->getUnderlyingType());
6789 }
6790
6791 return false;
6792}
6793
6794
John McCall9f54ad42009-12-10 09:41:52 +00006795/// Determines whether to create a using shadow decl for a particular
6796/// decl, given the set of decls existing prior to this using lookup.
6797bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6798 const LookupResult &Previous) {
6799 // Diagnose finding a decl which is not from a base class of the
6800 // current class. We do this now because there are cases where this
6801 // function will silently decide not to build a shadow decl, which
6802 // will pre-empt further diagnostics.
6803 //
6804 // We don't need to do this in C++0x because we do the check once on
6805 // the qualifier.
6806 //
6807 // FIXME: diagnose the following if we care enough:
6808 // struct A { int foo; };
6809 // struct B : A { using A::foo; };
6810 // template <class T> struct C : A {};
6811 // template <class T> struct D : C<T> { using B::foo; } // <---
6812 // This is invalid (during instantiation) in C++03 because B::foo
6813 // resolves to the using decl in B, which is not a base class of D<T>.
6814 // We can't diagnose it immediately because C<T> is an unknown
6815 // specialization. The UsingShadowDecl in D<T> then points directly
6816 // to A::foo, which will look well-formed when we instantiate.
6817 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006818 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006819 DeclContext *OrigDC = Orig->getDeclContext();
6820
6821 // Handle enums and anonymous structs.
6822 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6823 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6824 while (OrigRec->isAnonymousStructOrUnion())
6825 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6826
6827 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6828 if (OrigDC == CurContext) {
6829 Diag(Using->getLocation(),
6830 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006831 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006832 Diag(Orig->getLocation(), diag::note_using_decl_target);
6833 return true;
6834 }
6835
Douglas Gregordc355712011-02-25 00:36:19 +00006836 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006837 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006838 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006839 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006840 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006841 Diag(Orig->getLocation(), diag::note_using_decl_target);
6842 return true;
6843 }
6844 }
6845
6846 if (Previous.empty()) return false;
6847
6848 NamedDecl *Target = Orig;
6849 if (isa<UsingShadowDecl>(Target))
6850 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6851
John McCalld7533ec2009-12-11 02:33:26 +00006852 // If the target happens to be one of the previous declarations, we
6853 // don't have a conflict.
6854 //
6855 // FIXME: but we might be increasing its access, in which case we
6856 // should redeclare it.
6857 NamedDecl *NonTag = 0, *Tag = 0;
6858 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6859 I != E; ++I) {
6860 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006861 bool Result;
6862 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6863 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006864
6865 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6866 }
6867
John McCall9f54ad42009-12-10 09:41:52 +00006868 if (Target->isFunctionOrFunctionTemplate()) {
6869 FunctionDecl *FD;
6870 if (isa<FunctionTemplateDecl>(Target))
6871 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6872 else
6873 FD = cast<FunctionDecl>(Target);
6874
6875 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006876 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006877 case Ovl_Overload:
6878 return false;
6879
6880 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006881 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006882 break;
6883
6884 // We found a decl with the exact signature.
6885 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006886 // If we're in a record, we want to hide the target, so we
6887 // return true (without a diagnostic) to tell the caller not to
6888 // build a shadow decl.
6889 if (CurContext->isRecord())
6890 return true;
6891
6892 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006893 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006894 break;
6895 }
6896
6897 Diag(Target->getLocation(), diag::note_using_decl_target);
6898 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6899 return true;
6900 }
6901
6902 // Target is not a function.
6903
John McCall9f54ad42009-12-10 09:41:52 +00006904 if (isa<TagDecl>(Target)) {
6905 // No conflict between a tag and a non-tag.
6906 if (!Tag) return false;
6907
John McCall41ce66f2009-12-10 19:51:03 +00006908 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006909 Diag(Target->getLocation(), diag::note_using_decl_target);
6910 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6911 return true;
6912 }
6913
6914 // No conflict between a tag and a non-tag.
6915 if (!NonTag) return false;
6916
John McCall41ce66f2009-12-10 19:51:03 +00006917 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006918 Diag(Target->getLocation(), diag::note_using_decl_target);
6919 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6920 return true;
6921}
6922
John McCall9488ea12009-11-17 05:59:44 +00006923/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006924UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006925 UsingDecl *UD,
6926 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006927
6928 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006929 NamedDecl *Target = Orig;
6930 if (isa<UsingShadowDecl>(Target)) {
6931 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6932 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006933 }
6934
6935 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006936 = UsingShadowDecl::Create(Context, CurContext,
6937 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006938 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006939
6940 Shadow->setAccess(UD->getAccess());
6941 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6942 Shadow->setInvalidDecl();
6943
John McCall9488ea12009-11-17 05:59:44 +00006944 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006945 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006946 else
John McCall604e7f12009-12-08 07:46:18 +00006947 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006948
John McCall604e7f12009-12-08 07:46:18 +00006949
John McCall9f54ad42009-12-10 09:41:52 +00006950 return Shadow;
6951}
John McCall604e7f12009-12-08 07:46:18 +00006952
John McCall9f54ad42009-12-10 09:41:52 +00006953/// Hides a using shadow declaration. This is required by the current
6954/// using-decl implementation when a resolvable using declaration in a
6955/// class is followed by a declaration which would hide or override
6956/// one or more of the using decl's targets; for example:
6957///
6958/// struct Base { void foo(int); };
6959/// struct Derived : Base {
6960/// using Base::foo;
6961/// void foo(int);
6962/// };
6963///
6964/// The governing language is C++03 [namespace.udecl]p12:
6965///
6966/// When a using-declaration brings names from a base class into a
6967/// derived class scope, member functions in the derived class
6968/// override and/or hide member functions with the same name and
6969/// parameter types in a base class (rather than conflicting).
6970///
6971/// There are two ways to implement this:
6972/// (1) optimistically create shadow decls when they're not hidden
6973/// by existing declarations, or
6974/// (2) don't create any shadow decls (or at least don't make them
6975/// visible) until we've fully parsed/instantiated the class.
6976/// The problem with (1) is that we might have to retroactively remove
6977/// a shadow decl, which requires several O(n) operations because the
6978/// decl structures are (very reasonably) not designed for removal.
6979/// (2) avoids this but is very fiddly and phase-dependent.
6980void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006981 if (Shadow->getDeclName().getNameKind() ==
6982 DeclarationName::CXXConversionFunctionName)
6983 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6984
John McCall9f54ad42009-12-10 09:41:52 +00006985 // Remove it from the DeclContext...
6986 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006987
John McCall9f54ad42009-12-10 09:41:52 +00006988 // ...and the scope, if applicable...
6989 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006990 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006991 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006992 }
6993
John McCall9f54ad42009-12-10 09:41:52 +00006994 // ...and the using decl.
6995 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6996
6997 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006998 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006999}
7000
John McCall7ba107a2009-11-18 02:36:19 +00007001/// Builds a using declaration.
7002///
7003/// \param IsInstantiation - Whether this call arises from an
7004/// instantiation of an unresolved using declaration. We treat
7005/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007006NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7007 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007008 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007009 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007010 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007011 bool IsInstantiation,
7012 bool IsTypeName,
7013 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007014 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007015 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007016 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007017
Anders Carlsson550b14b2009-08-28 05:49:21 +00007018 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007019
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007020 if (SS.isEmpty()) {
7021 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007022 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007023 }
Mike Stump1eb44332009-09-09 15:08:12 +00007024
John McCall9f54ad42009-12-10 09:41:52 +00007025 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007026 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007027 ForRedeclaration);
7028 Previous.setHideTags(false);
7029 if (S) {
7030 LookupName(Previous, S);
7031
7032 // It is really dumb that we have to do this.
7033 LookupResult::Filter F = Previous.makeFilter();
7034 while (F.hasNext()) {
7035 NamedDecl *D = F.next();
7036 if (!isDeclInScope(D, CurContext, S))
7037 F.erase();
7038 }
7039 F.done();
7040 } else {
7041 assert(IsInstantiation && "no scope in non-instantiation");
7042 assert(CurContext->isRecord() && "scope not record in instantiation");
7043 LookupQualifiedName(Previous, CurContext);
7044 }
7045
John McCall9f54ad42009-12-10 09:41:52 +00007046 // Check for invalid redeclarations.
7047 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
7048 return 0;
7049
7050 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007051 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7052 return 0;
7053
John McCallaf8e6ed2009-11-12 03:15:40 +00007054 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007055 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007056 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007057 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00007058 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00007059 // FIXME: not all declaration name kinds are legal here
7060 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7061 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007062 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007063 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007064 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007065 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7066 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007067 }
John McCalled976492009-12-04 22:46:56 +00007068 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007069 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7070 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007071 }
John McCalled976492009-12-04 22:46:56 +00007072 D->setAccess(AS);
7073 CurContext->addDecl(D);
7074
7075 if (!LookupContext) return D;
7076 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007077
John McCall77bb1aa2010-05-01 00:40:08 +00007078 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007079 UD->setInvalidDecl();
7080 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007081 }
7082
Richard Smithc5a89a12012-04-02 01:30:27 +00007083 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007084 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007085 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007086 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007087 return UD;
7088 }
7089
7090 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007091
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007092 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007093
John McCall604e7f12009-12-08 07:46:18 +00007094 // Unlike most lookups, we don't always want to hide tag
7095 // declarations: tag names are visible through the using declaration
7096 // even if hidden by ordinary names, *except* in a dependent context
7097 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007098 if (!IsInstantiation)
7099 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007100
John McCallb9abd8722012-04-07 03:04:20 +00007101 // For the purposes of this lookup, we have a base object type
7102 // equal to that of the current context.
7103 if (CurContext->isRecord()) {
7104 R.setBaseObjectType(
7105 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7106 }
7107
John McCalla24dc2e2009-11-17 02:14:36 +00007108 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007109
John McCallf36e02d2009-10-09 21:13:30 +00007110 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00007111 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007112 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007113 UD->setInvalidDecl();
7114 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007115 }
7116
John McCalled976492009-12-04 22:46:56 +00007117 if (R.isAmbiguous()) {
7118 UD->setInvalidDecl();
7119 return UD;
7120 }
Mike Stump1eb44332009-09-09 15:08:12 +00007121
John McCall7ba107a2009-11-18 02:36:19 +00007122 if (IsTypeName) {
7123 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007124 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007125 Diag(IdentLoc, diag::err_using_typename_non_type);
7126 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7127 Diag((*I)->getUnderlyingDecl()->getLocation(),
7128 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007129 UD->setInvalidDecl();
7130 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007131 }
7132 } else {
7133 // If we asked for a non-typename and we got a type, error out,
7134 // but only if this is an instantiation of an unresolved using
7135 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007136 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007137 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7138 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007139 UD->setInvalidDecl();
7140 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007141 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007142 }
7143
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007144 // C++0x N2914 [namespace.udecl]p6:
7145 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007146 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007147 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7148 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007149 UD->setInvalidDecl();
7150 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007151 }
Mike Stump1eb44332009-09-09 15:08:12 +00007152
John McCall9f54ad42009-12-10 09:41:52 +00007153 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7154 if (!CheckUsingShadowDecl(UD, *I, Previous))
7155 BuildUsingShadowDecl(S, UD, *I);
7156 }
John McCall9488ea12009-11-17 05:59:44 +00007157
7158 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007159}
7160
Sebastian Redlf677ea32011-02-05 19:23:19 +00007161/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007162bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7163 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007164
Douglas Gregordc355712011-02-25 00:36:19 +00007165 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007166 assert(SourceType &&
7167 "Using decl naming constructor doesn't have type in scope spec.");
7168 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7169
7170 // Check whether the named type is a direct base class.
7171 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7172 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7173 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7174 BaseIt != BaseE; ++BaseIt) {
7175 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7176 if (CanonicalSourceType == BaseType)
7177 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007178 if (BaseIt->getType()->isDependentType())
7179 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007180 }
7181
7182 if (BaseIt == BaseE) {
7183 // Did not find SourceType in the bases.
7184 Diag(UD->getUsingLocation(),
7185 diag::err_using_decl_constructor_not_in_direct_base)
7186 << UD->getNameInfo().getSourceRange()
7187 << QualType(SourceType, 0) << TargetClass;
7188 return true;
7189 }
7190
Richard Smithc5a89a12012-04-02 01:30:27 +00007191 if (!CurContext->isDependentContext())
7192 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007193
7194 return false;
7195}
7196
John McCall9f54ad42009-12-10 09:41:52 +00007197/// Checks that the given using declaration is not an invalid
7198/// redeclaration. Note that this is checking only for the using decl
7199/// itself, not for any ill-formedness among the UsingShadowDecls.
7200bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7201 bool isTypeName,
7202 const CXXScopeSpec &SS,
7203 SourceLocation NameLoc,
7204 const LookupResult &Prev) {
7205 // C++03 [namespace.udecl]p8:
7206 // C++0x [namespace.udecl]p10:
7207 // A using-declaration is a declaration and can therefore be used
7208 // repeatedly where (and only where) multiple declarations are
7209 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007210 //
John McCall8a726212010-11-29 18:01:58 +00007211 // That's in non-member contexts.
7212 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007213 return false;
7214
7215 NestedNameSpecifier *Qual
7216 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7217
7218 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7219 NamedDecl *D = *I;
7220
7221 bool DTypename;
7222 NestedNameSpecifier *DQual;
7223 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7224 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007225 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007226 } else if (UnresolvedUsingValueDecl *UD
7227 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7228 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007229 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007230 } else if (UnresolvedUsingTypenameDecl *UD
7231 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7232 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007233 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007234 } else continue;
7235
7236 // using decls differ if one says 'typename' and the other doesn't.
7237 // FIXME: non-dependent using decls?
7238 if (isTypeName != DTypename) continue;
7239
7240 // using decls differ if they name different scopes (but note that
7241 // template instantiation can cause this check to trigger when it
7242 // didn't before instantiation).
7243 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7244 Context.getCanonicalNestedNameSpecifier(DQual))
7245 continue;
7246
7247 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007248 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007249 return true;
7250 }
7251
7252 return false;
7253}
7254
John McCall604e7f12009-12-08 07:46:18 +00007255
John McCalled976492009-12-04 22:46:56 +00007256/// Checks that the given nested-name qualifier used in a using decl
7257/// in the current context is appropriately related to the current
7258/// scope. If an error is found, diagnoses it and returns true.
7259bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7260 const CXXScopeSpec &SS,
7261 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007262 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007263
John McCall604e7f12009-12-08 07:46:18 +00007264 if (!CurContext->isRecord()) {
7265 // C++03 [namespace.udecl]p3:
7266 // C++0x [namespace.udecl]p8:
7267 // A using-declaration for a class member shall be a member-declaration.
7268
7269 // If we weren't able to compute a valid scope, it must be a
7270 // dependent class scope.
7271 if (!NamedContext || NamedContext->isRecord()) {
7272 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7273 << SS.getRange();
7274 return true;
7275 }
7276
7277 // Otherwise, everything is known to be fine.
7278 return false;
7279 }
7280
7281 // The current scope is a record.
7282
7283 // If the named context is dependent, we can't decide much.
7284 if (!NamedContext) {
7285 // FIXME: in C++0x, we can diagnose if we can prove that the
7286 // nested-name-specifier does not refer to a base class, which is
7287 // still possible in some cases.
7288
7289 // Otherwise we have to conservatively report that things might be
7290 // okay.
7291 return false;
7292 }
7293
7294 if (!NamedContext->isRecord()) {
7295 // Ideally this would point at the last name in the specifier,
7296 // but we don't have that level of source info.
7297 Diag(SS.getRange().getBegin(),
7298 diag::err_using_decl_nested_name_specifier_is_not_class)
7299 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7300 return true;
7301 }
7302
Douglas Gregor6fb07292010-12-21 07:41:49 +00007303 if (!NamedContext->isDependentContext() &&
7304 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7305 return true;
7306
Richard Smith80ad52f2013-01-02 11:42:31 +00007307 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007308 // C++0x [namespace.udecl]p3:
7309 // In a using-declaration used as a member-declaration, the
7310 // nested-name-specifier shall name a base class of the class
7311 // being defined.
7312
7313 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7314 cast<CXXRecordDecl>(NamedContext))) {
7315 if (CurContext == NamedContext) {
7316 Diag(NameLoc,
7317 diag::err_using_decl_nested_name_specifier_is_current_class)
7318 << SS.getRange();
7319 return true;
7320 }
7321
7322 Diag(SS.getRange().getBegin(),
7323 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7324 << (NestedNameSpecifier*) SS.getScopeRep()
7325 << cast<CXXRecordDecl>(CurContext)
7326 << SS.getRange();
7327 return true;
7328 }
7329
7330 return false;
7331 }
7332
7333 // C++03 [namespace.udecl]p4:
7334 // A using-declaration used as a member-declaration shall refer
7335 // to a member of a base class of the class being defined [etc.].
7336
7337 // Salient point: SS doesn't have to name a base class as long as
7338 // lookup only finds members from base classes. Therefore we can
7339 // diagnose here only if we can prove that that can't happen,
7340 // i.e. if the class hierarchies provably don't intersect.
7341
7342 // TODO: it would be nice if "definitely valid" results were cached
7343 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7344 // need to be repeated.
7345
7346 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007347 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007348
7349 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7350 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7351 Data->Bases.insert(Base);
7352 return true;
7353 }
7354
7355 bool hasDependentBases(const CXXRecordDecl *Class) {
7356 return !Class->forallBases(collect, this);
7357 }
7358
7359 /// Returns true if the base is dependent or is one of the
7360 /// accumulated base classes.
7361 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7362 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7363 return !Data->Bases.count(Base);
7364 }
7365
7366 bool mightShareBases(const CXXRecordDecl *Class) {
7367 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7368 }
7369 };
7370
7371 UserData Data;
7372
7373 // Returns false if we find a dependent base.
7374 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7375 return false;
7376
7377 // Returns false if the class has a dependent base or if it or one
7378 // of its bases is present in the base set of the current context.
7379 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7380 return false;
7381
7382 Diag(SS.getRange().getBegin(),
7383 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7384 << (NestedNameSpecifier*) SS.getScopeRep()
7385 << cast<CXXRecordDecl>(CurContext)
7386 << SS.getRange();
7387
7388 return true;
John McCalled976492009-12-04 22:46:56 +00007389}
7390
Richard Smith162e1c12011-04-15 14:24:37 +00007391Decl *Sema::ActOnAliasDeclaration(Scope *S,
7392 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007393 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007394 SourceLocation UsingLoc,
7395 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007396 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007397 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007398 // Skip up to the relevant declaration scope.
7399 while (S->getFlags() & Scope::TemplateParamScope)
7400 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007401 assert((S->getFlags() & Scope::DeclScope) &&
7402 "got alias-declaration outside of declaration scope");
7403
7404 if (Type.isInvalid())
7405 return 0;
7406
7407 bool Invalid = false;
7408 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7409 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007410 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007411
7412 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7413 return 0;
7414
7415 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007416 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007417 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007418 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7419 TInfo->getTypeLoc().getBeginLoc());
7420 }
Richard Smith162e1c12011-04-15 14:24:37 +00007421
7422 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7423 LookupName(Previous, S);
7424
7425 // Warn about shadowing the name of a template parameter.
7426 if (Previous.isSingleResult() &&
7427 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007428 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007429 Previous.clear();
7430 }
7431
7432 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7433 "name in alias declaration must be an identifier");
7434 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7435 Name.StartLocation,
7436 Name.Identifier, TInfo);
7437
7438 NewTD->setAccess(AS);
7439
7440 if (Invalid)
7441 NewTD->setInvalidDecl();
7442
Richard Smith6b3d3e52013-02-20 19:22:51 +00007443 ProcessDeclAttributeList(S, NewTD, AttrList);
7444
Richard Smith3e4c6c42011-05-05 21:57:07 +00007445 CheckTypedefForVariablyModifiedType(S, NewTD);
7446 Invalid |= NewTD->isInvalidDecl();
7447
Richard Smith162e1c12011-04-15 14:24:37 +00007448 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007449
7450 NamedDecl *NewND;
7451 if (TemplateParamLists.size()) {
7452 TypeAliasTemplateDecl *OldDecl = 0;
7453 TemplateParameterList *OldTemplateParams = 0;
7454
7455 if (TemplateParamLists.size() != 1) {
7456 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007457 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7458 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007459 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007460 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007461
7462 // Only consider previous declarations in the same scope.
7463 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7464 /*ExplicitInstantiationOrSpecialization*/false);
7465 if (!Previous.empty()) {
7466 Redeclaration = true;
7467
7468 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7469 if (!OldDecl && !Invalid) {
7470 Diag(UsingLoc, diag::err_redefinition_different_kind)
7471 << Name.Identifier;
7472
7473 NamedDecl *OldD = Previous.getRepresentativeDecl();
7474 if (OldD->getLocation().isValid())
7475 Diag(OldD->getLocation(), diag::note_previous_definition);
7476
7477 Invalid = true;
7478 }
7479
7480 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7481 if (TemplateParameterListsAreEqual(TemplateParams,
7482 OldDecl->getTemplateParameters(),
7483 /*Complain=*/true,
7484 TPL_TemplateMatch))
7485 OldTemplateParams = OldDecl->getTemplateParameters();
7486 else
7487 Invalid = true;
7488
7489 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7490 if (!Invalid &&
7491 !Context.hasSameType(OldTD->getUnderlyingType(),
7492 NewTD->getUnderlyingType())) {
7493 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7494 // but we can't reasonably accept it.
7495 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7496 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7497 if (OldTD->getLocation().isValid())
7498 Diag(OldTD->getLocation(), diag::note_previous_definition);
7499 Invalid = true;
7500 }
7501 }
7502 }
7503
7504 // Merge any previous default template arguments into our parameters,
7505 // and check the parameter list.
7506 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7507 TPC_TypeAliasTemplate))
7508 return 0;
7509
7510 TypeAliasTemplateDecl *NewDecl =
7511 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7512 Name.Identifier, TemplateParams,
7513 NewTD);
7514
7515 NewDecl->setAccess(AS);
7516
7517 if (Invalid)
7518 NewDecl->setInvalidDecl();
7519 else if (OldDecl)
7520 NewDecl->setPreviousDeclaration(OldDecl);
7521
7522 NewND = NewDecl;
7523 } else {
7524 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7525 NewND = NewTD;
7526 }
Richard Smith162e1c12011-04-15 14:24:37 +00007527
7528 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007529 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007530
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007531 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007532 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007533}
7534
John McCalld226f652010-08-21 09:40:31 +00007535Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007536 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007537 SourceLocation AliasLoc,
7538 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007539 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007540 SourceLocation IdentLoc,
7541 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007542
Anders Carlsson81c85c42009-03-28 23:53:49 +00007543 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007544 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7545 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007546
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007547 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007548 NamedDecl *PrevDecl
7549 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7550 ForRedeclaration);
7551 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7552 PrevDecl = 0;
7553
7554 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007555 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007556 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007557 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007558 // FIXME: At some point, we'll want to create the (redundant)
7559 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007560 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007561 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007562 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007563 }
Mike Stump1eb44332009-09-09 15:08:12 +00007564
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007565 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7566 diag::err_redefinition_different_kind;
7567 Diag(AliasLoc, DiagID) << Alias;
7568 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007569 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007570 }
7571
John McCalla24dc2e2009-11-17 02:14:36 +00007572 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007573 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007574
John McCallf36e02d2009-10-09 21:13:30 +00007575 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007576 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007577 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007578 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007579 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007580 }
Mike Stump1eb44332009-09-09 15:08:12 +00007581
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007582 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007583 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007584 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007585 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007586
John McCall3dbd3d52010-02-16 06:53:13 +00007587 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007588 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007589}
7590
Sean Hunt001cad92011-05-10 00:49:42 +00007591Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007592Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7593 CXXMethodDecl *MD) {
7594 CXXRecordDecl *ClassDecl = MD->getParent();
7595
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007596 // C++ [except.spec]p14:
7597 // An implicitly declared special member function (Clause 12) shall have an
7598 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007599 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007600 if (ClassDecl->isInvalidDecl())
7601 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007602
Sebastian Redl60618fa2011-03-12 11:50:43 +00007603 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007604 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7605 BEnd = ClassDecl->bases_end();
7606 B != BEnd; ++B) {
7607 if (B->isVirtual()) // Handled below.
7608 continue;
7609
Douglas Gregor18274032010-07-03 00:47:00 +00007610 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7611 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007612 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7613 // If this is a deleted function, add it anyway. This might be conformant
7614 // with the standard. This might not. I'm not sure. It might not matter.
7615 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007616 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007617 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007618 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007619
7620 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007621 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7622 BEnd = ClassDecl->vbases_end();
7623 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007624 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7625 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007626 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7627 // If this is a deleted function, add it anyway. This might be conformant
7628 // with the standard. This might not. I'm not sure. It might not matter.
7629 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007630 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007631 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007632 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007633
7634 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007635 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7636 FEnd = ClassDecl->field_end();
7637 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007638 if (F->hasInClassInitializer()) {
7639 if (Expr *E = F->getInClassInitializer())
7640 ExceptSpec.CalledExpr(E);
7641 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007642 // DR1351:
7643 // If the brace-or-equal-initializer of a non-static data member
7644 // invokes a defaulted default constructor of its class or of an
7645 // enclosing class in a potentially evaluated subexpression, the
7646 // program is ill-formed.
7647 //
7648 // This resolution is unworkable: the exception specification of the
7649 // default constructor can be needed in an unevaluated context, in
7650 // particular, in the operand of a noexcept-expression, and we can be
7651 // unable to compute an exception specification for an enclosed class.
7652 //
7653 // We do not allow an in-class initializer to require the evaluation
7654 // of the exception specification for any in-class initializer whose
7655 // definition is not lexically complete.
7656 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007657 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007658 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007659 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7660 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7661 // If this is a deleted function, add it anyway. This might be conformant
7662 // with the standard. This might not. I'm not sure. It might not matter.
7663 // In particular, the problem is that this function never gets called. It
7664 // might just be ill-formed because this function attempts to refer to
7665 // a deleted function here.
7666 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007667 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007668 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007669 }
John McCalle23cf432010-12-14 08:05:40 +00007670
Sean Hunt001cad92011-05-10 00:49:42 +00007671 return ExceptSpec;
7672}
7673
Richard Smith07b0fdc2013-03-18 21:12:30 +00007674Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007675Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7676 CXXRecordDecl *ClassDecl = CD->getParent();
7677
7678 // C++ [except.spec]p14:
7679 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007680 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007681 if (ClassDecl->isInvalidDecl())
7682 return ExceptSpec;
7683
7684 // Inherited constructor.
7685 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7686 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7687 // FIXME: Copying or moving the parameters could add extra exceptions to the
7688 // set, as could the default arguments for the inherited constructor. This
7689 // will be addressed when we implement the resolution of core issue 1351.
7690 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7691
7692 // Direct base-class constructors.
7693 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7694 BEnd = ClassDecl->bases_end();
7695 B != BEnd; ++B) {
7696 if (B->isVirtual()) // Handled below.
7697 continue;
7698
7699 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7700 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7701 if (BaseClassDecl == InheritedDecl)
7702 continue;
7703 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7704 if (Constructor)
7705 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7706 }
7707 }
7708
7709 // Virtual base-class constructors.
7710 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7711 BEnd = ClassDecl->vbases_end();
7712 B != BEnd; ++B) {
7713 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7714 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7715 if (BaseClassDecl == InheritedDecl)
7716 continue;
7717 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7718 if (Constructor)
7719 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7720 }
7721 }
7722
7723 // Field constructors.
7724 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7725 FEnd = ClassDecl->field_end();
7726 F != FEnd; ++F) {
7727 if (F->hasInClassInitializer()) {
7728 if (Expr *E = F->getInClassInitializer())
7729 ExceptSpec.CalledExpr(E);
7730 else if (!F->isInvalidDecl())
7731 Diag(CD->getLocation(),
7732 diag::err_in_class_initializer_references_def_ctor) << CD;
7733 } else if (const RecordType *RecordTy
7734 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7735 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7736 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7737 if (Constructor)
7738 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7739 }
7740 }
7741
Richard Smith07b0fdc2013-03-18 21:12:30 +00007742 return ExceptSpec;
7743}
7744
Richard Smithafb49182012-11-29 01:34:07 +00007745namespace {
7746/// RAII object to register a special member as being currently declared.
7747struct DeclaringSpecialMember {
7748 Sema &S;
7749 Sema::SpecialMemberDecl D;
7750 bool WasAlreadyBeingDeclared;
7751
7752 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7753 : S(S), D(RD, CSM) {
7754 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7755 if (WasAlreadyBeingDeclared)
7756 // This almost never happens, but if it does, ensure that our cache
7757 // doesn't contain a stale result.
7758 S.SpecialMemberCache.clear();
7759
7760 // FIXME: Register a note to be produced if we encounter an error while
7761 // declaring the special member.
7762 }
7763 ~DeclaringSpecialMember() {
7764 if (!WasAlreadyBeingDeclared)
7765 S.SpecialMembersBeingDeclared.erase(D);
7766 }
7767
7768 /// \brief Are we already trying to declare this special member?
7769 bool isAlreadyBeingDeclared() const {
7770 return WasAlreadyBeingDeclared;
7771 }
7772};
7773}
7774
Sean Hunt001cad92011-05-10 00:49:42 +00007775CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7776 CXXRecordDecl *ClassDecl) {
7777 // C++ [class.ctor]p5:
7778 // A default constructor for a class X is a constructor of class X
7779 // that can be called without an argument. If there is no
7780 // user-declared constructor for class X, a default constructor is
7781 // implicitly declared. An implicitly-declared default constructor
7782 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007783 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007784 "Should not build implicit default constructor!");
7785
Richard Smithafb49182012-11-29 01:34:07 +00007786 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7787 if (DSM.isAlreadyBeingDeclared())
7788 return 0;
7789
Richard Smith7756afa2012-06-10 05:43:50 +00007790 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7791 CXXDefaultConstructor,
7792 false);
7793
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007794 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007795 CanQualType ClassType
7796 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007797 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007798 DeclarationName Name
7799 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007800 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007801 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007802 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007803 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007804 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007805 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007806 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007807 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007808
7809 // Build an exception specification pointing back at this constructor.
7810 FunctionProtoType::ExtProtoInfo EPI;
7811 EPI.ExceptionSpecType = EST_Unevaluated;
7812 EPI.ExceptionSpecDecl = DefaultCon;
Jordan Rosebea522f2013-03-08 21:51:21 +00007813 DefaultCon->setType(Context.getFunctionType(Context.VoidTy,
7814 ArrayRef<QualType>(),
7815 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007816
Richard Smithbc2a35d2012-12-08 08:32:28 +00007817 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7818 // constructors is easy to compute.
7819 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7820
7821 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007822 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007823
Douglas Gregor18274032010-07-03 00:47:00 +00007824 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007825 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007826
Douglas Gregor23c94db2010-07-02 17:43:08 +00007827 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007828 PushOnScopeChains(DefaultCon, S, false);
7829 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007830
Douglas Gregor32df23e2010-07-01 22:02:46 +00007831 return DefaultCon;
7832}
7833
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007834void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7835 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007836 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007837 !Constructor->doesThisDeclarationHaveABody() &&
7838 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007839 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007840
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007841 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007842 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007843
Eli Friedman9a14db32012-10-18 20:14:08 +00007844 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007845 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007846 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007847 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007848 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007849 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007850 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007851 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007852 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007853
7854 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007855 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007856
7857 Constructor->setUsed();
7858 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007859
7860 if (ASTMutationListener *L = getASTMutationListener()) {
7861 L->CompletedImplicitDefinition(Constructor);
7862 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007863}
7864
Richard Smith7a614d82011-06-11 17:19:42 +00007865void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007866 // Check that any explicitly-defaulted methods have exception specifications
7867 // compatible with their implicit exception specifications.
7868 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007869}
7870
Richard Smith4841ca52013-04-10 05:48:59 +00007871namespace {
7872/// Information on inheriting constructors to declare.
7873class InheritingConstructorInfo {
7874public:
7875 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7876 : SemaRef(SemaRef), Derived(Derived) {
7877 // Mark the constructors that we already have in the derived class.
7878 //
7879 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7880 // unless there is a user-declared constructor with the same signature in
7881 // the class where the using-declaration appears.
7882 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7883 }
7884
7885 void inheritAll(CXXRecordDecl *RD) {
7886 visitAll(RD, &InheritingConstructorInfo::inherit);
7887 }
7888
7889private:
7890 /// Information about an inheriting constructor.
7891 struct InheritingConstructor {
7892 InheritingConstructor()
7893 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7894
7895 /// If \c true, a constructor with this signature is already declared
7896 /// in the derived class.
7897 bool DeclaredInDerived;
7898
7899 /// The constructor which is inherited.
7900 const CXXConstructorDecl *BaseCtor;
7901
7902 /// The derived constructor we declared.
7903 CXXConstructorDecl *DerivedCtor;
7904 };
7905
7906 /// Inheriting constructors with a given canonical type. There can be at
7907 /// most one such non-template constructor, and any number of templated
7908 /// constructors.
7909 struct InheritingConstructorsForType {
7910 InheritingConstructor NonTemplate;
7911 llvm::SmallVector<
7912 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7913
7914 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7915 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7916 TemplateParameterList *ParamList = FTD->getTemplateParameters();
7917 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7918 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7919 false, S.TPL_TemplateMatch))
7920 return Templates[I].second;
7921 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7922 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007923 }
Richard Smith4841ca52013-04-10 05:48:59 +00007924
7925 return NonTemplate;
7926 }
7927 };
7928
7929 /// Get or create the inheriting constructor record for a constructor.
7930 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7931 QualType CtorType) {
7932 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7933 .getEntry(SemaRef, Ctor);
7934 }
7935
7936 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7937
7938 /// Process all constructors for a class.
7939 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7940 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7941 CtorE = RD->ctor_end();
7942 CtorIt != CtorE; ++CtorIt)
7943 (this->*Callback)(*CtorIt);
7944 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7945 I(RD->decls_begin()), E(RD->decls_end());
7946 I != E; ++I) {
7947 const FunctionDecl *FD = (*I)->getTemplatedDecl();
7948 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7949 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007950 }
7951 }
Richard Smith4841ca52013-04-10 05:48:59 +00007952
7953 /// Note that a constructor (or constructor template) was declared in Derived.
7954 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7955 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7956 }
7957
7958 /// Inherit a single constructor.
7959 void inherit(const CXXConstructorDecl *Ctor) {
7960 const FunctionProtoType *CtorType =
7961 Ctor->getType()->castAs<FunctionProtoType>();
7962 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7963 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7964
7965 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7966
7967 // Core issue (no number yet): the ellipsis is always discarded.
7968 if (EPI.Variadic) {
7969 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7970 SemaRef.Diag(Ctor->getLocation(),
7971 diag::note_using_decl_constructor_ellipsis);
7972 EPI.Variadic = false;
7973 }
7974
7975 // Declare a constructor for each number of parameters.
7976 //
7977 // C++11 [class.inhctor]p1:
7978 // The candidate set of inherited constructors from the class X named in
7979 // the using-declaration consists of [... modulo defects ...] for each
7980 // constructor or constructor template of X, the set of constructors or
7981 // constructor templates that results from omitting any ellipsis parameter
7982 // specification and successively omitting parameters with a default
7983 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00007984 unsigned MinParams = minParamsToInherit(Ctor);
7985 unsigned Params = Ctor->getNumParams();
7986 if (Params >= MinParams) {
7987 do
7988 declareCtor(UsingLoc, Ctor,
7989 SemaRef.Context.getFunctionType(
7990 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7991 while (Params > MinParams &&
7992 Ctor->getParamDecl(--Params)->hasDefaultArg());
7993 }
Richard Smith4841ca52013-04-10 05:48:59 +00007994 }
7995
7996 /// Find the using-declaration which specified that we should inherit the
7997 /// constructors of \p Base.
7998 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
7999 // No fancy lookup required; just look for the base constructor name
8000 // directly within the derived class.
8001 ASTContext &Context = SemaRef.Context;
8002 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8003 Context.getCanonicalType(Context.getRecordType(Base)));
8004 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8005 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8006 }
8007
8008 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8009 // C++11 [class.inhctor]p3:
8010 // [F]or each constructor template in the candidate set of inherited
8011 // constructors, a constructor template is implicitly declared
8012 if (Ctor->getDescribedFunctionTemplate())
8013 return 0;
8014
8015 // For each non-template constructor in the candidate set of inherited
8016 // constructors other than a constructor having no parameters or a
8017 // copy/move constructor having a single parameter, a constructor is
8018 // implicitly declared [...]
8019 if (Ctor->getNumParams() == 0)
8020 return 1;
8021 if (Ctor->isCopyOrMoveConstructor())
8022 return 2;
8023
8024 // Per discussion on core reflector, never inherit a constructor which
8025 // would become a default, copy, or move constructor of Derived either.
8026 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8027 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8028 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8029 }
8030
8031 /// Declare a single inheriting constructor, inheriting the specified
8032 /// constructor, with the given type.
8033 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8034 QualType DerivedType) {
8035 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8036
8037 // C++11 [class.inhctor]p3:
8038 // ... a constructor is implicitly declared with the same constructor
8039 // characteristics unless there is a user-declared constructor with
8040 // the same signature in the class where the using-declaration appears
8041 if (Entry.DeclaredInDerived)
8042 return;
8043
8044 // C++11 [class.inhctor]p7:
8045 // If two using-declarations declare inheriting constructors with the
8046 // same signature, the program is ill-formed
8047 if (Entry.DerivedCtor) {
8048 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8049 // Only diagnose this once per constructor.
8050 if (Entry.DerivedCtor->isInvalidDecl())
8051 return;
8052 Entry.DerivedCtor->setInvalidDecl();
8053
8054 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8055 SemaRef.Diag(BaseCtor->getLocation(),
8056 diag::note_using_decl_constructor_conflict_current_ctor);
8057 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8058 diag::note_using_decl_constructor_conflict_previous_ctor);
8059 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8060 diag::note_using_decl_constructor_conflict_previous_using);
8061 } else {
8062 // Core issue (no number): if the same inheriting constructor is
8063 // produced by multiple base class constructors from the same base
8064 // class, the inheriting constructor is defined as deleted.
8065 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8066 }
8067
8068 return;
8069 }
8070
8071 ASTContext &Context = SemaRef.Context;
8072 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8073 Context.getCanonicalType(Context.getRecordType(Derived)));
8074 DeclarationNameInfo NameInfo(Name, UsingLoc);
8075
8076 TemplateParameterList *TemplateParams = 0;
8077 if (const FunctionTemplateDecl *FTD =
8078 BaseCtor->getDescribedFunctionTemplate()) {
8079 TemplateParams = FTD->getTemplateParameters();
8080 // We're reusing template parameters from a different DeclContext. This
8081 // is questionable at best, but works out because the template depth in
8082 // both places is guaranteed to be 0.
8083 // FIXME: Rebuild the template parameters in the new context, and
8084 // transform the function type to refer to them.
8085 }
8086
8087 // Build type source info pointing at the using-declaration. This is
8088 // required by template instantiation.
8089 TypeSourceInfo *TInfo =
8090 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8091 FunctionProtoTypeLoc ProtoLoc =
8092 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8093
8094 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8095 Context, Derived, UsingLoc, NameInfo, DerivedType,
8096 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8097 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8098
8099 // Build an unevaluated exception specification for this constructor.
8100 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8101 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8102 EPI.ExceptionSpecType = EST_Unevaluated;
8103 EPI.ExceptionSpecDecl = DerivedCtor;
8104 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8105 FPT->getArgTypes(), EPI));
8106
8107 // Build the parameter declarations.
8108 SmallVector<ParmVarDecl *, 16> ParamDecls;
8109 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8110 TypeSourceInfo *TInfo =
8111 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8112 ParmVarDecl *PD = ParmVarDecl::Create(
8113 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8114 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8115 PD->setScopeInfo(0, I);
8116 PD->setImplicit();
8117 ParamDecls.push_back(PD);
8118 ProtoLoc.setArg(I, PD);
8119 }
8120
8121 // Set up the new constructor.
8122 DerivedCtor->setAccess(BaseCtor->getAccess());
8123 DerivedCtor->setParams(ParamDecls);
8124 DerivedCtor->setInheritedConstructor(BaseCtor);
8125 if (BaseCtor->isDeleted())
8126 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8127
8128 // If this is a constructor template, build the template declaration.
8129 if (TemplateParams) {
8130 FunctionTemplateDecl *DerivedTemplate =
8131 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8132 TemplateParams, DerivedCtor);
8133 DerivedTemplate->setAccess(BaseCtor->getAccess());
8134 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8135 Derived->addDecl(DerivedTemplate);
8136 } else {
8137 Derived->addDecl(DerivedCtor);
8138 }
8139
8140 Entry.BaseCtor = BaseCtor;
8141 Entry.DerivedCtor = DerivedCtor;
8142 }
8143
8144 Sema &SemaRef;
8145 CXXRecordDecl *Derived;
8146 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8147 MapType Map;
8148};
8149}
8150
8151void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8152 // Defer declaring the inheriting constructors until the class is
8153 // instantiated.
8154 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008155 return;
8156
Richard Smith4841ca52013-04-10 05:48:59 +00008157 // Find base classes from which we might inherit constructors.
8158 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8159 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8160 BaseE = ClassDecl->bases_end();
8161 BaseIt != BaseE; ++BaseIt)
8162 if (BaseIt->getInheritConstructors())
8163 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008164
Richard Smith4841ca52013-04-10 05:48:59 +00008165 // Go no further if we're not inheriting any constructors.
8166 if (InheritedBases.empty())
8167 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008168
Richard Smith4841ca52013-04-10 05:48:59 +00008169 // Declare the inherited constructors.
8170 InheritingConstructorInfo ICI(*this, ClassDecl);
8171 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8172 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008173}
8174
Richard Smith07b0fdc2013-03-18 21:12:30 +00008175void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8176 CXXConstructorDecl *Constructor) {
8177 CXXRecordDecl *ClassDecl = Constructor->getParent();
8178 assert(Constructor->getInheritedConstructor() &&
8179 !Constructor->doesThisDeclarationHaveABody() &&
8180 !Constructor->isDeleted());
8181
8182 SynthesizedFunctionScope Scope(*this, Constructor);
8183 DiagnosticErrorTrap Trap(Diags);
8184 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8185 Trap.hasErrorOccurred()) {
8186 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8187 << Context.getTagDeclType(ClassDecl);
8188 Constructor->setInvalidDecl();
8189 return;
8190 }
8191
8192 SourceLocation Loc = Constructor->getLocation();
8193 Constructor->setBody(new (Context) CompoundStmt(Loc));
8194
8195 Constructor->setUsed();
8196 MarkVTableUsed(CurrentLocation, ClassDecl);
8197
8198 if (ASTMutationListener *L = getASTMutationListener()) {
8199 L->CompletedImplicitDefinition(Constructor);
8200 }
8201}
8202
8203
Sean Huntcb45a0f2011-05-12 22:46:25 +00008204Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008205Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8206 CXXRecordDecl *ClassDecl = MD->getParent();
8207
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008208 // C++ [except.spec]p14:
8209 // An implicitly declared special member function (Clause 12) shall have
8210 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008211 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008212 if (ClassDecl->isInvalidDecl())
8213 return ExceptSpec;
8214
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008215 // Direct base-class destructors.
8216 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8217 BEnd = ClassDecl->bases_end();
8218 B != BEnd; ++B) {
8219 if (B->isVirtual()) // Handled below.
8220 continue;
8221
8222 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008223 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008224 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008225 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008226
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008227 // Virtual base-class destructors.
8228 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8229 BEnd = ClassDecl->vbases_end();
8230 B != BEnd; ++B) {
8231 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008232 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008233 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008234 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008235
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008236 // Field destructors.
8237 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8238 FEnd = ClassDecl->field_end();
8239 F != FEnd; ++F) {
8240 if (const RecordType *RecordTy
8241 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008242 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008243 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008244 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008245
Sean Huntcb45a0f2011-05-12 22:46:25 +00008246 return ExceptSpec;
8247}
8248
8249CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8250 // C++ [class.dtor]p2:
8251 // If a class has no user-declared destructor, a destructor is
8252 // declared implicitly. An implicitly-declared destructor is an
8253 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008254 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008255
Richard Smithafb49182012-11-29 01:34:07 +00008256 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8257 if (DSM.isAlreadyBeingDeclared())
8258 return 0;
8259
Douglas Gregor4923aa22010-07-02 20:37:36 +00008260 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008261 CanQualType ClassType
8262 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008263 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008264 DeclarationName Name
8265 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008266 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008267 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008268 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8269 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008270 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008271 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008272 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008273 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008274
8275 // Build an exception specification pointing back at this destructor.
8276 FunctionProtoType::ExtProtoInfo EPI;
8277 EPI.ExceptionSpecType = EST_Unevaluated;
8278 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00008279 Destructor->setType(Context.getFunctionType(Context.VoidTy,
8280 ArrayRef<QualType>(),
8281 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008282
Richard Smithbc2a35d2012-12-08 08:32:28 +00008283 AddOverriddenMethods(ClassDecl, Destructor);
8284
8285 // We don't need to use SpecialMemberIsTrivial here; triviality for
8286 // destructors is easy to compute.
8287 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8288
8289 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008290 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008291
Douglas Gregor4923aa22010-07-02 20:37:36 +00008292 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008293 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008294
Douglas Gregor4923aa22010-07-02 20:37:36 +00008295 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008296 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008297 PushOnScopeChains(Destructor, S, false);
8298 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008299
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008300 return Destructor;
8301}
8302
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008303void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008304 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008305 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008306 !Destructor->doesThisDeclarationHaveABody() &&
8307 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008308 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008309 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008310 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008311
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008312 if (Destructor->isInvalidDecl())
8313 return;
8314
Eli Friedman9a14db32012-10-18 20:14:08 +00008315 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008316
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008317 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008318 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8319 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008320
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008321 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008322 Diag(CurrentLocation, diag::note_member_synthesized_at)
8323 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8324
8325 Destructor->setInvalidDecl();
8326 return;
8327 }
8328
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008329 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008330 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008331 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008332 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008333 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008334
8335 if (ASTMutationListener *L = getASTMutationListener()) {
8336 L->CompletedImplicitDefinition(Destructor);
8337 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008338}
8339
Richard Smitha4156b82012-04-21 18:42:51 +00008340/// \brief Perform any semantic analysis which needs to be delayed until all
8341/// pending class member declarations have been parsed.
8342void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008343 // If the context is an invalid C++ class, just suppress these checks.
8344 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8345 if (Record->isInvalidDecl()) {
8346 DelayedDestructorExceptionSpecChecks.clear();
8347 return;
8348 }
8349 }
8350
Richard Smitha4156b82012-04-21 18:42:51 +00008351 // Perform any deferred checking of exception specifications for virtual
8352 // destructors.
8353 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8354 i != e; ++i) {
8355 const CXXDestructorDecl *Dtor =
8356 DelayedDestructorExceptionSpecChecks[i].first;
8357 assert(!Dtor->getParent()->isDependentType() &&
8358 "Should not ever add destructors of templates into the list.");
8359 CheckOverridingFunctionExceptionSpec(Dtor,
8360 DelayedDestructorExceptionSpecChecks[i].second);
8361 }
8362 DelayedDestructorExceptionSpecChecks.clear();
8363}
8364
Richard Smithb9d0b762012-07-27 04:22:15 +00008365void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8366 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008367 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008368 "adjusting dtor exception specs was introduced in c++11");
8369
Sebastian Redl0ee33912011-05-19 05:13:44 +00008370 // C++11 [class.dtor]p3:
8371 // A declaration of a destructor that does not have an exception-
8372 // specification is implicitly considered to have the same exception-
8373 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008374 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008375 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008376 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008377 return;
8378
Chandler Carruth3f224b22011-09-20 04:55:26 +00008379 // Replace the destructor's type, building off the existing one. Fortunately,
8380 // the only thing of interest in the destructor type is its extended info.
8381 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008382 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8383 EPI.ExceptionSpecType = EST_Unevaluated;
8384 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00008385 Destructor->setType(Context.getFunctionType(Context.VoidTy,
8386 ArrayRef<QualType>(),
8387 EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008388
Sebastian Redl0ee33912011-05-19 05:13:44 +00008389 // FIXME: If the destructor has a body that could throw, and the newly created
8390 // spec doesn't allow exceptions, we should emit a warning, because this
8391 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008392 // However, we don't have a body or an exception specification yet, so it
8393 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008394}
8395
Richard Smith8c889532012-11-14 00:50:40 +00008396/// When generating a defaulted copy or move assignment operator, if a field
8397/// should be copied with __builtin_memcpy rather than via explicit assignments,
8398/// do so. This optimization only applies for arrays of scalars, and for arrays
8399/// of class type where the selected copy/move-assignment operator is trivial.
8400static StmtResult
8401buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8402 Expr *To, Expr *From) {
8403 // Compute the size of the memory buffer to be copied.
8404 QualType SizeType = S.Context.getSizeType();
8405 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8406 S.Context.getTypeSizeInChars(T).getQuantity());
8407
8408 // Take the address of the field references for "from" and "to". We
8409 // directly construct UnaryOperators here because semantic analysis
8410 // does not permit us to take the address of an xvalue.
8411 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8412 S.Context.getPointerType(From->getType()),
8413 VK_RValue, OK_Ordinary, Loc);
8414 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8415 S.Context.getPointerType(To->getType()),
8416 VK_RValue, OK_Ordinary, Loc);
8417
8418 const Type *E = T->getBaseElementTypeUnsafe();
8419 bool NeedsCollectableMemCpy =
8420 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8421
8422 // Create a reference to the __builtin_objc_memmove_collectable function
8423 StringRef MemCpyName = NeedsCollectableMemCpy ?
8424 "__builtin_objc_memmove_collectable" :
8425 "__builtin_memcpy";
8426 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8427 Sema::LookupOrdinaryName);
8428 S.LookupName(R, S.TUScope, true);
8429
8430 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8431 if (!MemCpy)
8432 // Something went horribly wrong earlier, and we will have complained
8433 // about it.
8434 return StmtError();
8435
8436 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8437 VK_RValue, Loc, 0);
8438 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8439
8440 Expr *CallArgs[] = {
8441 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8442 };
8443 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8444 Loc, CallArgs, Loc);
8445
8446 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8447 return S.Owned(Call.takeAs<Stmt>());
8448}
8449
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008450/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008451/// \c To.
8452///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008453/// This routine is used to copy/move the members of a class with an
8454/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008455/// copied are arrays, this routine builds for loops to copy them.
8456///
8457/// \param S The Sema object used for type-checking.
8458///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008459/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008460///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008461/// \param T The type of the expressions being copied/moved. Both expressions
8462/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008463///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008464/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008465///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008466/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008467///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008468/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008469/// Otherwise, it's a non-static member subobject.
8470///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008471/// \param Copying Whether we're copying or moving.
8472///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008473/// \param Depth Internal parameter recording the depth of the recursion.
8474///
Richard Smith8c889532012-11-14 00:50:40 +00008475/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8476/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008477static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008478buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8479 Expr *To, Expr *From,
8480 bool CopyingBaseSubobject, bool Copying,
8481 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008482 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008483 // Each subobject is assigned in the manner appropriate to its type:
8484 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008485 // - if the subobject is of class type, as if by a call to operator= with
8486 // the subobject as the object expression and the corresponding
8487 // subobject of x as a single function argument (as if by explicit
8488 // qualification; that is, ignoring any possible virtual overriding
8489 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008490 //
8491 // C++03 [class.copy]p13:
8492 // - if the subobject is of class type, the copy assignment operator for
8493 // the class is used (as if by explicit qualification; that is,
8494 // ignoring any possible virtual overriding functions in more derived
8495 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008496 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8497 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008498
Douglas Gregor06a9f362010-05-01 20:49:11 +00008499 // Look for operator=.
8500 DeclarationName Name
8501 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8502 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8503 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008504
Richard Smith044c8aa2012-11-13 00:54:12 +00008505 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8506 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008507 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008508 LookupResult::Filter F = OpLookup.makeFilter();
8509 while (F.hasNext()) {
8510 NamedDecl *D = F.next();
8511 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8512 if (Method->isCopyAssignmentOperator() ||
8513 (!Copying && Method->isMoveAssignmentOperator()))
8514 continue;
8515
8516 F.erase();
8517 }
8518 F.done();
John McCallb0207482010-03-16 06:11:48 +00008519 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008520
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008521 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008522 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008523 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008524 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008525 // ambiguities), we need to cast "this" to that subobject type; to
8526 // ensure that we don't go through the virtual call mechanism, we need
8527 // to qualify the operator= name with the base class (see below). However,
8528 // this means that if the base class has a protected copy assignment
8529 // operator, the protected member access check will fail. So, we
8530 // rewrite "protected" access to "public" access in this case, since we
8531 // know by construction that we're calling from a derived class.
8532 if (CopyingBaseSubobject) {
8533 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8534 L != LEnd; ++L) {
8535 if (L.getAccess() == AS_protected)
8536 L.setAccess(AS_public);
8537 }
8538 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008539
Douglas Gregor06a9f362010-05-01 20:49:11 +00008540 // Create the nested-name-specifier that will be used to qualify the
8541 // reference to operator=; this is required to suppress the virtual
8542 // call mechanism.
8543 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008544 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008545 SS.MakeTrivial(S.Context,
8546 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008547 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008548 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008549
Douglas Gregor06a9f362010-05-01 20:49:11 +00008550 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008551 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008552 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008553 /*TemplateKWLoc=*/SourceLocation(),
8554 /*FirstQualifierInScope=*/0,
8555 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008556 /*TemplateArgs=*/0,
8557 /*SuppressQualifierCheck=*/true);
8558 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008559 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008560
Douglas Gregor06a9f362010-05-01 20:49:11 +00008561 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008562
Richard Smith044c8aa2012-11-13 00:54:12 +00008563 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008564 OpEqualRef.takeAs<Expr>(),
8565 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008566 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008567 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008568
Richard Smith8c889532012-11-14 00:50:40 +00008569 // If we built a call to a trivial 'operator=' while copying an array,
8570 // bail out. We'll replace the whole shebang with a memcpy.
8571 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8572 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8573 return StmtResult((Stmt*)0);
8574
Richard Smith044c8aa2012-11-13 00:54:12 +00008575 // Convert to an expression-statement, and clean up any produced
8576 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008577 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008578 }
John McCallb0207482010-03-16 06:11:48 +00008579
Richard Smith044c8aa2012-11-13 00:54:12 +00008580 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008581 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008582 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008583 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008584 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008585 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008586 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008587 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008588 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008589
8590 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008591 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008592
Douglas Gregor06a9f362010-05-01 20:49:11 +00008593 // Construct a loop over the array bounds, e.g.,
8594 //
8595 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8596 //
8597 // that will copy each of the array elements.
8598 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008599
Douglas Gregor06a9f362010-05-01 20:49:11 +00008600 // Create the iteration variable.
8601 IdentifierInfo *IterationVarName = 0;
8602 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008603 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008604 llvm::raw_svector_ostream OS(Str);
8605 OS << "__i" << Depth;
8606 IterationVarName = &S.Context.Idents.get(OS.str());
8607 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008608 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008609 IterationVarName, SizeType,
8610 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008611 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008612
Douglas Gregor06a9f362010-05-01 20:49:11 +00008613 // Initialize the iteration variable to zero.
8614 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008615 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008616
8617 // Create a reference to the iteration variable; we'll use this several
8618 // times throughout.
8619 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008620 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008621 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008622 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8623 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8624
Douglas Gregor06a9f362010-05-01 20:49:11 +00008625 // Create the DeclStmt that holds the iteration variable.
8626 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008627
Douglas Gregor06a9f362010-05-01 20:49:11 +00008628 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008629 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008630 IterationVarRefRVal,
8631 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008632 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008633 IterationVarRefRVal,
8634 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008635 if (!Copying) // Cast to rvalue
8636 From = CastForMoving(S, From);
8637
8638 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008639 StmtResult Copy =
8640 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8641 To, From, CopyingBaseSubobject,
8642 Copying, Depth + 1);
8643 // Bail out if copying fails or if we determined that we should use memcpy.
8644 if (Copy.isInvalid() || !Copy.get())
8645 return Copy;
8646
8647 // Create the comparison against the array bound.
8648 llvm::APInt Upper
8649 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8650 Expr *Comparison
8651 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8652 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8653 BO_NE, S.Context.BoolTy,
8654 VK_RValue, OK_Ordinary, Loc, false);
8655
8656 // Create the pre-increment of the iteration variable.
8657 Expr *Increment
8658 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8659 VK_LValue, OK_Ordinary, Loc);
8660
Douglas Gregor06a9f362010-05-01 20:49:11 +00008661 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008662 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008663 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008664 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008665 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008666}
8667
Richard Smith8c889532012-11-14 00:50:40 +00008668static StmtResult
8669buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8670 Expr *To, Expr *From,
8671 bool CopyingBaseSubobject, bool Copying) {
8672 // Maybe we should use a memcpy?
8673 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8674 T.isTriviallyCopyableType(S.Context))
8675 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8676
8677 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8678 CopyingBaseSubobject,
8679 Copying, 0));
8680
8681 // If we ended up picking a trivial assignment operator for an array of a
8682 // non-trivially-copyable class type, just emit a memcpy.
8683 if (!Result.isInvalid() && !Result.get())
8684 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8685
8686 return Result;
8687}
8688
Richard Smithb9d0b762012-07-27 04:22:15 +00008689Sema::ImplicitExceptionSpecification
8690Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8691 CXXRecordDecl *ClassDecl = MD->getParent();
8692
8693 ImplicitExceptionSpecification ExceptSpec(*this);
8694 if (ClassDecl->isInvalidDecl())
8695 return ExceptSpec;
8696
8697 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8698 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8699 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8700
Douglas Gregorb87786f2010-07-01 17:48:08 +00008701 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008702 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008703 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008704
8705 // It is unspecified whether or not an implicit copy assignment operator
8706 // attempts to deduplicate calls to assignment operators of virtual bases are
8707 // made. As such, this exception specification is effectively unspecified.
8708 // Based on a similar decision made for constness in C++0x, we're erring on
8709 // the side of assuming such calls to be made regardless of whether they
8710 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008711 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8712 BaseEnd = ClassDecl->bases_end();
8713 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008714 if (Base->isVirtual())
8715 continue;
8716
Douglas Gregora376d102010-07-02 21:50:04 +00008717 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008718 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008719 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8720 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008721 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008722 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008723
8724 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8725 BaseEnd = ClassDecl->vbases_end();
8726 Base != BaseEnd; ++Base) {
8727 CXXRecordDecl *BaseClassDecl
8728 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8729 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8730 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008731 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008732 }
8733
Douglas Gregorb87786f2010-07-01 17:48:08 +00008734 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8735 FieldEnd = ClassDecl->field_end();
8736 Field != FieldEnd;
8737 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008738 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008739 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8740 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008741 LookupCopyingAssignment(FieldClassDecl,
8742 ArgQuals | FieldType.getCVRQualifiers(),
8743 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008744 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008745 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008746 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008747
Richard Smithb9d0b762012-07-27 04:22:15 +00008748 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008749}
8750
8751CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8752 // Note: The following rules are largely analoguous to the copy
8753 // constructor rules. Note that virtual bases are not taken into account
8754 // for determining the argument type of the operator. Note also that
8755 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008756 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008757
Richard Smithafb49182012-11-29 01:34:07 +00008758 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8759 if (DSM.isAlreadyBeingDeclared())
8760 return 0;
8761
Sean Hunt30de05c2011-05-14 05:23:20 +00008762 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8763 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008764 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008765 ArgType = ArgType.withConst();
8766 ArgType = Context.getLValueReferenceType(ArgType);
8767
Douglas Gregord3c35902010-07-01 16:36:15 +00008768 // An implicitly-declared copy assignment operator is an inline public
8769 // member of its class.
8770 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008771 SourceLocation ClassLoc = ClassDecl->getLocation();
8772 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008773 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008774 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008775 /*TInfo=*/0,
8776 /*StorageClass=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008777 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008778 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008779 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008780 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008781 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008782
8783 // Build an exception specification pointing back at this member.
8784 FunctionProtoType::ExtProtoInfo EPI;
8785 EPI.ExceptionSpecType = EST_Unevaluated;
8786 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008787 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008788
Douglas Gregord3c35902010-07-01 16:36:15 +00008789 // Add the parameter to the operator.
8790 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008791 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008792 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008793 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008794 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008795
Richard Smithbc2a35d2012-12-08 08:32:28 +00008796 AddOverriddenMethods(ClassDecl, CopyAssignment);
8797
8798 CopyAssignment->setTrivial(
8799 ClassDecl->needsOverloadResolutionForCopyAssignment()
8800 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8801 : ClassDecl->hasTrivialCopyAssignment());
8802
Nico Weberafcc96a2012-01-23 03:19:29 +00008803 // C++0x [class.copy]p19:
8804 // .... If the class definition does not explicitly declare a copy
8805 // assignment operator, there is no user-declared move constructor, and
8806 // there is no user-declared move assignment operator, a copy assignment
8807 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008808 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008809 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008810
Richard Smithbc2a35d2012-12-08 08:32:28 +00008811 // Note that we have added this copy-assignment operator.
8812 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8813
8814 if (Scope *S = getScopeForContext(ClassDecl))
8815 PushOnScopeChains(CopyAssignment, S, false);
8816 ClassDecl->addDecl(CopyAssignment);
8817
Douglas Gregord3c35902010-07-01 16:36:15 +00008818 return CopyAssignment;
8819}
8820
Douglas Gregor06a9f362010-05-01 20:49:11 +00008821void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8822 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008823 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008824 CopyAssignOperator->isOverloadedOperator() &&
8825 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008826 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8827 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008828 "DefineImplicitCopyAssignment called for wrong function");
8829
8830 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8831
8832 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8833 CopyAssignOperator->setInvalidDecl();
8834 return;
8835 }
8836
8837 CopyAssignOperator->setUsed();
8838
Eli Friedman9a14db32012-10-18 20:14:08 +00008839 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008840 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008841
8842 // C++0x [class.copy]p30:
8843 // The implicitly-defined or explicitly-defaulted copy assignment operator
8844 // for a non-union class X performs memberwise copy assignment of its
8845 // subobjects. The direct base classes of X are assigned first, in the
8846 // order of their declaration in the base-specifier-list, and then the
8847 // immediate non-static data members of X are assigned, in the order in
8848 // which they were declared in the class definition.
8849
8850 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008851 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008852
8853 // The parameter for the "other" object, which we are copying from.
8854 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8855 Qualifiers OtherQuals = Other->getType().getQualifiers();
8856 QualType OtherRefType = Other->getType();
8857 if (const LValueReferenceType *OtherRef
8858 = OtherRefType->getAs<LValueReferenceType>()) {
8859 OtherRefType = OtherRef->getPointeeType();
8860 OtherQuals = OtherRefType.getQualifiers();
8861 }
8862
8863 // Our location for everything implicitly-generated.
8864 SourceLocation Loc = CopyAssignOperator->getLocation();
8865
8866 // Construct a reference to the "other" object. We'll be using this
8867 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008868 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008869 assert(OtherRef && "Reference to parameter cannot fail!");
8870
8871 // Construct the "this" pointer. We'll be using this throughout the generated
8872 // ASTs.
8873 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8874 assert(This && "Reference to this cannot fail!");
8875
8876 // Assign base classes.
8877 bool Invalid = false;
8878 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8879 E = ClassDecl->bases_end(); Base != E; ++Base) {
8880 // Form the assignment:
8881 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8882 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008883 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008884 Invalid = true;
8885 continue;
8886 }
8887
John McCallf871d0c2010-08-07 06:22:56 +00008888 CXXCastPath BasePath;
8889 BasePath.push_back(Base);
8890
Douglas Gregor06a9f362010-05-01 20:49:11 +00008891 // Construct the "from" expression, which is an implicit cast to the
8892 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008893 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008894 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8895 CK_UncheckedDerivedToBase,
8896 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008897
8898 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008899 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008900
8901 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008902 To = ImpCastExprToType(To.take(),
8903 Context.getCVRQualifiedType(BaseType,
8904 CopyAssignOperator->getTypeQualifiers()),
8905 CK_UncheckedDerivedToBase,
8906 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008907
8908 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008909 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008910 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008911 /*CopyingBaseSubobject=*/true,
8912 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008913 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008914 Diag(CurrentLocation, diag::note_member_synthesized_at)
8915 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8916 CopyAssignOperator->setInvalidDecl();
8917 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008918 }
8919
8920 // Success! Record the copy.
8921 Statements.push_back(Copy.takeAs<Expr>());
8922 }
8923
Douglas Gregor06a9f362010-05-01 20:49:11 +00008924 // Assign non-static members.
8925 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8926 FieldEnd = ClassDecl->field_end();
8927 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008928 if (Field->isUnnamedBitfield())
8929 continue;
8930
Douglas Gregor06a9f362010-05-01 20:49:11 +00008931 // Check for members of reference type; we can't copy those.
8932 if (Field->getType()->isReferenceType()) {
8933 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8934 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8935 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008936 Diag(CurrentLocation, diag::note_member_synthesized_at)
8937 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008938 Invalid = true;
8939 continue;
8940 }
8941
8942 // Check for members of const-qualified, non-class type.
8943 QualType BaseType = Context.getBaseElementType(Field->getType());
8944 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8945 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8946 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8947 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008948 Diag(CurrentLocation, diag::note_member_synthesized_at)
8949 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008950 Invalid = true;
8951 continue;
8952 }
John McCallb77115d2011-06-17 00:18:42 +00008953
8954 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008955 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8956 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008957
8958 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008959 if (FieldType->isIncompleteArrayType()) {
8960 assert(ClassDecl->hasFlexibleArrayMember() &&
8961 "Incomplete array type is not valid");
8962 continue;
8963 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008964
8965 // Build references to the field in the object we're copying from and to.
8966 CXXScopeSpec SS; // Intentionally empty
8967 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8968 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008969 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008970 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008971 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008972 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008973 SS, SourceLocation(), 0,
8974 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008975 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008976 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008977 SS, SourceLocation(), 0,
8978 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008979 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8980 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008981
Douglas Gregor06a9f362010-05-01 20:49:11 +00008982 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008983 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008984 To.get(), From.get(),
8985 /*CopyingBaseSubobject=*/false,
8986 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008987 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008988 Diag(CurrentLocation, diag::note_member_synthesized_at)
8989 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8990 CopyAssignOperator->setInvalidDecl();
8991 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008992 }
8993
8994 // Success! Record the copy.
8995 Statements.push_back(Copy.takeAs<Stmt>());
8996 }
8997
8998 if (!Invalid) {
8999 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00009000 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009001
John McCall60d7b3a2010-08-24 06:29:42 +00009002 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009003 if (Return.isInvalid())
9004 Invalid = true;
9005 else {
9006 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009007
9008 if (Trap.hasErrorOccurred()) {
9009 Diag(CurrentLocation, diag::note_member_synthesized_at)
9010 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9011 Invalid = true;
9012 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009013 }
9014 }
9015
9016 if (Invalid) {
9017 CopyAssignOperator->setInvalidDecl();
9018 return;
9019 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009020
9021 StmtResult Body;
9022 {
9023 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009024 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009025 /*isStmtExpr=*/false);
9026 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9027 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009028 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009029
9030 if (ASTMutationListener *L = getASTMutationListener()) {
9031 L->CompletedImplicitDefinition(CopyAssignOperator);
9032 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009033}
9034
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009035Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009036Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9037 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009038
Richard Smithb9d0b762012-07-27 04:22:15 +00009039 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009040 if (ClassDecl->isInvalidDecl())
9041 return ExceptSpec;
9042
9043 // C++0x [except.spec]p14:
9044 // An implicitly declared special member function (Clause 12) shall have an
9045 // exception-specification. [...]
9046
9047 // It is unspecified whether or not an implicit move assignment operator
9048 // attempts to deduplicate calls to assignment operators of virtual bases are
9049 // made. As such, this exception specification is effectively unspecified.
9050 // Based on a similar decision made for constness in C++0x, we're erring on
9051 // the side of assuming such calls to be made regardless of whether they
9052 // actually happen.
9053 // Note that a move constructor is not implicitly declared when there are
9054 // virtual bases, but it can still be user-declared and explicitly defaulted.
9055 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9056 BaseEnd = ClassDecl->bases_end();
9057 Base != BaseEnd; ++Base) {
9058 if (Base->isVirtual())
9059 continue;
9060
9061 CXXRecordDecl *BaseClassDecl
9062 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9063 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009064 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009065 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009066 }
9067
9068 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9069 BaseEnd = ClassDecl->vbases_end();
9070 Base != BaseEnd; ++Base) {
9071 CXXRecordDecl *BaseClassDecl
9072 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9073 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009074 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009075 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009076 }
9077
9078 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9079 FieldEnd = ClassDecl->field_end();
9080 Field != FieldEnd;
9081 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009082 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009083 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009084 if (CXXMethodDecl *MoveAssign =
9085 LookupMovingAssignment(FieldClassDecl,
9086 FieldType.getCVRQualifiers(),
9087 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009088 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009089 }
9090 }
9091
9092 return ExceptSpec;
9093}
9094
Richard Smith1c931be2012-04-02 18:40:40 +00009095/// Determine whether the class type has any direct or indirect virtual base
9096/// classes which have a non-trivial move assignment operator.
9097static bool
9098hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9099 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9100 BaseEnd = ClassDecl->vbases_end();
9101 Base != BaseEnd; ++Base) {
9102 CXXRecordDecl *BaseClass =
9103 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9104
9105 // Try to declare the move assignment. If it would be deleted, then the
9106 // class does not have a non-trivial move assignment.
9107 if (BaseClass->needsImplicitMoveAssignment())
9108 S.DeclareImplicitMoveAssignment(BaseClass);
9109
Richard Smith426391c2012-11-16 00:53:38 +00009110 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009111 return true;
9112 }
9113
9114 return false;
9115}
9116
9117/// Determine whether the given type either has a move constructor or is
9118/// trivially copyable.
9119static bool
9120hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9121 Type = S.Context.getBaseElementType(Type);
9122
9123 // FIXME: Technically, non-trivially-copyable non-class types, such as
9124 // reference types, are supposed to return false here, but that appears
9125 // to be a standard defect.
9126 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009127 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009128 return true;
9129
9130 if (Type.isTriviallyCopyableType(S.Context))
9131 return true;
9132
9133 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009134 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9135 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009136 if (ClassDecl->needsImplicitMoveConstructor())
9137 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009138 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009139 }
9140
Richard Smithe5411b72012-12-01 02:35:44 +00009141 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9142 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009143 if (ClassDecl->needsImplicitMoveAssignment())
9144 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009145 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009146}
9147
9148/// Determine whether all non-static data members and direct or virtual bases
9149/// of class \p ClassDecl have either a move operation, or are trivially
9150/// copyable.
9151static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9152 bool IsConstructor) {
9153 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9154 BaseEnd = ClassDecl->bases_end();
9155 Base != BaseEnd; ++Base) {
9156 if (Base->isVirtual())
9157 continue;
9158
9159 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9160 return false;
9161 }
9162
9163 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9164 BaseEnd = ClassDecl->vbases_end();
9165 Base != BaseEnd; ++Base) {
9166 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9167 return false;
9168 }
9169
9170 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9171 FieldEnd = ClassDecl->field_end();
9172 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009173 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009174 return false;
9175 }
9176
9177 return true;
9178}
9179
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009180CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009181 // C++11 [class.copy]p20:
9182 // If the definition of a class X does not explicitly declare a move
9183 // assignment operator, one will be implicitly declared as defaulted
9184 // if and only if:
9185 //
9186 // - [first 4 bullets]
9187 assert(ClassDecl->needsImplicitMoveAssignment());
9188
Richard Smithafb49182012-11-29 01:34:07 +00009189 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9190 if (DSM.isAlreadyBeingDeclared())
9191 return 0;
9192
Richard Smith1c931be2012-04-02 18:40:40 +00009193 // [Checked after we build the declaration]
9194 // - the move assignment operator would not be implicitly defined as
9195 // deleted,
9196
9197 // [DR1402]:
9198 // - X has no direct or indirect virtual base class with a non-trivial
9199 // move assignment operator, and
9200 // - each of X's non-static data members and direct or virtual base classes
9201 // has a type that either has a move assignment operator or is trivially
9202 // copyable.
9203 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9204 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9205 ClassDecl->setFailedImplicitMoveAssignment();
9206 return 0;
9207 }
9208
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009209 // Note: The following rules are largely analoguous to the move
9210 // constructor rules.
9211
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009212 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9213 QualType RetType = Context.getLValueReferenceType(ArgType);
9214 ArgType = Context.getRValueReferenceType(ArgType);
9215
9216 // An implicitly-declared move assignment operator is an inline public
9217 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009218 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9219 SourceLocation ClassLoc = ClassDecl->getLocation();
9220 DeclarationNameInfo NameInfo(Name, ClassLoc);
9221 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00009222 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009223 /*TInfo=*/0,
9224 /*StorageClass=*/SC_None,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009225 /*isInline=*/true,
9226 /*isConstexpr=*/false,
9227 SourceLocation());
9228 MoveAssignment->setAccess(AS_public);
9229 MoveAssignment->setDefaulted();
9230 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009231
Richard Smithb9d0b762012-07-27 04:22:15 +00009232 // Build an exception specification pointing back at this member.
9233 FunctionProtoType::ExtProtoInfo EPI;
9234 EPI.ExceptionSpecType = EST_Unevaluated;
9235 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009236 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009237
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009238 // Add the parameter to the operator.
9239 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9240 ClassLoc, ClassLoc, /*Id=*/0,
9241 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009242 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009243 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009244
Richard Smithbc2a35d2012-12-08 08:32:28 +00009245 AddOverriddenMethods(ClassDecl, MoveAssignment);
9246
9247 MoveAssignment->setTrivial(
9248 ClassDecl->needsOverloadResolutionForMoveAssignment()
9249 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9250 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009251
9252 // C++0x [class.copy]p9:
9253 // If the definition of a class X does not explicitly declare a move
9254 // assignment operator, one will be implicitly declared as defaulted if and
9255 // only if:
9256 // [...]
9257 // - the move assignment operator would not be implicitly defined as
9258 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009259 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009260 // Cache this result so that we don't try to generate this over and over
9261 // on every lookup, leaking memory and wasting time.
9262 ClassDecl->setFailedImplicitMoveAssignment();
9263 return 0;
9264 }
9265
Richard Smithbc2a35d2012-12-08 08:32:28 +00009266 // Note that we have added this copy-assignment operator.
9267 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9268
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009269 if (Scope *S = getScopeForContext(ClassDecl))
9270 PushOnScopeChains(MoveAssignment, S, false);
9271 ClassDecl->addDecl(MoveAssignment);
9272
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009273 return MoveAssignment;
9274}
9275
9276void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9277 CXXMethodDecl *MoveAssignOperator) {
9278 assert((MoveAssignOperator->isDefaulted() &&
9279 MoveAssignOperator->isOverloadedOperator() &&
9280 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009281 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9282 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009283 "DefineImplicitMoveAssignment called for wrong function");
9284
9285 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9286
9287 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9288 MoveAssignOperator->setInvalidDecl();
9289 return;
9290 }
9291
9292 MoveAssignOperator->setUsed();
9293
Eli Friedman9a14db32012-10-18 20:14:08 +00009294 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009295 DiagnosticErrorTrap Trap(Diags);
9296
9297 // C++0x [class.copy]p28:
9298 // The implicitly-defined or move assignment operator for a non-union class
9299 // X performs memberwise move assignment of its subobjects. The direct base
9300 // classes of X are assigned first, in the order of their declaration in the
9301 // base-specifier-list, and then the immediate non-static data members of X
9302 // are assigned, in the order in which they were declared in the class
9303 // definition.
9304
9305 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009306 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009307
9308 // The parameter for the "other" object, which we are move from.
9309 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9310 QualType OtherRefType = Other->getType()->
9311 getAs<RValueReferenceType>()->getPointeeType();
9312 assert(OtherRefType.getQualifiers() == 0 &&
9313 "Bad argument type of defaulted move assignment");
9314
9315 // Our location for everything implicitly-generated.
9316 SourceLocation Loc = MoveAssignOperator->getLocation();
9317
9318 // Construct a reference to the "other" object. We'll be using this
9319 // throughout the generated ASTs.
9320 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9321 assert(OtherRef && "Reference to parameter cannot fail!");
9322 // Cast to rvalue.
9323 OtherRef = CastForMoving(*this, OtherRef);
9324
9325 // Construct the "this" pointer. We'll be using this throughout the generated
9326 // ASTs.
9327 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9328 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009329
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009330 // Assign base classes.
9331 bool Invalid = false;
9332 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9333 E = ClassDecl->bases_end(); Base != E; ++Base) {
9334 // Form the assignment:
9335 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9336 QualType BaseType = Base->getType().getUnqualifiedType();
9337 if (!BaseType->isRecordType()) {
9338 Invalid = true;
9339 continue;
9340 }
9341
9342 CXXCastPath BasePath;
9343 BasePath.push_back(Base);
9344
9345 // Construct the "from" expression, which is an implicit cast to the
9346 // appropriately-qualified base type.
9347 Expr *From = OtherRef;
9348 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009349 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009350
9351 // Dereference "this".
9352 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9353
9354 // Implicitly cast "this" to the appropriately-qualified base type.
9355 To = ImpCastExprToType(To.take(),
9356 Context.getCVRQualifiedType(BaseType,
9357 MoveAssignOperator->getTypeQualifiers()),
9358 CK_UncheckedDerivedToBase,
9359 VK_LValue, &BasePath);
9360
9361 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009362 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009363 To.get(), From,
9364 /*CopyingBaseSubobject=*/true,
9365 /*Copying=*/false);
9366 if (Move.isInvalid()) {
9367 Diag(CurrentLocation, diag::note_member_synthesized_at)
9368 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9369 MoveAssignOperator->setInvalidDecl();
9370 return;
9371 }
9372
9373 // Success! Record the move.
9374 Statements.push_back(Move.takeAs<Expr>());
9375 }
9376
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009377 // Assign non-static members.
9378 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9379 FieldEnd = ClassDecl->field_end();
9380 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009381 if (Field->isUnnamedBitfield())
9382 continue;
9383
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009384 // Check for members of reference type; we can't move those.
9385 if (Field->getType()->isReferenceType()) {
9386 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9387 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9388 Diag(Field->getLocation(), diag::note_declared_at);
9389 Diag(CurrentLocation, diag::note_member_synthesized_at)
9390 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9391 Invalid = true;
9392 continue;
9393 }
9394
9395 // Check for members of const-qualified, non-class type.
9396 QualType BaseType = Context.getBaseElementType(Field->getType());
9397 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9398 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9399 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9400 Diag(Field->getLocation(), diag::note_declared_at);
9401 Diag(CurrentLocation, diag::note_member_synthesized_at)
9402 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9403 Invalid = true;
9404 continue;
9405 }
9406
9407 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009408 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9409 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009410
9411 QualType FieldType = Field->getType().getNonReferenceType();
9412 if (FieldType->isIncompleteArrayType()) {
9413 assert(ClassDecl->hasFlexibleArrayMember() &&
9414 "Incomplete array type is not valid");
9415 continue;
9416 }
9417
9418 // Build references to the field in the object we're copying from and to.
9419 CXXScopeSpec SS; // Intentionally empty
9420 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9421 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009422 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009423 MemberLookup.resolveKind();
9424 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9425 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009426 SS, SourceLocation(), 0,
9427 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009428 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9429 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009430 SS, SourceLocation(), 0,
9431 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009432 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9433 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9434
9435 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9436 "Member reference with rvalue base must be rvalue except for reference "
9437 "members, which aren't allowed for move assignment.");
9438
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009439 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009440 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009441 To.get(), From.get(),
9442 /*CopyingBaseSubobject=*/false,
9443 /*Copying=*/false);
9444 if (Move.isInvalid()) {
9445 Diag(CurrentLocation, diag::note_member_synthesized_at)
9446 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9447 MoveAssignOperator->setInvalidDecl();
9448 return;
9449 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009450
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009451 // Success! Record the copy.
9452 Statements.push_back(Move.takeAs<Stmt>());
9453 }
9454
9455 if (!Invalid) {
9456 // Add a "return *this;"
9457 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9458
9459 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9460 if (Return.isInvalid())
9461 Invalid = true;
9462 else {
9463 Statements.push_back(Return.takeAs<Stmt>());
9464
9465 if (Trap.hasErrorOccurred()) {
9466 Diag(CurrentLocation, diag::note_member_synthesized_at)
9467 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9468 Invalid = true;
9469 }
9470 }
9471 }
9472
9473 if (Invalid) {
9474 MoveAssignOperator->setInvalidDecl();
9475 return;
9476 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009477
9478 StmtResult Body;
9479 {
9480 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009481 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009482 /*isStmtExpr=*/false);
9483 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9484 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009485 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9486
9487 if (ASTMutationListener *L = getASTMutationListener()) {
9488 L->CompletedImplicitDefinition(MoveAssignOperator);
9489 }
9490}
9491
Richard Smithb9d0b762012-07-27 04:22:15 +00009492Sema::ImplicitExceptionSpecification
9493Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9494 CXXRecordDecl *ClassDecl = MD->getParent();
9495
9496 ImplicitExceptionSpecification ExceptSpec(*this);
9497 if (ClassDecl->isInvalidDecl())
9498 return ExceptSpec;
9499
9500 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9501 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9502 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9503
Douglas Gregor0d405db2010-07-01 20:59:04 +00009504 // C++ [except.spec]p14:
9505 // An implicitly declared special member function (Clause 12) shall have an
9506 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009507 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9508 BaseEnd = ClassDecl->bases_end();
9509 Base != BaseEnd;
9510 ++Base) {
9511 // Virtual bases are handled below.
9512 if (Base->isVirtual())
9513 continue;
9514
Douglas Gregor22584312010-07-02 23:41:54 +00009515 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009516 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009517 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009518 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009519 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009520 }
9521 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9522 BaseEnd = ClassDecl->vbases_end();
9523 Base != BaseEnd;
9524 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009525 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009526 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009527 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009528 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009529 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009530 }
9531 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9532 FieldEnd = ClassDecl->field_end();
9533 Field != FieldEnd;
9534 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009535 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009536 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9537 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009538 LookupCopyingConstructor(FieldClassDecl,
9539 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009540 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009541 }
9542 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009543
Richard Smithb9d0b762012-07-27 04:22:15 +00009544 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009545}
9546
9547CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9548 CXXRecordDecl *ClassDecl) {
9549 // C++ [class.copy]p4:
9550 // If the class definition does not explicitly declare a copy
9551 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009552 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009553
Richard Smithafb49182012-11-29 01:34:07 +00009554 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9555 if (DSM.isAlreadyBeingDeclared())
9556 return 0;
9557
Sean Hunt49634cf2011-05-13 06:10:58 +00009558 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9559 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009560 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009561 if (Const)
9562 ArgType = ArgType.withConst();
9563 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009564
Richard Smith7756afa2012-06-10 05:43:50 +00009565 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9566 CXXCopyConstructor,
9567 Const);
9568
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009569 DeclarationName Name
9570 = Context.DeclarationNames.getCXXConstructorName(
9571 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009572 SourceLocation ClassLoc = ClassDecl->getLocation();
9573 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009574
9575 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009576 // member of its class.
9577 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009578 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009579 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009580 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009581 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009582 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009583
Richard Smithb9d0b762012-07-27 04:22:15 +00009584 // Build an exception specification pointing back at this member.
9585 FunctionProtoType::ExtProtoInfo EPI;
9586 EPI.ExceptionSpecType = EST_Unevaluated;
9587 EPI.ExceptionSpecDecl = CopyConstructor;
9588 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009589 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009590
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009591 // Add the parameter to the constructor.
9592 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009593 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009594 /*IdentifierInfo=*/0,
9595 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009596 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009597 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009598
Richard Smithbc2a35d2012-12-08 08:32:28 +00009599 CopyConstructor->setTrivial(
9600 ClassDecl->needsOverloadResolutionForCopyConstructor()
9601 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9602 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009603
Nico Weberafcc96a2012-01-23 03:19:29 +00009604 // C++11 [class.copy]p8:
9605 // ... If the class definition does not explicitly declare a copy
9606 // constructor, there is no user-declared move constructor, and there is no
9607 // user-declared move assignment operator, a copy constructor is implicitly
9608 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009609 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009610 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009611
Richard Smithbc2a35d2012-12-08 08:32:28 +00009612 // Note that we have declared this constructor.
9613 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9614
9615 if (Scope *S = getScopeForContext(ClassDecl))
9616 PushOnScopeChains(CopyConstructor, S, false);
9617 ClassDecl->addDecl(CopyConstructor);
9618
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009619 return CopyConstructor;
9620}
9621
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009622void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009623 CXXConstructorDecl *CopyConstructor) {
9624 assert((CopyConstructor->isDefaulted() &&
9625 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009626 !CopyConstructor->doesThisDeclarationHaveABody() &&
9627 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009628 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009629
Anders Carlsson63010a72010-04-23 16:24:12 +00009630 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009631 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009632
Eli Friedman9a14db32012-10-18 20:14:08 +00009633 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009634 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009635
David Blaikie93c86172013-01-17 05:26:25 +00009636 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009637 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009638 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009639 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009640 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009641 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009642 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009643 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9644 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009645 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009646 /*isStmtExpr=*/false)
9647 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009648 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009649 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009650
9651 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009652 if (ASTMutationListener *L = getASTMutationListener()) {
9653 L->CompletedImplicitDefinition(CopyConstructor);
9654 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009655}
9656
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009657Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009658Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9659 CXXRecordDecl *ClassDecl = MD->getParent();
9660
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009661 // C++ [except.spec]p14:
9662 // An implicitly declared special member function (Clause 12) shall have an
9663 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009664 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009665 if (ClassDecl->isInvalidDecl())
9666 return ExceptSpec;
9667
9668 // Direct base-class constructors.
9669 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9670 BEnd = ClassDecl->bases_end();
9671 B != BEnd; ++B) {
9672 if (B->isVirtual()) // Handled below.
9673 continue;
9674
9675 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9676 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009677 CXXConstructorDecl *Constructor =
9678 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009679 // If this is a deleted function, add it anyway. This might be conformant
9680 // with the standard. This might not. I'm not sure. It might not matter.
9681 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009682 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009683 }
9684 }
9685
9686 // Virtual base-class constructors.
9687 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9688 BEnd = ClassDecl->vbases_end();
9689 B != BEnd; ++B) {
9690 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9691 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009692 CXXConstructorDecl *Constructor =
9693 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009694 // If this is a deleted function, add it anyway. This might be conformant
9695 // with the standard. This might not. I'm not sure. It might not matter.
9696 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009697 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009698 }
9699 }
9700
9701 // Field constructors.
9702 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9703 FEnd = ClassDecl->field_end();
9704 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009705 QualType FieldType = Context.getBaseElementType(F->getType());
9706 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9707 CXXConstructorDecl *Constructor =
9708 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009709 // If this is a deleted function, add it anyway. This might be conformant
9710 // with the standard. This might not. I'm not sure. It might not matter.
9711 // In particular, the problem is that this function never gets called. It
9712 // might just be ill-formed because this function attempts to refer to
9713 // a deleted function here.
9714 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009715 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009716 }
9717 }
9718
9719 return ExceptSpec;
9720}
9721
9722CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9723 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009724 // C++11 [class.copy]p9:
9725 // If the definition of a class X does not explicitly declare a move
9726 // constructor, one will be implicitly declared as defaulted if and only if:
9727 //
9728 // - [first 4 bullets]
9729 assert(ClassDecl->needsImplicitMoveConstructor());
9730
Richard Smithafb49182012-11-29 01:34:07 +00009731 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9732 if (DSM.isAlreadyBeingDeclared())
9733 return 0;
9734
Richard Smith1c931be2012-04-02 18:40:40 +00009735 // [Checked after we build the declaration]
9736 // - the move assignment operator would not be implicitly defined as
9737 // deleted,
9738
9739 // [DR1402]:
9740 // - each of X's non-static data members and direct or virtual base classes
9741 // has a type that either has a move constructor or is trivially copyable.
9742 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9743 ClassDecl->setFailedImplicitMoveConstructor();
9744 return 0;
9745 }
9746
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009747 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9748 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009749
Richard Smith7756afa2012-06-10 05:43:50 +00009750 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9751 CXXMoveConstructor,
9752 false);
9753
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009754 DeclarationName Name
9755 = Context.DeclarationNames.getCXXConstructorName(
9756 Context.getCanonicalType(ClassType));
9757 SourceLocation ClassLoc = ClassDecl->getLocation();
9758 DeclarationNameInfo NameInfo(Name, ClassLoc);
9759
9760 // C++0x [class.copy]p11:
9761 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009762 // member of its class.
9763 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009764 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009765 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009766 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009767 MoveConstructor->setAccess(AS_public);
9768 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009769
Richard Smithb9d0b762012-07-27 04:22:15 +00009770 // Build an exception specification pointing back at this member.
9771 FunctionProtoType::ExtProtoInfo EPI;
9772 EPI.ExceptionSpecType = EST_Unevaluated;
9773 EPI.ExceptionSpecDecl = MoveConstructor;
9774 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009775 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009776
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009777 // Add the parameter to the constructor.
9778 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9779 ClassLoc, ClassLoc,
9780 /*IdentifierInfo=*/0,
9781 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009782 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009783 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009784
Richard Smithbc2a35d2012-12-08 08:32:28 +00009785 MoveConstructor->setTrivial(
9786 ClassDecl->needsOverloadResolutionForMoveConstructor()
9787 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9788 : ClassDecl->hasTrivialMoveConstructor());
9789
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009790 // C++0x [class.copy]p9:
9791 // If the definition of a class X does not explicitly declare a move
9792 // constructor, one will be implicitly declared as defaulted if and only if:
9793 // [...]
9794 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009795 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009796 // Cache this result so that we don't try to generate this over and over
9797 // on every lookup, leaking memory and wasting time.
9798 ClassDecl->setFailedImplicitMoveConstructor();
9799 return 0;
9800 }
9801
9802 // Note that we have declared this constructor.
9803 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9804
9805 if (Scope *S = getScopeForContext(ClassDecl))
9806 PushOnScopeChains(MoveConstructor, S, false);
9807 ClassDecl->addDecl(MoveConstructor);
9808
9809 return MoveConstructor;
9810}
9811
9812void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9813 CXXConstructorDecl *MoveConstructor) {
9814 assert((MoveConstructor->isDefaulted() &&
9815 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009816 !MoveConstructor->doesThisDeclarationHaveABody() &&
9817 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009818 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9819
9820 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9821 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9822
Eli Friedman9a14db32012-10-18 20:14:08 +00009823 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009824 DiagnosticErrorTrap Trap(Diags);
9825
David Blaikie93c86172013-01-17 05:26:25 +00009826 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009827 Trap.hasErrorOccurred()) {
9828 Diag(CurrentLocation, diag::note_member_synthesized_at)
9829 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9830 MoveConstructor->setInvalidDecl();
9831 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009832 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009833 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9834 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009835 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009836 /*isStmtExpr=*/false)
9837 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009838 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009839 }
9840
9841 MoveConstructor->setUsed();
9842
9843 if (ASTMutationListener *L = getASTMutationListener()) {
9844 L->CompletedImplicitDefinition(MoveConstructor);
9845 }
9846}
9847
Douglas Gregore4e68d42012-02-15 19:33:52 +00009848bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9849 return FD->isDeleted() &&
9850 (FD->isDefaulted() || FD->isImplicit()) &&
9851 isa<CXXMethodDecl>(FD);
9852}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009853
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009854/// \brief Mark the call operator of the given lambda closure type as "used".
9855static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9856 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009857 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009858 Lambda->lookup(
9859 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009860 CallOperator->setReferenced();
9861 CallOperator->setUsed();
9862}
9863
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009864void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9865 SourceLocation CurrentLocation,
9866 CXXConversionDecl *Conv)
9867{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009868 CXXRecordDecl *Lambda = Conv->getParent();
9869
9870 // Make sure that the lambda call operator is marked used.
9871 markLambdaCallOperatorUsed(*this, Lambda);
9872
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009873 Conv->setUsed();
9874
Eli Friedman9a14db32012-10-18 20:14:08 +00009875 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009876 DiagnosticErrorTrap Trap(Diags);
9877
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009878 // Return the address of the __invoke function.
9879 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9880 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009881 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009882 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9883 VK_LValue, Conv->getLocation()).take();
9884 assert(FunctionRef && "Can't refer to __invoke function?");
9885 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009886 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009887 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009888 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009889
9890 // Fill in the __invoke function with a dummy implementation. IR generation
9891 // will fill in the actual details.
9892 Invoke->setUsed();
9893 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009894 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009895
9896 if (ASTMutationListener *L = getASTMutationListener()) {
9897 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009898 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009899 }
9900}
9901
9902void Sema::DefineImplicitLambdaToBlockPointerConversion(
9903 SourceLocation CurrentLocation,
9904 CXXConversionDecl *Conv)
9905{
9906 Conv->setUsed();
9907
Eli Friedman9a14db32012-10-18 20:14:08 +00009908 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009909 DiagnosticErrorTrap Trap(Diags);
9910
Douglas Gregorac1303e2012-02-22 05:02:47 +00009911 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009912 Expr *This = ActOnCXXThis(CurrentLocation).take();
9913 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009914
Eli Friedman23f02672012-03-01 04:01:32 +00009915 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9916 Conv->getLocation(),
9917 Conv, DerefThis);
9918
9919 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9920 // behavior. Note that only the general conversion function does this
9921 // (since it's unusable otherwise); in the case where we inline the
9922 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009923 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009924 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9925 CK_CopyAndAutoreleaseBlockObject,
9926 BuildBlock.get(), 0, VK_RValue);
9927
9928 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009929 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009930 Conv->setInvalidDecl();
9931 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009932 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009933
Douglas Gregorac1303e2012-02-22 05:02:47 +00009934 // Create the return statement that returns the block from the conversion
9935 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009936 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009937 if (Return.isInvalid()) {
9938 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9939 Conv->setInvalidDecl();
9940 return;
9941 }
9942
9943 // Set the body of the conversion function.
9944 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009945 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009946 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009947 Conv->getLocation()));
9948
Douglas Gregorac1303e2012-02-22 05:02:47 +00009949 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009950 if (ASTMutationListener *L = getASTMutationListener()) {
9951 L->CompletedImplicitDefinition(Conv);
9952 }
9953}
9954
Douglas Gregorf52757d2012-03-10 06:53:13 +00009955/// \brief Determine whether the given list arguments contains exactly one
9956/// "real" (non-default) argument.
9957static bool hasOneRealArgument(MultiExprArg Args) {
9958 switch (Args.size()) {
9959 case 0:
9960 return false;
9961
9962 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009963 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009964 return false;
9965
9966 // fall through
9967 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009968 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009969 }
9970
9971 return false;
9972}
9973
John McCall60d7b3a2010-08-24 06:29:42 +00009974ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009975Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009976 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009977 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009978 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009979 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009980 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009981 unsigned ConstructKind,
9982 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009983 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009984
Douglas Gregor2f599792010-04-02 18:24:57 +00009985 // C++0x [class.copy]p34:
9986 // When certain criteria are met, an implementation is allowed to
9987 // omit the copy/move construction of a class object, even if the
9988 // copy/move constructor and/or destructor for the object have
9989 // side effects. [...]
9990 // - when a temporary class object that has not been bound to a
9991 // reference (12.2) would be copied/moved to a class object
9992 // with the same cv-unqualified type, the copy/move operation
9993 // can be omitted by constructing the temporary object
9994 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009995 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009996 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009997 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009998 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009999 }
Mike Stump1eb44332009-09-09 15:08:12 +000010000
10001 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010002 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010003 IsListInitialization, RequiresZeroInit,
10004 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010005}
10006
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010007/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10008/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010009ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010010Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10011 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010012 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010013 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010014 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010015 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010016 unsigned ConstructKind,
10017 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010018 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010019 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010020 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010021 HadMultipleCandidates,
10022 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010023 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10024 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010025}
10026
John McCall68c6c9a2010-02-02 09:10:11 +000010027void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010028 if (VD->isInvalidDecl()) return;
10029
John McCall68c6c9a2010-02-02 09:10:11 +000010030 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010031 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010032 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010033 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010034
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010035 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010036 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010037 CheckDestructorAccess(VD->getLocation(), Destructor,
10038 PDiag(diag::err_access_dtor_var)
10039 << VD->getDeclName()
10040 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010041 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010042
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010043 if (!VD->hasGlobalStorage()) return;
10044
10045 // Emit warning for non-trivial dtor in global scope (a real global,
10046 // class-static, function-static).
10047 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10048
10049 // TODO: this should be re-enabled for static locals by !CXAAtExit
10050 if (!VD->isStaticLocal())
10051 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010052}
10053
Douglas Gregor39da0b82009-09-09 23:08:42 +000010054/// \brief Given a constructor and the set of arguments provided for the
10055/// constructor, convert the arguments and add any required default arguments
10056/// to form a proper call to this constructor.
10057///
10058/// \returns true if an error occurred, false otherwise.
10059bool
10060Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10061 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010062 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010063 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010064 bool AllowExplicit,
10065 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010066 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10067 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010068 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010069
10070 const FunctionProtoType *Proto
10071 = Constructor->getType()->getAs<FunctionProtoType>();
10072 assert(Proto && "Constructor without a prototype?");
10073 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010074
10075 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010076 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010077 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010078 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010079 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010080
10081 VariadicCallType CallType =
10082 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010083 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010084 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10085 Proto, 0, Args, NumArgs, AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010086 CallType, AllowExplicit,
10087 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010088 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010089
10090 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
10091
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010092 CheckConstructorCall(Constructor,
10093 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10094 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010095 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010096
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010097 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010098}
10099
Anders Carlsson20d45d22009-12-12 00:32:00 +000010100static inline bool
10101CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10102 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010103 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010104 if (isa<NamespaceDecl>(DC)) {
10105 return SemaRef.Diag(FnDecl->getLocation(),
10106 diag::err_operator_new_delete_declared_in_namespace)
10107 << FnDecl->getDeclName();
10108 }
10109
10110 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010111 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010112 return SemaRef.Diag(FnDecl->getLocation(),
10113 diag::err_operator_new_delete_declared_static)
10114 << FnDecl->getDeclName();
10115 }
10116
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010117 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010118}
10119
Anders Carlsson156c78e2009-12-13 17:53:43 +000010120static inline bool
10121CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10122 CanQualType ExpectedResultType,
10123 CanQualType ExpectedFirstParamType,
10124 unsigned DependentParamTypeDiag,
10125 unsigned InvalidParamTypeDiag) {
10126 QualType ResultType =
10127 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10128
10129 // Check that the result type is not dependent.
10130 if (ResultType->isDependentType())
10131 return SemaRef.Diag(FnDecl->getLocation(),
10132 diag::err_operator_new_delete_dependent_result_type)
10133 << FnDecl->getDeclName() << ExpectedResultType;
10134
10135 // Check that the result type is what we expect.
10136 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10137 return SemaRef.Diag(FnDecl->getLocation(),
10138 diag::err_operator_new_delete_invalid_result_type)
10139 << FnDecl->getDeclName() << ExpectedResultType;
10140
10141 // A function template must have at least 2 parameters.
10142 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10143 return SemaRef.Diag(FnDecl->getLocation(),
10144 diag::err_operator_new_delete_template_too_few_parameters)
10145 << FnDecl->getDeclName();
10146
10147 // The function decl must have at least 1 parameter.
10148 if (FnDecl->getNumParams() == 0)
10149 return SemaRef.Diag(FnDecl->getLocation(),
10150 diag::err_operator_new_delete_too_few_parameters)
10151 << FnDecl->getDeclName();
10152
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010153 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010154 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10155 if (FirstParamType->isDependentType())
10156 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10157 << FnDecl->getDeclName() << ExpectedFirstParamType;
10158
10159 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010160 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010161 ExpectedFirstParamType)
10162 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10163 << FnDecl->getDeclName() << ExpectedFirstParamType;
10164
10165 return false;
10166}
10167
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010168static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010169CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010170 // C++ [basic.stc.dynamic.allocation]p1:
10171 // A program is ill-formed if an allocation function is declared in a
10172 // namespace scope other than global scope or declared static in global
10173 // scope.
10174 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10175 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010176
10177 CanQualType SizeTy =
10178 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10179
10180 // C++ [basic.stc.dynamic.allocation]p1:
10181 // The return type shall be void*. The first parameter shall have type
10182 // std::size_t.
10183 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10184 SizeTy,
10185 diag::err_operator_new_dependent_param_type,
10186 diag::err_operator_new_param_type))
10187 return true;
10188
10189 // C++ [basic.stc.dynamic.allocation]p1:
10190 // The first parameter shall not have an associated default argument.
10191 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010192 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010193 diag::err_operator_new_default_arg)
10194 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10195
10196 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010197}
10198
10199static bool
Richard Smith444d3842012-10-20 08:26:51 +000010200CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010201 // C++ [basic.stc.dynamic.deallocation]p1:
10202 // A program is ill-formed if deallocation functions are declared in a
10203 // namespace scope other than global scope or declared static in global
10204 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010205 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10206 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010207
10208 // C++ [basic.stc.dynamic.deallocation]p2:
10209 // Each deallocation function shall return void and its first parameter
10210 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010211 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10212 SemaRef.Context.VoidPtrTy,
10213 diag::err_operator_delete_dependent_param_type,
10214 diag::err_operator_delete_param_type))
10215 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010216
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010217 return false;
10218}
10219
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010220/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10221/// of this overloaded operator is well-formed. If so, returns false;
10222/// otherwise, emits appropriate diagnostics and returns true.
10223bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010224 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010225 "Expected an overloaded operator declaration");
10226
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010227 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10228
Mike Stump1eb44332009-09-09 15:08:12 +000010229 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010230 // The allocation and deallocation functions, operator new,
10231 // operator new[], operator delete and operator delete[], are
10232 // described completely in 3.7.3. The attributes and restrictions
10233 // found in the rest of this subclause do not apply to them unless
10234 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010235 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010236 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010237
Anders Carlssona3ccda52009-12-12 00:26:23 +000010238 if (Op == OO_New || Op == OO_Array_New)
10239 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010240
10241 // C++ [over.oper]p6:
10242 // An operator function shall either be a non-static member
10243 // function or be a non-member function and have at least one
10244 // parameter whose type is a class, a reference to a class, an
10245 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010246 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10247 if (MethodDecl->isStatic())
10248 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010249 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010250 } else {
10251 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010252 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10253 ParamEnd = FnDecl->param_end();
10254 Param != ParamEnd; ++Param) {
10255 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010256 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10257 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010258 ClassOrEnumParam = true;
10259 break;
10260 }
10261 }
10262
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010263 if (!ClassOrEnumParam)
10264 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010265 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010266 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010267 }
10268
10269 // C++ [over.oper]p8:
10270 // An operator function cannot have default arguments (8.3.6),
10271 // except where explicitly stated below.
10272 //
Mike Stump1eb44332009-09-09 15:08:12 +000010273 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010274 // (C++ [over.call]p1).
10275 if (Op != OO_Call) {
10276 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10277 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010278 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010279 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010280 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010281 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010282 }
10283 }
10284
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010285 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10286 { false, false, false }
10287#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10288 , { Unary, Binary, MemberOnly }
10289#include "clang/Basic/OperatorKinds.def"
10290 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010291
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010292 bool CanBeUnaryOperator = OperatorUses[Op][0];
10293 bool CanBeBinaryOperator = OperatorUses[Op][1];
10294 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010295
10296 // C++ [over.oper]p8:
10297 // [...] Operator functions cannot have more or fewer parameters
10298 // than the number required for the corresponding operator, as
10299 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010300 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010301 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010302 if (Op != OO_Call &&
10303 ((NumParams == 1 && !CanBeUnaryOperator) ||
10304 (NumParams == 2 && !CanBeBinaryOperator) ||
10305 (NumParams < 1) || (NumParams > 2))) {
10306 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010307 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010308 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010309 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010310 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010311 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010312 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010313 assert(CanBeBinaryOperator &&
10314 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010315 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010316 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010317
Chris Lattner416e46f2008-11-21 07:57:12 +000010318 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010319 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010320 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010321
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010322 // Overloaded operators other than operator() cannot be variadic.
10323 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010324 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010325 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010326 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010327 }
10328
10329 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010330 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10331 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010332 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010333 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010334 }
10335
10336 // C++ [over.inc]p1:
10337 // The user-defined function called operator++ implements the
10338 // prefix and postfix ++ operator. If this function is a member
10339 // function with no parameters, or a non-member function with one
10340 // parameter of class or enumeration type, it defines the prefix
10341 // increment operator ++ for objects of that type. If the function
10342 // is a member function with one parameter (which shall be of type
10343 // int) or a non-member function with two parameters (the second
10344 // of which shall be of type int), it defines the postfix
10345 // increment operator ++ for objects of that type.
10346 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10347 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10348 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010349 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010350 ParamIsInt = BT->getKind() == BuiltinType::Int;
10351
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010352 if (!ParamIsInt)
10353 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010354 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010355 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010356 }
10357
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010358 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010359}
Chris Lattner5a003a42008-12-17 07:09:26 +000010360
Sean Hunta6c058d2010-01-13 09:01:02 +000010361/// CheckLiteralOperatorDeclaration - Check whether the declaration
10362/// of this literal operator function is well-formed. If so, returns
10363/// false; otherwise, emits appropriate diagnostics and returns true.
10364bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010365 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010366 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10367 << FnDecl->getDeclName();
10368 return true;
10369 }
10370
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010371 if (FnDecl->isExternC()) {
10372 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10373 return true;
10374 }
10375
Sean Hunta6c058d2010-01-13 09:01:02 +000010376 bool Valid = false;
10377
Richard Smith36f5cfe2012-03-09 08:00:36 +000010378 // This might be the definition of a literal operator template.
10379 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10380 // This might be a specialization of a literal operator template.
10381 if (!TpDecl)
10382 TpDecl = FnDecl->getPrimaryTemplate();
10383
Sean Hunt216c2782010-04-07 23:11:06 +000010384 // template <char...> type operator "" name() is the only valid template
10385 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010386 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010387 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010388 // Must have only one template parameter
10389 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10390 if (Params->size() == 1) {
10391 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010392 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010393
Sean Hunt216c2782010-04-07 23:11:06 +000010394 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010395 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10396 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10397 Valid = true;
10398 }
10399 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010400 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010401 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010402 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10403
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010404 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010405
Sean Hunt30019c02010-04-07 22:57:35 +000010406 // unsigned long long int, long double, and any character type are allowed
10407 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010408 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10409 Context.hasSameType(T, Context.LongDoubleTy) ||
10410 Context.hasSameType(T, Context.CharTy) ||
10411 Context.hasSameType(T, Context.WCharTy) ||
10412 Context.hasSameType(T, Context.Char16Ty) ||
10413 Context.hasSameType(T, Context.Char32Ty)) {
10414 if (++Param == FnDecl->param_end())
10415 Valid = true;
10416 goto FinishedParams;
10417 }
10418
Sean Hunt30019c02010-04-07 22:57:35 +000010419 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010420 const PointerType *PT = T->getAs<PointerType>();
10421 if (!PT)
10422 goto FinishedParams;
10423 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010424 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010425 goto FinishedParams;
10426 T = T.getUnqualifiedType();
10427
10428 // Move on to the second parameter;
10429 ++Param;
10430
10431 // If there is no second parameter, the first must be a const char *
10432 if (Param == FnDecl->param_end()) {
10433 if (Context.hasSameType(T, Context.CharTy))
10434 Valid = true;
10435 goto FinishedParams;
10436 }
10437
10438 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10439 // are allowed as the first parameter to a two-parameter function
10440 if (!(Context.hasSameType(T, Context.CharTy) ||
10441 Context.hasSameType(T, Context.WCharTy) ||
10442 Context.hasSameType(T, Context.Char16Ty) ||
10443 Context.hasSameType(T, Context.Char32Ty)))
10444 goto FinishedParams;
10445
10446 // The second and final parameter must be an std::size_t
10447 T = (*Param)->getType().getUnqualifiedType();
10448 if (Context.hasSameType(T, Context.getSizeType()) &&
10449 ++Param == FnDecl->param_end())
10450 Valid = true;
10451 }
10452
10453 // FIXME: This diagnostic is absolutely terrible.
10454FinishedParams:
10455 if (!Valid) {
10456 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10457 << FnDecl->getDeclName();
10458 return true;
10459 }
10460
Richard Smitha9e88b22012-03-09 08:16:22 +000010461 // A parameter-declaration-clause containing a default argument is not
10462 // equivalent to any of the permitted forms.
10463 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10464 ParamEnd = FnDecl->param_end();
10465 Param != ParamEnd; ++Param) {
10466 if ((*Param)->hasDefaultArg()) {
10467 Diag((*Param)->getDefaultArgRange().getBegin(),
10468 diag::err_literal_operator_default_argument)
10469 << (*Param)->getDefaultArgRange();
10470 break;
10471 }
10472 }
10473
Richard Smith2fb4ae32012-03-08 02:39:21 +000010474 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010475 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10476 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010477 // C++11 [usrlit.suffix]p1:
10478 // Literal suffix identifiers that do not start with an underscore
10479 // are reserved for future standardization.
10480 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010481 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010482
Sean Hunta6c058d2010-01-13 09:01:02 +000010483 return false;
10484}
10485
Douglas Gregor074149e2009-01-05 19:45:36 +000010486/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10487/// linkage specification, including the language and (if present)
10488/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10489/// the location of the language string literal, which is provided
10490/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10491/// the '{' brace. Otherwise, this linkage specification does not
10492/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010493Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10494 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010495 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010496 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010497 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010498 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010499 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010500 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010501 Language = LinkageSpecDecl::lang_cxx;
10502 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010503 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010504 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010505 }
Mike Stump1eb44332009-09-09 15:08:12 +000010506
Chris Lattnercc98eac2008-12-17 07:13:27 +000010507 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010508
Douglas Gregor074149e2009-01-05 19:45:36 +000010509 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010510 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010511 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010512 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010513 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010514}
10515
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010516/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010517/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10518/// valid, it's the position of the closing '}' brace in a linkage
10519/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010520Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010521 Decl *LinkageSpec,
10522 SourceLocation RBraceLoc) {
10523 if (LinkageSpec) {
10524 if (RBraceLoc.isValid()) {
10525 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10526 LSDecl->setRBraceLoc(RBraceLoc);
10527 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010528 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010529 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010530 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010531}
10532
Michael Han684aa732013-02-22 17:15:32 +000010533Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10534 AttributeList *AttrList,
10535 SourceLocation SemiLoc) {
10536 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10537 // Attribute declarations appertain to empty declaration so we handle
10538 // them here.
10539 if (AttrList)
10540 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010541
Michael Han684aa732013-02-22 17:15:32 +000010542 CurContext->addDecl(ED);
10543 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010544}
10545
Douglas Gregord308e622009-05-18 20:51:54 +000010546/// \brief Perform semantic analysis for the variable declaration that
10547/// occurs within a C++ catch clause, returning the newly-created
10548/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010549VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010550 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010551 SourceLocation StartLoc,
10552 SourceLocation Loc,
10553 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010554 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010555 QualType ExDeclType = TInfo->getType();
10556
Sebastian Redl4b07b292008-12-22 19:15:10 +000010557 // Arrays and functions decay.
10558 if (ExDeclType->isArrayType())
10559 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10560 else if (ExDeclType->isFunctionType())
10561 ExDeclType = Context.getPointerType(ExDeclType);
10562
10563 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10564 // The exception-declaration shall not denote a pointer or reference to an
10565 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010566 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010567 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010568 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010569 Invalid = true;
10570 }
Douglas Gregord308e622009-05-18 20:51:54 +000010571
Sebastian Redl4b07b292008-12-22 19:15:10 +000010572 QualType BaseType = ExDeclType;
10573 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010574 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010575 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010576 BaseType = Ptr->getPointeeType();
10577 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010578 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010579 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010580 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010581 BaseType = Ref->getPointeeType();
10582 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010583 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010584 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010585 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010586 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010587 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010588
Mike Stump1eb44332009-09-09 15:08:12 +000010589 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010590 RequireNonAbstractType(Loc, ExDeclType,
10591 diag::err_abstract_type_in_decl,
10592 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010593 Invalid = true;
10594
John McCall5a180392010-07-24 00:37:23 +000010595 // Only the non-fragile NeXT runtime currently supports C++ catches
10596 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010597 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010598 QualType T = ExDeclType;
10599 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10600 T = RT->getPointeeType();
10601
10602 if (T->isObjCObjectType()) {
10603 Diag(Loc, diag::err_objc_object_catch);
10604 Invalid = true;
10605 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010606 // FIXME: should this be a test for macosx-fragile specifically?
10607 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010608 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010609 }
10610 }
10611
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010612 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010613 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010614 ExDecl->setExceptionVariable(true);
10615
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010616 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010617 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010618 Invalid = true;
10619
Douglas Gregorc41b8782011-07-06 18:14:43 +000010620 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010621 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010622 // Insulate this from anything else we might currently be parsing.
10623 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10624
Douglas Gregor6d182892010-03-05 23:38:39 +000010625 // C++ [except.handle]p16:
10626 // The object declared in an exception-declaration or, if the
10627 // exception-declaration does not specify a name, a temporary (12.2) is
10628 // copy-initialized (8.5) from the exception object. [...]
10629 // The object is destroyed when the handler exits, after the destruction
10630 // of any automatic objects initialized within the handler.
10631 //
10632 // We just pretend to initialize the object with itself, then make sure
10633 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010634 QualType initType = ExDeclType;
10635
10636 InitializedEntity entity =
10637 InitializedEntity::InitializeVariable(ExDecl);
10638 InitializationKind initKind =
10639 InitializationKind::CreateCopy(Loc, SourceLocation());
10640
10641 Expr *opaqueValue =
10642 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10643 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10644 ExprResult result = sequence.Perform(*this, entity, initKind,
10645 MultiExprArg(&opaqueValue, 1));
10646 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010647 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010648 else {
10649 // If the constructor used was non-trivial, set this as the
10650 // "initializer".
10651 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10652 if (!construct->getConstructor()->isTrivial()) {
10653 Expr *init = MaybeCreateExprWithCleanups(construct);
10654 ExDecl->setInit(init);
10655 }
10656
10657 // And make sure it's destructable.
10658 FinalizeVarWithDestructor(ExDecl, recordType);
10659 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010660 }
10661 }
10662
Douglas Gregord308e622009-05-18 20:51:54 +000010663 if (Invalid)
10664 ExDecl->setInvalidDecl();
10665
10666 return ExDecl;
10667}
10668
10669/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10670/// handler.
John McCalld226f652010-08-21 09:40:31 +000010671Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010672 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010673 bool Invalid = D.isInvalidType();
10674
10675 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010676 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10677 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010678 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10679 D.getIdentifierLoc());
10680 Invalid = true;
10681 }
10682
Sebastian Redl4b07b292008-12-22 19:15:10 +000010683 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010684 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010685 LookupOrdinaryName,
10686 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010687 // The scope should be freshly made just for us. There is just no way
10688 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010689 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010690 if (PrevDecl->isTemplateParameter()) {
10691 // Maybe we will complain about the shadowed template parameter.
10692 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010693 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010694 }
10695 }
10696
Chris Lattnereaaebc72009-04-25 08:06:05 +000010697 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010698 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10699 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010700 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010701 }
10702
Douglas Gregor83cb9422010-09-09 17:09:21 +000010703 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010704 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010705 D.getIdentifierLoc(),
10706 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010707 if (Invalid)
10708 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010709
Sebastian Redl4b07b292008-12-22 19:15:10 +000010710 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010711 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010712 PushOnScopeChains(ExDecl, S);
10713 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010714 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010715
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010716 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010717 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010718}
Anders Carlssonfb311762009-03-14 00:25:26 +000010719
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010720Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010721 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010722 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010723 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010724 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010725
Richard Smithe3f470a2012-07-11 22:37:56 +000010726 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10727 return 0;
10728
10729 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10730 AssertMessage, RParenLoc, false);
10731}
10732
10733Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10734 Expr *AssertExpr,
10735 StringLiteral *AssertMessage,
10736 SourceLocation RParenLoc,
10737 bool Failed) {
10738 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10739 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010740 // In a static_assert-declaration, the constant-expression shall be a
10741 // constant expression that can be contextually converted to bool.
10742 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10743 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010744 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010745
Richard Smithdaaefc52011-12-14 23:32:26 +000010746 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010747 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010748 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010749 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010750 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010751
Richard Smithe3f470a2012-07-11 22:37:56 +000010752 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010753 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010754 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010755 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010756 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010757 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010758 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010759 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010760 }
Mike Stump1eb44332009-09-09 15:08:12 +000010761
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010762 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010763 AssertExpr, AssertMessage, RParenLoc,
10764 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010765
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010766 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010767 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010768}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010769
Douglas Gregor1d869352010-04-07 16:53:43 +000010770/// \brief Perform semantic analysis of the given friend type declaration.
10771///
10772/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010773FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010774 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010775 TypeSourceInfo *TSInfo) {
10776 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10777
10778 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010779 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010780
Richard Smith6b130222011-10-18 21:39:00 +000010781 // C++03 [class.friend]p2:
10782 // An elaborated-type-specifier shall be used in a friend declaration
10783 // for a class.*
10784 //
10785 // * The class-key of the elaborated-type-specifier is required.
10786 if (!ActiveTemplateInstantiations.empty()) {
10787 // Do not complain about the form of friend template types during
10788 // template instantiation; we will already have complained when the
10789 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010790 } else {
10791 if (!T->isElaboratedTypeSpecifier()) {
10792 // If we evaluated the type to a record type, suggest putting
10793 // a tag in front.
10794 if (const RecordType *RT = T->getAs<RecordType>()) {
10795 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010796
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010797 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010798
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010799 Diag(TypeRange.getBegin(),
10800 getLangOpts().CPlusPlus11 ?
10801 diag::warn_cxx98_compat_unelaborated_friend_type :
10802 diag::ext_unelaborated_friend_type)
10803 << (unsigned) RD->getTagKind()
10804 << T
10805 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10806 InsertionText);
10807 } else {
10808 Diag(FriendLoc,
10809 getLangOpts().CPlusPlus11 ?
10810 diag::warn_cxx98_compat_nonclass_type_friend :
10811 diag::ext_nonclass_type_friend)
10812 << T
10813 << TypeRange;
10814 }
10815 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010816 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010817 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010818 diag::warn_cxx98_compat_enum_friend :
10819 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010820 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010821 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010822 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010823
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010824 // C++11 [class.friend]p3:
10825 // A friend declaration that does not declare a function shall have one
10826 // of the following forms:
10827 // friend elaborated-type-specifier ;
10828 // friend simple-type-specifier ;
10829 // friend typename-specifier ;
10830 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10831 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10832 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010833
Douglas Gregor06245bf2010-04-07 17:57:12 +000010834 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010835 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010836 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010837 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010838}
10839
John McCall9a34edb2010-10-19 01:40:49 +000010840/// Handle a friend tag declaration where the scope specifier was
10841/// templated.
10842Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10843 unsigned TagSpec, SourceLocation TagLoc,
10844 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010845 IdentifierInfo *Name,
10846 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010847 AttributeList *Attr,
10848 MultiTemplateParamsArg TempParamLists) {
10849 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10850
10851 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010852 bool Invalid = false;
10853
10854 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010855 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010856 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010857 TempParamLists.size(),
10858 /*friend*/ true,
10859 isExplicitSpecialization,
10860 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010861 if (TemplateParams->size() > 0) {
10862 // This is a declaration of a class template.
10863 if (Invalid)
10864 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010865
Eric Christopher4110e132011-07-21 05:34:24 +000010866 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10867 SS, Name, NameLoc, Attr,
10868 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010869 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010870 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010871 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010872 } else {
10873 // The "template<>" header is extraneous.
10874 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10875 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10876 isExplicitSpecialization = true;
10877 }
10878 }
10879
10880 if (Invalid) return 0;
10881
John McCall9a34edb2010-10-19 01:40:49 +000010882 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010883 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010884 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010885 isAllExplicitSpecializations = false;
10886 break;
10887 }
10888 }
10889
10890 // FIXME: don't ignore attributes.
10891
10892 // If it's explicit specializations all the way down, just forget
10893 // about the template header and build an appropriate non-templated
10894 // friend. TODO: for source fidelity, remember the headers.
10895 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010896 if (SS.isEmpty()) {
10897 bool Owned = false;
10898 bool IsDependent = false;
10899 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10900 Attr, AS_public,
10901 /*ModulePrivateLoc=*/SourceLocation(),
10902 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010903 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010904 /*ScopedEnumUsesClassTag=*/false,
10905 /*UnderlyingType=*/TypeResult());
10906 }
10907
Douglas Gregor2494dd02011-03-01 01:34:45 +000010908 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010909 ElaboratedTypeKeyword Keyword
10910 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010911 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010912 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010913 if (T.isNull())
10914 return 0;
10915
10916 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10917 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010918 DependentNameTypeLoc TL =
10919 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010920 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010921 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010922 TL.setNameLoc(NameLoc);
10923 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010924 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010925 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010926 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010927 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010928 }
10929
10930 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010931 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010932 Friend->setAccess(AS_public);
10933 CurContext->addDecl(Friend);
10934 return Friend;
10935 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010936
10937 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10938
10939
John McCall9a34edb2010-10-19 01:40:49 +000010940
10941 // Handle the case of a templated-scope friend class. e.g.
10942 // template <class T> class A<T>::B;
10943 // FIXME: we don't support these right now.
10944 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10945 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10946 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000010947 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010948 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010949 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010950 TL.setNameLoc(NameLoc);
10951
10952 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010953 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010954 Friend->setAccess(AS_public);
10955 Friend->setUnsupportedFriend(true);
10956 CurContext->addDecl(Friend);
10957 return Friend;
10958}
10959
10960
John McCalldd4a3b02009-09-16 22:47:08 +000010961/// Handle a friend type declaration. This works in tandem with
10962/// ActOnTag.
10963///
10964/// Notes on friend class templates:
10965///
10966/// We generally treat friend class declarations as if they were
10967/// declaring a class. So, for example, the elaborated type specifier
10968/// in a friend declaration is required to obey the restrictions of a
10969/// class-head (i.e. no typedefs in the scope chain), template
10970/// parameters are required to match up with simple template-ids, &c.
10971/// However, unlike when declaring a template specialization, it's
10972/// okay to refer to a template specialization without an empty
10973/// template parameter declaration, e.g.
10974/// friend class A<T>::B<unsigned>;
10975/// We permit this as a special case; if there are any template
10976/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010977/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010978Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010979 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010980 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010981
10982 assert(DS.isFriendSpecified());
10983 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10984
John McCalldd4a3b02009-09-16 22:47:08 +000010985 // Try to convert the decl specifier to a type. This works for
10986 // friend templates because ActOnTag never produces a ClassTemplateDecl
10987 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010988 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010989 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10990 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010991 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010992 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010993
Douglas Gregor6ccab972010-12-16 01:14:37 +000010994 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10995 return 0;
10996
John McCalldd4a3b02009-09-16 22:47:08 +000010997 // This is definitely an error in C++98. It's probably meant to
10998 // be forbidden in C++0x, too, but the specification is just
10999 // poorly written.
11000 //
11001 // The problem is with declarations like the following:
11002 // template <T> friend A<T>::foo;
11003 // where deciding whether a class C is a friend or not now hinges
11004 // on whether there exists an instantiation of A that causes
11005 // 'foo' to equal C. There are restrictions on class-heads
11006 // (which we declare (by fiat) elaborated friend declarations to
11007 // be) that makes this tractable.
11008 //
11009 // FIXME: handle "template <> friend class A<T>;", which
11010 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011011 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011012 Diag(Loc, diag::err_tagless_friend_type_template)
11013 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011014 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011015 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011016
John McCall02cace72009-08-28 07:59:38 +000011017 // C++98 [class.friend]p1: A friend of a class is a function
11018 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011019 // This is fixed in DR77, which just barely didn't make the C++03
11020 // deadline. It's also a very silly restriction that seriously
11021 // affects inner classes and which nobody else seems to implement;
11022 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011023 //
11024 // But note that we could warn about it: it's always useless to
11025 // friend one of your own members (it's not, however, worthless to
11026 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011027
John McCalldd4a3b02009-09-16 22:47:08 +000011028 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011029 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011030 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011031 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011032 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011033 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011034 DS.getFriendSpecLoc());
11035 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011036 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011037
11038 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011039 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011040
John McCalldd4a3b02009-09-16 22:47:08 +000011041 D->setAccess(AS_public);
11042 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011043
John McCalld226f652010-08-21 09:40:31 +000011044 return D;
John McCall02cace72009-08-28 07:59:38 +000011045}
11046
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011047NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11048 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011049 const DeclSpec &DS = D.getDeclSpec();
11050
11051 assert(DS.isFriendSpecified());
11052 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11053
11054 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011055 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011056
11057 // C++ [class.friend]p1
11058 // A friend of a class is a function or class....
11059 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011060 // It *doesn't* see through dependent types, which is correct
11061 // according to [temp.arg.type]p3:
11062 // If a declaration acquires a function type through a
11063 // type dependent on a template-parameter and this causes
11064 // a declaration that does not use the syntactic form of a
11065 // function declarator to have a function type, the program
11066 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011067 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011068 Diag(Loc, diag::err_unexpected_friend);
11069
11070 // It might be worthwhile to try to recover by creating an
11071 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011072 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011073 }
11074
11075 // C++ [namespace.memdef]p3
11076 // - If a friend declaration in a non-local class first declares a
11077 // class or function, the friend class or function is a member
11078 // of the innermost enclosing namespace.
11079 // - The name of the friend is not found by simple name lookup
11080 // until a matching declaration is provided in that namespace
11081 // scope (either before or after the class declaration granting
11082 // friendship).
11083 // - If a friend function is called, its name may be found by the
11084 // name lookup that considers functions from namespaces and
11085 // classes associated with the types of the function arguments.
11086 // - When looking for a prior declaration of a class or a function
11087 // declared as a friend, scopes outside the innermost enclosing
11088 // namespace scope are not considered.
11089
John McCall337ec3d2010-10-12 23:13:28 +000011090 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011091 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11092 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011093 assert(Name);
11094
Douglas Gregor6ccab972010-12-16 01:14:37 +000011095 // Check for unexpanded parameter packs.
11096 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11097 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11098 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11099 return 0;
11100
John McCall67d1a672009-08-06 02:15:43 +000011101 // The context we found the declaration in, or in which we should
11102 // create the declaration.
11103 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011104 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011105 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011106 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011107
John McCall337ec3d2010-10-12 23:13:28 +000011108 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000011109
John McCall337ec3d2010-10-12 23:13:28 +000011110 // There are four cases here.
11111 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000011112 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000011113 // there as appropriate.
11114 // Recover from invalid scope qualifiers as if they just weren't there.
11115 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000011116 // C++0x [namespace.memdef]p3:
11117 // If the name in a friend declaration is neither qualified nor
11118 // a template-id and the declaration is a function or an
11119 // elaborated-type-specifier, the lookup to determine whether
11120 // the entity has been previously declared shall not consider
11121 // any scopes outside the innermost enclosing namespace.
11122 // C++0x [class.friend]p11:
11123 // If a friend declaration appears in a local class and the name
11124 // specified is an unqualified name, a prior declaration is
11125 // looked up without considering scopes that are outside the
11126 // innermost enclosing non-class scope. For a friend function
11127 // declaration, if there is no prior declaration, the program is
11128 // ill-formed.
11129 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000011130 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011131
John McCall29ae6e52010-10-13 05:45:15 +000011132 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011133 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011134
Rafael Espindola11dc6342013-04-25 20:12:36 +000011135 // Skip class contexts. If someone can cite chapter and verse
11136 // for this behavior, that would be nice --- it's what GCC and
11137 // EDG do, and it seems like a reasonable intent, but the spec
11138 // really only says that checks for unqualified existing
11139 // declarations should stop at the nearest enclosing namespace,
11140 // not that they should only consider the nearest enclosing
11141 // namespace.
11142 while (DC->isRecord())
11143 DC = DC->getParent();
11144
11145 DeclContext *LookupDC = DC;
11146 while (LookupDC->isTransparentContext())
11147 LookupDC = LookupDC->getParent();
11148
11149 while (true) {
11150 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011151
11152 // TODO: decide what we think about using declarations.
Rafael Espindola11dc6342013-04-25 20:12:36 +000011153 if (isLocal)
John McCall67d1a672009-08-06 02:15:43 +000011154 break;
John McCall29ae6e52010-10-13 05:45:15 +000011155
Rafael Espindola11dc6342013-04-25 20:12:36 +000011156 if (!Previous.empty()) {
11157 DC = LookupDC;
11158 break;
John McCall8a407372010-10-14 22:22:28 +000011159 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011160
11161 if (isTemplateId) {
11162 if (isa<TranslationUnitDecl>(LookupDC)) break;
11163 } else {
11164 if (LookupDC->isFileContext()) break;
11165 }
11166 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011167 }
11168
John McCall380aaa42010-10-13 06:22:15 +000011169 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011170
Douglas Gregor883af832011-10-10 01:11:59 +000011171 // C++ [class.friend]p6:
11172 // A function can be defined in a friend declaration of a class if and
11173 // only if the class is a non-local class (9.8), the function name is
11174 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011175 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011176 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11177 }
11178
John McCall337ec3d2010-10-12 23:13:28 +000011179 // - There's a non-dependent scope specifier, in which case we
11180 // compute it and do a previous lookup there for a function
11181 // or function template.
11182 } else if (!SS.getScopeRep()->isDependent()) {
11183 DC = computeDeclContext(SS);
11184 if (!DC) return 0;
11185
11186 if (RequireCompleteDeclContext(SS, DC)) return 0;
11187
11188 LookupQualifiedName(Previous, DC);
11189
11190 // Ignore things found implicitly in the wrong scope.
11191 // TODO: better diagnostics for this case. Suggesting the right
11192 // qualified scope would be nice...
11193 LookupResult::Filter F = Previous.makeFilter();
11194 while (F.hasNext()) {
11195 NamedDecl *D = F.next();
11196 if (!DC->InEnclosingNamespaceSetOf(
11197 D->getDeclContext()->getRedeclContext()))
11198 F.erase();
11199 }
11200 F.done();
11201
11202 if (Previous.empty()) {
11203 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011204 Diag(Loc, diag::err_qualified_friend_not_found)
11205 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011206 return 0;
11207 }
11208
11209 // C++ [class.friend]p1: A friend of a class is a function or
11210 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011211 if (DC->Equals(CurContext))
11212 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011213 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011214 diag::warn_cxx98_compat_friend_is_member :
11215 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011216
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011217 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011218 // C++ [class.friend]p6:
11219 // A function can be defined in a friend declaration of a class if and
11220 // only if the class is a non-local class (9.8), the function name is
11221 // unqualified, and the function has namespace scope.
11222 SemaDiagnosticBuilder DB
11223 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11224
11225 DB << SS.getScopeRep();
11226 if (DC->isFileContext())
11227 DB << FixItHint::CreateRemoval(SS.getRange());
11228 SS.clear();
11229 }
John McCall337ec3d2010-10-12 23:13:28 +000011230
11231 // - There's a scope specifier that does not match any template
11232 // parameter lists, in which case we use some arbitrary context,
11233 // create a method or method template, and wait for instantiation.
11234 // - There's a scope specifier that does match some template
11235 // parameter lists, which we don't handle right now.
11236 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011237 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011238 // C++ [class.friend]p6:
11239 // A function can be defined in a friend declaration of a class if and
11240 // only if the class is a non-local class (9.8), the function name is
11241 // unqualified, and the function has namespace scope.
11242 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11243 << SS.getScopeRep();
11244 }
11245
John McCall337ec3d2010-10-12 23:13:28 +000011246 DC = CurContext;
11247 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011248 }
Douglas Gregor883af832011-10-10 01:11:59 +000011249
John McCall29ae6e52010-10-13 05:45:15 +000011250 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011251 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011252 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11253 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11254 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011255 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011256 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11257 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011258 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011259 }
John McCall67d1a672009-08-06 02:15:43 +000011260 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011261
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011262 // FIXME: This is an egregious hack to cope with cases where the scope stack
11263 // does not contain the declaration context, i.e., in an out-of-line
11264 // definition of a class.
11265 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11266 if (!DCScope) {
11267 FakeDCScope.setEntity(DC);
11268 DCScope = &FakeDCScope;
11269 }
11270
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011271 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011272 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011273 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011274 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011275
Douglas Gregor182ddf02009-09-28 00:08:27 +000011276 assert(ND->getDeclContext() == DC);
11277 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011278
John McCallab88d972009-08-31 22:39:49 +000011279 // Add the function declaration to the appropriate lookup tables,
11280 // adjusting the redeclarations list as necessary. We don't
11281 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011282 //
John McCallab88d972009-08-31 22:39:49 +000011283 // Also update the scope-based lookup if the target context's
11284 // lookup context is in lexical scope.
11285 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011286 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011287 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011288 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011289 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011290 }
John McCall02cace72009-08-28 07:59:38 +000011291
11292 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011293 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011294 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011295 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011296 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011297
John McCall1f2e1a92012-08-10 03:15:35 +000011298 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011299 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011300 } else {
11301 if (DC->isRecord()) CheckFriendAccess(ND);
11302
John McCall6102ca12010-10-16 06:59:13 +000011303 FunctionDecl *FD;
11304 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11305 FD = FTD->getTemplatedDecl();
11306 else
11307 FD = cast<FunctionDecl>(ND);
11308
11309 // Mark templated-scope function declarations as unsupported.
11310 if (FD->getNumTemplateParameterLists())
11311 FrD->setUnsupportedFriend(true);
11312 }
John McCall337ec3d2010-10-12 23:13:28 +000011313
John McCalld226f652010-08-21 09:40:31 +000011314 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011315}
11316
John McCalld226f652010-08-21 09:40:31 +000011317void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11318 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011319
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011320 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011321 if (!Fn) {
11322 Diag(DelLoc, diag::err_deleted_non_function);
11323 return;
11324 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011325
Douglas Gregoref96ee02012-01-14 16:38:05 +000011326 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011327 // Don't consider the implicit declaration we generate for explicit
11328 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011329 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11330 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011331 Diag(DelLoc, diag::err_deleted_decl_not_first);
11332 Diag(Prev->getLocation(), diag::note_previous_declaration);
11333 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011334 // If the declaration wasn't the first, we delete the function anyway for
11335 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011336 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011337 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011338
11339 if (Fn->isDeleted())
11340 return;
11341
11342 // See if we're deleting a function which is already known to override a
11343 // non-deleted virtual function.
11344 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11345 bool IssuedDiagnostic = false;
11346 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11347 E = MD->end_overridden_methods();
11348 I != E; ++I) {
11349 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11350 if (!IssuedDiagnostic) {
11351 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11352 IssuedDiagnostic = true;
11353 }
11354 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11355 }
11356 }
11357 }
11358
Sean Hunt10620eb2011-05-06 20:44:56 +000011359 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011360}
Sebastian Redl13e88542009-04-27 21:33:24 +000011361
Sean Hunte4246a62011-05-12 06:15:49 +000011362void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011363 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011364
11365 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011366 if (MD->getParent()->isDependentType()) {
11367 MD->setDefaulted();
11368 MD->setExplicitlyDefaulted();
11369 return;
11370 }
11371
Sean Hunte4246a62011-05-12 06:15:49 +000011372 CXXSpecialMember Member = getSpecialMember(MD);
11373 if (Member == CXXInvalid) {
11374 Diag(DefaultLoc, diag::err_default_special_members);
11375 return;
11376 }
11377
11378 MD->setDefaulted();
11379 MD->setExplicitlyDefaulted();
11380
Sean Huntcd10dec2011-05-23 23:14:04 +000011381 // If this definition appears within the record, do the checking when
11382 // the record is complete.
11383 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011384 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011385 // Find the uninstantiated declaration that actually had the '= default'
11386 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011387 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011388
Richard Smith12fef492013-03-27 00:22:47 +000011389 // If the method was defaulted on its first declaration, we will have
11390 // already performed the checking in CheckCompletedCXXClass. Such a
11391 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011392 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011393 return;
11394
Richard Smithb9d0b762012-07-27 04:22:15 +000011395 CheckExplicitlyDefaultedSpecialMember(MD);
11396
Richard Smith1d28caf2012-12-11 01:14:52 +000011397 // The exception specification is needed because we are defining the
11398 // function.
11399 ResolveExceptionSpec(DefaultLoc,
11400 MD->getType()->castAs<FunctionProtoType>());
11401
Sean Hunte4246a62011-05-12 06:15:49 +000011402 switch (Member) {
11403 case CXXDefaultConstructor: {
11404 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011405 if (!CD->isInvalidDecl())
11406 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11407 break;
11408 }
11409
11410 case CXXCopyConstructor: {
11411 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011412 if (!CD->isInvalidDecl())
11413 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011414 break;
11415 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011416
Sean Hunt2b188082011-05-14 05:23:28 +000011417 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011418 if (!MD->isInvalidDecl())
11419 DefineImplicitCopyAssignment(DefaultLoc, MD);
11420 break;
11421 }
11422
Sean Huntcb45a0f2011-05-12 22:46:25 +000011423 case CXXDestructor: {
11424 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011425 if (!DD->isInvalidDecl())
11426 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011427 break;
11428 }
11429
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011430 case CXXMoveConstructor: {
11431 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011432 if (!CD->isInvalidDecl())
11433 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011434 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011435 }
Sean Hunt82713172011-05-25 23:16:36 +000011436
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011437 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011438 if (!MD->isInvalidDecl())
11439 DefineImplicitMoveAssignment(DefaultLoc, MD);
11440 break;
11441 }
11442
11443 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011444 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011445 }
11446 } else {
11447 Diag(DefaultLoc, diag::err_default_special_members);
11448 }
11449}
11450
Sebastian Redl13e88542009-04-27 21:33:24 +000011451static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011452 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011453 Stmt *SubStmt = *CI;
11454 if (!SubStmt)
11455 continue;
11456 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011457 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011458 diag::err_return_in_constructor_handler);
11459 if (!isa<Expr>(SubStmt))
11460 SearchForReturnInStmt(Self, SubStmt);
11461 }
11462}
11463
11464void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11465 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11466 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11467 SearchForReturnInStmt(*this, Handler);
11468 }
11469}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011470
David Blaikie299adab2013-01-18 23:03:15 +000011471bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011472 const CXXMethodDecl *Old) {
11473 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11474 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11475
11476 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11477
11478 // If the calling conventions match, everything is fine
11479 if (NewCC == OldCC)
11480 return false;
11481
11482 // If either of the calling conventions are set to "default", we need to pick
11483 // something more sensible based on the target. This supports code where the
11484 // one method explicitly sets thiscall, and another has no explicit calling
11485 // convention.
11486 CallingConv Default =
11487 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11488 if (NewCC == CC_Default)
11489 NewCC = Default;
11490 if (OldCC == CC_Default)
11491 OldCC = Default;
11492
11493 // If the calling conventions still don't match, then report the error
11494 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011495 Diag(New->getLocation(),
11496 diag::err_conflicting_overriding_cc_attributes)
11497 << New->getDeclName() << New->getType() << Old->getType();
11498 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11499 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011500 }
11501
11502 return false;
11503}
11504
Mike Stump1eb44332009-09-09 15:08:12 +000011505bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011506 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011507 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11508 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011509
Chandler Carruth73857792010-02-15 11:53:20 +000011510 if (Context.hasSameType(NewTy, OldTy) ||
11511 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011512 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011513
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011514 // Check if the return types are covariant
11515 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011516
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011517 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011518 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11519 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011520 NewClassTy = NewPT->getPointeeType();
11521 OldClassTy = OldPT->getPointeeType();
11522 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011523 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11524 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11525 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11526 NewClassTy = NewRT->getPointeeType();
11527 OldClassTy = OldRT->getPointeeType();
11528 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011529 }
11530 }
Mike Stump1eb44332009-09-09 15:08:12 +000011531
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011532 // The return types aren't either both pointers or references to a class type.
11533 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011534 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011535 diag::err_different_return_type_for_overriding_virtual_function)
11536 << New->getDeclName() << NewTy << OldTy;
11537 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011538
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011539 return true;
11540 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011541
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011542 // C++ [class.virtual]p6:
11543 // If the return type of D::f differs from the return type of B::f, the
11544 // class type in the return type of D::f shall be complete at the point of
11545 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011546 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11547 if (!RT->isBeingDefined() &&
11548 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011549 diag::err_covariant_return_incomplete,
11550 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011551 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011552 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011553
Douglas Gregora4923eb2009-11-16 21:35:15 +000011554 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011555 // Check if the new class derives from the old class.
11556 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11557 Diag(New->getLocation(),
11558 diag::err_covariant_return_not_derived)
11559 << New->getDeclName() << NewTy << OldTy;
11560 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11561 return true;
11562 }
Mike Stump1eb44332009-09-09 15:08:12 +000011563
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011564 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011565 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011566 diag::err_covariant_return_inaccessible_base,
11567 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11568 // FIXME: Should this point to the return type?
11569 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011570 // FIXME: this note won't trigger for delayed access control
11571 // diagnostics, and it's impossible to get an undelayed error
11572 // here from access control during the original parse because
11573 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011574 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11575 return true;
11576 }
11577 }
Mike Stump1eb44332009-09-09 15:08:12 +000011578
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011579 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011580 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011581 Diag(New->getLocation(),
11582 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011583 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011584 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11585 return true;
11586 };
Mike Stump1eb44332009-09-09 15:08:12 +000011587
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011588
11589 // The new class type must have the same or less qualifiers as the old type.
11590 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11591 Diag(New->getLocation(),
11592 diag::err_covariant_return_type_class_type_more_qualified)
11593 << New->getDeclName() << NewTy << OldTy;
11594 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11595 return true;
11596 };
Mike Stump1eb44332009-09-09 15:08:12 +000011597
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011598 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011599}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011600
Douglas Gregor4ba31362009-12-01 17:24:26 +000011601/// \brief Mark the given method pure.
11602///
11603/// \param Method the method to be marked pure.
11604///
11605/// \param InitRange the source range that covers the "0" initializer.
11606bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011607 SourceLocation EndLoc = InitRange.getEnd();
11608 if (EndLoc.isValid())
11609 Method->setRangeEnd(EndLoc);
11610
Douglas Gregor4ba31362009-12-01 17:24:26 +000011611 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11612 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011613 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011614 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011615
11616 if (!Method->isInvalidDecl())
11617 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11618 << Method->getDeclName() << InitRange;
11619 return true;
11620}
11621
Douglas Gregor552e2992012-02-21 02:22:07 +000011622/// \brief Determine whether the given declaration is a static data member.
11623static bool isStaticDataMember(Decl *D) {
11624 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11625 if (!Var)
11626 return false;
11627
11628 return Var->isStaticDataMember();
11629}
John McCall731ad842009-12-19 09:28:58 +000011630/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11631/// an initializer for the out-of-line declaration 'Dcl'. The scope
11632/// is a fresh scope pushed for just this purpose.
11633///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011634/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11635/// static data member of class X, names should be looked up in the scope of
11636/// class X.
John McCalld226f652010-08-21 09:40:31 +000011637void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011638 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011639 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011640
John McCall731ad842009-12-19 09:28:58 +000011641 // We should only get called for declarations with scope specifiers, like:
11642 // int foo::bar;
11643 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011644 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011645
11646 // If we are parsing the initializer for a static data member, push a
11647 // new expression evaluation context that is associated with this static
11648 // data member.
11649 if (isStaticDataMember(D))
11650 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011651}
11652
11653/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011654/// initializer for the out-of-line declaration 'D'.
11655void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011656 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011657 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011658
Douglas Gregor552e2992012-02-21 02:22:07 +000011659 if (isStaticDataMember(D))
11660 PopExpressionEvaluationContext();
11661
John McCall731ad842009-12-19 09:28:58 +000011662 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011663 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011664}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011665
11666/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11667/// C++ if/switch/while/for statement.
11668/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011669DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011670 // C++ 6.4p2:
11671 // The declarator shall not specify a function or an array.
11672 // The type-specifier-seq shall not contain typedef and shall not declare a
11673 // new class or enumeration.
11674 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11675 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011676
11677 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011678 if (!Dcl)
11679 return true;
11680
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011681 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11682 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011683 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011684 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011685 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011686
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011687 return Dcl;
11688}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011689
Douglas Gregordfe65432011-07-28 19:11:31 +000011690void Sema::LoadExternalVTableUses() {
11691 if (!ExternalSource)
11692 return;
11693
11694 SmallVector<ExternalVTableUse, 4> VTables;
11695 ExternalSource->ReadUsedVTables(VTables);
11696 SmallVector<VTableUse, 4> NewUses;
11697 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11698 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11699 = VTablesUsed.find(VTables[I].Record);
11700 // Even if a definition wasn't required before, it may be required now.
11701 if (Pos != VTablesUsed.end()) {
11702 if (!Pos->second && VTables[I].DefinitionRequired)
11703 Pos->second = true;
11704 continue;
11705 }
11706
11707 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11708 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11709 }
11710
11711 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11712}
11713
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011714void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11715 bool DefinitionRequired) {
11716 // Ignore any vtable uses in unevaluated operands or for classes that do
11717 // not have a vtable.
11718 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11719 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011720 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011721 return;
11722
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011723 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011724 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011725 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11726 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11727 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11728 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011729 // If we already had an entry, check to see if we are promoting this vtable
11730 // to required a definition. If so, we need to reappend to the VTableUses
11731 // list, since we may have already processed the first entry.
11732 if (DefinitionRequired && !Pos.first->second) {
11733 Pos.first->second = true;
11734 } else {
11735 // Otherwise, we can early exit.
11736 return;
11737 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011738 }
11739
11740 // Local classes need to have their virtual members marked
11741 // immediately. For all other classes, we mark their virtual members
11742 // at the end of the translation unit.
11743 if (Class->isLocalClass())
11744 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011745 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011746 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011747}
11748
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011749bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011750 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011751 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011752 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011753
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011754 // Note: The VTableUses vector could grow as a result of marking
11755 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011756 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011757 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011758 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011759 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011760 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011761 if (!Class)
11762 continue;
11763
11764 SourceLocation Loc = VTableUses[I].second;
11765
Richard Smithb9d0b762012-07-27 04:22:15 +000011766 bool DefineVTable = true;
11767
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011768 // If this class has a key function, but that key function is
11769 // defined in another translation unit, we don't need to emit the
11770 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011771 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011772 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011773 switch (KeyFunction->getTemplateSpecializationKind()) {
11774 case TSK_Undeclared:
11775 case TSK_ExplicitSpecialization:
11776 case TSK_ExplicitInstantiationDeclaration:
11777 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011778 DefineVTable = false;
11779 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011780
11781 case TSK_ExplicitInstantiationDefinition:
11782 case TSK_ImplicitInstantiation:
11783 // We will be instantiating the key function.
11784 break;
11785 }
11786 } else if (!KeyFunction) {
11787 // If we have a class with no key function that is the subject
11788 // of an explicit instantiation declaration, suppress the
11789 // vtable; it will live with the explicit instantiation
11790 // definition.
11791 bool IsExplicitInstantiationDeclaration
11792 = Class->getTemplateSpecializationKind()
11793 == TSK_ExplicitInstantiationDeclaration;
11794 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11795 REnd = Class->redecls_end();
11796 R != REnd; ++R) {
11797 TemplateSpecializationKind TSK
11798 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11799 if (TSK == TSK_ExplicitInstantiationDeclaration)
11800 IsExplicitInstantiationDeclaration = true;
11801 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11802 IsExplicitInstantiationDeclaration = false;
11803 break;
11804 }
11805 }
11806
11807 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011808 DefineVTable = false;
11809 }
11810
11811 // The exception specifications for all virtual members may be needed even
11812 // if we are not providing an authoritative form of the vtable in this TU.
11813 // We may choose to emit it available_externally anyway.
11814 if (!DefineVTable) {
11815 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11816 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011817 }
11818
11819 // Mark all of the virtual members of this class as referenced, so
11820 // that we can build a vtable. Then, tell the AST consumer that a
11821 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011822 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011823 MarkVirtualMembersReferenced(Loc, Class);
11824 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11825 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11826
11827 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola531db822013-03-07 02:00:27 +000011828 if (Class->hasExternalLinkage() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011829 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011830 const FunctionDecl *KeyFunctionDef = 0;
11831 if (!KeyFunction ||
11832 (KeyFunction->hasBody(KeyFunctionDef) &&
11833 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011834 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11835 TSK_ExplicitInstantiationDefinition
11836 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11837 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011838 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011839 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011840 VTableUses.clear();
11841
Douglas Gregor78844032011-04-22 22:25:37 +000011842 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011843}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011844
Richard Smithb9d0b762012-07-27 04:22:15 +000011845void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11846 const CXXRecordDecl *RD) {
11847 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11848 E = RD->method_end(); I != E; ++I)
11849 if ((*I)->isVirtual() && !(*I)->isPure())
11850 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11851}
11852
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011853void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11854 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011855 // Mark all functions which will appear in RD's vtable as used.
11856 CXXFinalOverriderMap FinalOverriders;
11857 RD->getFinalOverriders(FinalOverriders);
11858 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11859 E = FinalOverriders.end();
11860 I != E; ++I) {
11861 for (OverridingMethods::const_iterator OI = I->second.begin(),
11862 OE = I->second.end();
11863 OI != OE; ++OI) {
11864 assert(OI->second.size() > 0 && "no final overrider");
11865 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011866
Richard Smithff817f72012-07-07 06:59:51 +000011867 // C++ [basic.def.odr]p2:
11868 // [...] A virtual member function is used if it is not pure. [...]
11869 if (!Overrider->isPure())
11870 MarkFunctionReferenced(Loc, Overrider);
11871 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011872 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011873
11874 // Only classes that have virtual bases need a VTT.
11875 if (RD->getNumVBases() == 0)
11876 return;
11877
11878 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11879 e = RD->bases_end(); i != e; ++i) {
11880 const CXXRecordDecl *Base =
11881 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011882 if (Base->getNumVBases() == 0)
11883 continue;
11884 MarkVirtualMembersReferenced(Loc, Base);
11885 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011886}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011887
11888/// SetIvarInitializers - This routine builds initialization ASTs for the
11889/// Objective-C implementation whose ivars need be initialized.
11890void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011891 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011892 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011893 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011894 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011895 CollectIvarsToConstructOrDestruct(OID, ivars);
11896 if (ivars.empty())
11897 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011898 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011899 for (unsigned i = 0; i < ivars.size(); i++) {
11900 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011901 if (Field->isInvalidDecl())
11902 continue;
11903
Sean Huntcbb67482011-01-08 20:30:50 +000011904 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011905 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11906 InitializationKind InitKind =
11907 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11908
11909 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011910 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011911 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011912 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011913 // Note, MemberInit could actually come back empty if no initialization
11914 // is required (e.g., because it would call a trivial default constructor)
11915 if (!MemberInit.get() || MemberInit.isInvalid())
11916 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011917
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011918 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011919 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11920 SourceLocation(),
11921 MemberInit.takeAs<Expr>(),
11922 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011923 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011924
11925 // Be sure that the destructor is accessible and is marked as referenced.
11926 if (const RecordType *RecordTy
11927 = Context.getBaseElementType(Field->getType())
11928 ->getAs<RecordType>()) {
11929 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011930 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011931 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011932 CheckDestructorAccess(Field->getLocation(), Destructor,
11933 PDiag(diag::err_access_dtor_ivar)
11934 << Context.getBaseElementType(Field->getType()));
11935 }
11936 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011937 }
11938 ObjCImplementation->setIvarInitializers(Context,
11939 AllToInit.data(), AllToInit.size());
11940 }
11941}
Sean Huntfe57eef2011-05-04 05:57:24 +000011942
Sean Huntebcbe1d2011-05-04 23:29:54 +000011943static
11944void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11945 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11946 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11947 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11948 Sema &S) {
11949 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11950 CE = Current.end();
11951 if (Ctor->isInvalidDecl())
11952 return;
11953
Richard Smitha8eaf002012-08-23 06:16:52 +000011954 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11955
11956 // Target may not be determinable yet, for instance if this is a dependent
11957 // call in an uninstantiated template.
11958 if (Target) {
11959 const FunctionDecl *FNTarget = 0;
11960 (void)Target->hasBody(FNTarget);
11961 Target = const_cast<CXXConstructorDecl*>(
11962 cast_or_null<CXXConstructorDecl>(FNTarget));
11963 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011964
11965 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11966 // Avoid dereferencing a null pointer here.
11967 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11968
11969 if (!Current.insert(Canonical))
11970 return;
11971
11972 // We know that beyond here, we aren't chaining into a cycle.
11973 if (!Target || !Target->isDelegatingConstructor() ||
11974 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11975 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11976 Valid.insert(*CI);
11977 Current.clear();
11978 // We've hit a cycle.
11979 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11980 Current.count(TCanonical)) {
11981 // If we haven't diagnosed this cycle yet, do so now.
11982 if (!Invalid.count(TCanonical)) {
11983 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011984 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011985 << Ctor;
11986
Richard Smitha8eaf002012-08-23 06:16:52 +000011987 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011988 if (TCanonical != Canonical)
11989 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11990
11991 CXXConstructorDecl *C = Target;
11992 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011993 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011994 (void)C->getTargetConstructor()->hasBody(FNTarget);
11995 assert(FNTarget && "Ctor cycle through bodiless function");
11996
Richard Smitha8eaf002012-08-23 06:16:52 +000011997 C = const_cast<CXXConstructorDecl*>(
11998 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011999 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12000 }
12001 }
12002
12003 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12004 Invalid.insert(*CI);
12005 Current.clear();
12006 } else {
12007 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12008 }
12009}
12010
12011
Sean Huntfe57eef2011-05-04 05:57:24 +000012012void Sema::CheckDelegatingCtorCycles() {
12013 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12014
Sean Huntebcbe1d2011-05-04 23:29:54 +000012015 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12016 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000012017
Douglas Gregor0129b562011-07-27 21:57:17 +000012018 for (DelegatingCtorDeclsType::iterator
12019 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012020 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012021 I != E; ++I)
12022 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012023
12024 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
12025 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012026}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012027
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012028namespace {
12029 /// \brief AST visitor that finds references to the 'this' expression.
12030 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12031 Sema &S;
12032
12033 public:
12034 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12035
12036 bool VisitCXXThisExpr(CXXThisExpr *E) {
12037 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12038 << E->isImplicit();
12039 return false;
12040 }
12041 };
12042}
12043
12044bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12045 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12046 if (!TSInfo)
12047 return false;
12048
12049 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012050 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012051 if (!ProtoTL)
12052 return false;
12053
12054 // C++11 [expr.prim.general]p3:
12055 // [The expression this] shall not appear before the optional
12056 // cv-qualifier-seq and it shall not appear within the declaration of a
12057 // static member function (although its type and value category are defined
12058 // within a static member function as they are within a non-static member
12059 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012060 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012061 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012062 FindCXXThisExpr Finder(*this);
12063
12064 // If the return type came after the cv-qualifier-seq, check it now.
12065 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012066 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012067 return true;
12068
12069 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012070 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12071 return true;
12072
12073 return checkThisInStaticMemberFunctionAttributes(Method);
12074}
12075
12076bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12077 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12078 if (!TSInfo)
12079 return false;
12080
12081 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012082 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012083 if (!ProtoTL)
12084 return false;
12085
David Blaikie39e6ab42013-02-18 22:06:02 +000012086 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012087 FindCXXThisExpr Finder(*this);
12088
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012089 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012090 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012091 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012092 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012093 case EST_DynamicNone:
12094 case EST_MSAny:
12095 case EST_None:
12096 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012097
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012098 case EST_ComputedNoexcept:
12099 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12100 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012101
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012102 case EST_Dynamic:
12103 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012104 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012105 E != EEnd; ++E) {
12106 if (!Finder.TraverseType(*E))
12107 return true;
12108 }
12109 break;
12110 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012111
12112 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012113}
12114
12115bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12116 FindCXXThisExpr Finder(*this);
12117
12118 // Check attributes.
12119 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12120 A != AEnd; ++A) {
12121 // FIXME: This should be emitted by tblgen.
12122 Expr *Arg = 0;
12123 ArrayRef<Expr *> Args;
12124 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12125 Arg = G->getArg();
12126 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12127 Arg = G->getArg();
12128 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12129 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12130 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12131 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12132 else if (ExclusiveLockFunctionAttr *ELF
12133 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12134 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12135 else if (SharedLockFunctionAttr *SLF
12136 = dyn_cast<SharedLockFunctionAttr>(*A))
12137 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12138 else if (ExclusiveTrylockFunctionAttr *ETLF
12139 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12140 Arg = ETLF->getSuccessValue();
12141 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12142 } else if (SharedTrylockFunctionAttr *STLF
12143 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12144 Arg = STLF->getSuccessValue();
12145 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12146 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12147 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12148 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12149 Arg = LR->getArg();
12150 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12151 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12152 else if (ExclusiveLocksRequiredAttr *ELR
12153 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12154 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12155 else if (SharedLocksRequiredAttr *SLR
12156 = dyn_cast<SharedLocksRequiredAttr>(*A))
12157 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12158
12159 if (Arg && !Finder.TraverseStmt(Arg))
12160 return true;
12161
12162 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12163 if (!Finder.TraverseStmt(Args[I]))
12164 return true;
12165 }
12166 }
12167
12168 return false;
12169}
12170
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012171void
12172Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12173 ArrayRef<ParsedType> DynamicExceptions,
12174 ArrayRef<SourceRange> DynamicExceptionRanges,
12175 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012176 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012177 FunctionProtoType::ExtProtoInfo &EPI) {
12178 Exceptions.clear();
12179 EPI.ExceptionSpecType = EST;
12180 if (EST == EST_Dynamic) {
12181 Exceptions.reserve(DynamicExceptions.size());
12182 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12183 // FIXME: Preserve type source info.
12184 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12185
12186 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12187 collectUnexpandedParameterPacks(ET, Unexpanded);
12188 if (!Unexpanded.empty()) {
12189 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12190 UPPC_ExceptionType,
12191 Unexpanded);
12192 continue;
12193 }
12194
12195 // Check that the type is valid for an exception spec, and
12196 // drop it if not.
12197 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12198 Exceptions.push_back(ET);
12199 }
12200 EPI.NumExceptions = Exceptions.size();
12201 EPI.Exceptions = Exceptions.data();
12202 return;
12203 }
12204
12205 if (EST == EST_ComputedNoexcept) {
12206 // If an error occurred, there's no expression here.
12207 if (NoexceptExpr) {
12208 assert((NoexceptExpr->isTypeDependent() ||
12209 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12210 Context.BoolTy) &&
12211 "Parser should have made sure that the expression is boolean");
12212 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12213 EPI.ExceptionSpecType = EST_BasicNoexcept;
12214 return;
12215 }
12216
12217 if (!NoexceptExpr->isValueDependent())
12218 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012219 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012220 /*AllowFold*/ false).take();
12221 EPI.NoexceptExpr = NoexceptExpr;
12222 }
12223 return;
12224 }
12225}
12226
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012227/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12228Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12229 // Implicitly declared functions (e.g. copy constructors) are
12230 // __host__ __device__
12231 if (D->isImplicit())
12232 return CFT_HostDevice;
12233
12234 if (D->hasAttr<CUDAGlobalAttr>())
12235 return CFT_Global;
12236
12237 if (D->hasAttr<CUDADeviceAttr>()) {
12238 if (D->hasAttr<CUDAHostAttr>())
12239 return CFT_HostDevice;
12240 else
12241 return CFT_Device;
12242 }
12243
12244 return CFT_Host;
12245}
12246
12247bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12248 CUDAFunctionTarget CalleeTarget) {
12249 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12250 // Callable from the device only."
12251 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12252 return true;
12253
12254 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12255 // Callable from the host only."
12256 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12257 // Callable from the host only."
12258 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12259 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12260 return true;
12261
12262 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12263 return true;
12264
12265 return false;
12266}
John McCall76da55d2013-04-16 07:28:30 +000012267
12268/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12269///
12270MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12271 SourceLocation DeclStart,
12272 Declarator &D, Expr *BitWidth,
12273 InClassInitStyle InitStyle,
12274 AccessSpecifier AS,
12275 AttributeList *MSPropertyAttr) {
12276 IdentifierInfo *II = D.getIdentifier();
12277 if (!II) {
12278 Diag(DeclStart, diag::err_anonymous_property);
12279 return NULL;
12280 }
12281 SourceLocation Loc = D.getIdentifierLoc();
12282
12283 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12284 QualType T = TInfo->getType();
12285 if (getLangOpts().CPlusPlus) {
12286 CheckExtraCXXDefaultArguments(D);
12287
12288 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12289 UPPC_DataMemberType)) {
12290 D.setInvalidType();
12291 T = Context.IntTy;
12292 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12293 }
12294 }
12295
12296 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12297
12298 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12299 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12300 diag::err_invalid_thread)
12301 << DeclSpec::getSpecifierName(TSCS);
12302
12303 // Check to see if this name was declared as a member previously
12304 NamedDecl *PrevDecl = 0;
12305 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12306 LookupName(Previous, S);
12307 switch (Previous.getResultKind()) {
12308 case LookupResult::Found:
12309 case LookupResult::FoundUnresolvedValue:
12310 PrevDecl = Previous.getAsSingle<NamedDecl>();
12311 break;
12312
12313 case LookupResult::FoundOverloaded:
12314 PrevDecl = Previous.getRepresentativeDecl();
12315 break;
12316
12317 case LookupResult::NotFound:
12318 case LookupResult::NotFoundInCurrentInstantiation:
12319 case LookupResult::Ambiguous:
12320 break;
12321 }
12322
12323 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12324 // Maybe we will complain about the shadowed template parameter.
12325 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12326 // Just pretend that we didn't see the previous declaration.
12327 PrevDecl = 0;
12328 }
12329
12330 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12331 PrevDecl = 0;
12332
12333 SourceLocation TSSL = D.getLocStart();
12334 MSPropertyDecl *NewPD;
12335 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12336 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12337 II, T, TInfo, TSSL,
12338 Data.GetterId, Data.SetterId);
12339 ProcessDeclAttributes(TUScope, NewPD, D);
12340 NewPD->setAccess(AS);
12341
12342 if (NewPD->isInvalidDecl())
12343 Record->setInvalidDecl();
12344
12345 if (D.getDeclSpec().isModulePrivateSpecified())
12346 NewPD->setModulePrivate();
12347
12348 if (NewPD->isInvalidDecl() && PrevDecl) {
12349 // Don't introduce NewFD into scope; there's already something
12350 // with the same name in the same scope.
12351 } else if (II) {
12352 PushOnScopeChains(NewPD, S);
12353 } else
12354 Record->addDecl(NewPD);
12355
12356 return NewPD;
12357}