blob: 46010e4bdb78e9af3f92a60be5a032c977682d86 [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);
Chris Lattner9e979552008-04-12 23:52:44 +000068 };
Chris Lattner8123a952008-04-10 02:22:51 +000069
Chris Lattner9e979552008-04-12 23:52:44 +000070 /// VisitExpr - Visit all of the children of this expression.
71 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
72 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000073 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000074 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000075 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000076 }
77
Chris Lattner9e979552008-04-12 23:52:44 +000078 /// VisitDeclRefExpr - Visit a reference to a declaration, to
79 /// determine whether this declaration can be used in the default
80 /// argument expression.
81 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000082 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000083 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
84 // C++ [dcl.fct.default]p9
85 // Default arguments are evaluated each time the function is
86 // called. The order of evaluation of function arguments is
87 // unspecified. Consequently, parameters of a function shall not
88 // be used in default argument expressions, even if they are not
89 // evaluated. Parameters of a function declared before a default
90 // argument expression are in scope and can hide namespace and
91 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000092 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000093 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000094 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000095 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000096 // C++ [dcl.fct.default]p7
97 // Local variables shall not be used in default argument
98 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000099 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000100 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000101 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000102 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000103 }
Chris Lattner8123a952008-04-10 02:22:51 +0000104
Douglas Gregor3996f232008-11-04 13:41:56 +0000105 return false;
106 }
Chris Lattner9e979552008-04-12 23:52:44 +0000107
Douglas Gregor796da182008-11-04 14:32:21 +0000108 /// VisitCXXThisExpr - Visit a C++ "this" expression.
109 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
110 // C++ [dcl.fct.default]p8:
111 // The keyword this shall not be used in a default argument of a
112 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000113 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000114 diag::err_param_default_argument_references_this)
115 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000116 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000117
118 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
119 // C++11 [expr.lambda.prim]p13:
120 // A lambda-expression appearing in a default argument shall not
121 // implicitly or explicitly capture any entity.
122 if (Lambda->capture_begin() == Lambda->capture_end())
123 return false;
124
125 return S->Diag(Lambda->getLocStart(),
126 diag::err_lambda_capture_default_arg);
127 }
Chris Lattner8123a952008-04-10 02:22:51 +0000128}
129
Richard Smithe6975e92012-04-17 00:58:00 +0000130void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
131 CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000132 // If we have an MSAny spec already, don't bother.
133 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000134 return;
135
136 const FunctionProtoType *Proto
137 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000138 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
139 if (!Proto)
140 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000141
142 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
143
144 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000145 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000146 ClearExceptions();
147 ComputedEST = EST;
148 return;
149 }
150
Richard Smith7a614d82011-06-11 17:19:42 +0000151 // FIXME: If the call to this decl is using any of its default arguments, we
152 // need to search them for potentially-throwing calls.
153
Sean Hunt001cad92011-05-10 00:49:42 +0000154 // If this function has a basic noexcept, it doesn't affect the outcome.
155 if (EST == EST_BasicNoexcept)
156 return;
157
158 // If we have a throw-all spec at this point, ignore the function.
159 if (ComputedEST == EST_None)
160 return;
161
162 // If we're still at noexcept(true) and there's a nothrow() callee,
163 // change to that specification.
164 if (EST == EST_DynamicNone) {
165 if (ComputedEST == EST_BasicNoexcept)
166 ComputedEST = EST_DynamicNone;
167 return;
168 }
169
170 // Check out noexcept specs.
171 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000172 FunctionProtoType::NoexceptResult NR =
173 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000174 assert(NR != FunctionProtoType::NR_NoNoexcept &&
175 "Must have noexcept result for EST_ComputedNoexcept.");
176 assert(NR != FunctionProtoType::NR_Dependent &&
177 "Should not generate implicit declarations for dependent cases, "
178 "and don't know how to handle them anyway.");
179
180 // noexcept(false) -> no spec on the new function
181 if (NR == FunctionProtoType::NR_Throw) {
182 ClearExceptions();
183 ComputedEST = EST_None;
184 }
185 // noexcept(true) won't change anything either.
186 return;
187 }
188
189 assert(EST == EST_Dynamic && "EST case not considered earlier.");
190 assert(ComputedEST != EST_None &&
191 "Shouldn't collect exceptions when throw-all is guaranteed.");
192 ComputedEST = EST_Dynamic;
193 // Record the exceptions in this function's exception specification.
194 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
195 EEnd = Proto->exception_end();
196 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000197 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000198 Exceptions.push_back(*E);
199}
200
Richard Smith7a614d82011-06-11 17:19:42 +0000201void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000202 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000203 return;
204
205 // FIXME:
206 //
207 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000208 // [An] implicit exception-specification specifies the type-id T if and
209 // only if T is allowed by the exception-specification of a function directly
210 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000211 // function it directly invokes allows all exceptions, and f shall allow no
212 // exceptions if every function it directly invokes allows no exceptions.
213 //
214 // Note in particular that if an implicit exception-specification is generated
215 // for a function containing a throw-expression, that specification can still
216 // be noexcept(true).
217 //
218 // Note also that 'directly invoked' is not defined in the standard, and there
219 // is no indication that we should only consider potentially-evaluated calls.
220 //
221 // Ultimately we should implement the intent of the standard: the exception
222 // specification should be the set of exceptions which can be thrown by the
223 // implicit definition. For now, we assume that any non-nothrow expression can
224 // throw any exception.
225
Richard Smithe6975e92012-04-17 00:58:00 +0000226 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000227 ComputedEST = EST_None;
228}
229
Anders Carlssoned961f92009-08-25 02:29:20 +0000230bool
John McCall9ae2f072010-08-23 23:25:46 +0000231Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000232 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000233 if (RequireCompleteType(Param->getLocation(), Param->getType(),
234 diag::err_typecheck_decl_incomplete_type)) {
235 Param->setInvalidDecl();
236 return true;
237 }
238
Anders Carlssoned961f92009-08-25 02:29:20 +0000239 // C++ [dcl.fct.default]p5
240 // A default argument expression is implicitly converted (clause
241 // 4) to the parameter type. The default argument expression has
242 // the same semantic constraints as the initializer expression in
243 // a declaration of a variable of the parameter type, using the
244 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000245 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
246 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000247 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
248 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000249 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000250 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000251 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000252 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000253 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000254
Richard Smith6c3af3d2013-01-17 01:17:56 +0000255 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000256 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // Okay: add the default argument to the parameter
259 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000261 // We have already instantiated this parameter; provide each of the
262 // instantiations with the uninstantiated default argument.
263 UnparsedDefaultArgInstantiationsMap::iterator InstPos
264 = UnparsedDefaultArgInstantiations.find(Param);
265 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
266 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
267 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
268
269 // We're done tracking this parameter's instantiations.
270 UnparsedDefaultArgInstantiations.erase(InstPos);
271 }
272
Anders Carlsson9351c172009-08-25 03:18:48 +0000273 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000274}
275
Chris Lattner8123a952008-04-10 02:22:51 +0000276/// ActOnParamDefaultArgument - Check whether the default argument
277/// provided for a function parameter is well-formed. If so, attach it
278/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000279void
John McCalld226f652010-08-21 09:40:31 +0000280Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000281 Expr *DefaultArg) {
282 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000283 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000284
John McCalld226f652010-08-21 09:40:31 +0000285 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000286 UnparsedDefaultArgLocs.erase(Param);
287
Chris Lattner3d1cee32008-04-08 05:04:30 +0000288 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000289 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000290 Diag(EqualLoc, diag::err_param_default_argument)
291 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000292 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000293 return;
294 }
295
Douglas Gregor6f526752010-12-16 08:48:57 +0000296 // Check for unexpanded parameter packs.
297 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
298 Param->setInvalidDecl();
299 return;
300 }
301
Anders Carlsson66e30672009-08-25 01:02:06 +0000302 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000303 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
304 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000305 Param->setInvalidDecl();
306 return;
307 }
Mike Stump1eb44332009-09-09 15:08:12 +0000308
John McCall9ae2f072010-08-23 23:25:46 +0000309 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000310}
311
Douglas Gregor61366e92008-12-24 00:01:03 +0000312/// ActOnParamUnparsedDefaultArgument - We've seen a default
313/// argument for a function parameter, but we can't parse it yet
314/// because we're inside a class definition. Note that this default
315/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000316void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000317 SourceLocation EqualLoc,
318 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000319 if (!param)
320 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000321
John McCalld226f652010-08-21 09:40:31 +0000322 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000323 if (Param)
324 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Anders Carlsson5e300d12009-06-12 16:51:40 +0000326 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000327}
328
Douglas Gregor72b505b2008-12-16 21:30:33 +0000329/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
330/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000331void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000332 if (!param)
333 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000334
John McCalld226f652010-08-21 09:40:31 +0000335 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Anders Carlsson5e300d12009-06-12 16:51:40 +0000337 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Anders Carlsson5e300d12009-06-12 16:51:40 +0000339 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000340}
341
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000342/// CheckExtraCXXDefaultArguments - Check for any extra default
343/// arguments in the declarator, which is not a function declaration
344/// or definition and therefore is not permitted to have default
345/// arguments. This routine should be invoked for every declarator
346/// that is not a function declaration or definition.
347void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
348 // C++ [dcl.fct.default]p3
349 // A default argument expression shall be specified only in the
350 // parameter-declaration-clause of a function declaration or in a
351 // template-parameter (14.1). It shall not be specified for a
352 // parameter pack. If it is specified in a
353 // parameter-declaration-clause, it shall not occur within a
354 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000355 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000356 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000357 DeclaratorChunk &chunk = D.getTypeObject(i);
358 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000359 if (MightBeFunction) {
360 // This is a function declaration. It can have default arguments, but
361 // keep looking in case its return type is a function type with default
362 // arguments.
363 MightBeFunction = false;
364 continue;
365 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000366 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
367 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000368 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000369 if (Param->hasUnparsedDefaultArg()) {
370 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000371 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000372 << SourceRange((*Toks)[1].getLocation(),
373 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000374 delete Toks;
375 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000376 } else if (Param->getDefaultArg()) {
377 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
378 << Param->getDefaultArg()->getSourceRange();
379 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000380 }
381 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000382 } else if (chunk.Kind != DeclaratorChunk::Paren) {
383 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000384 }
385 }
386}
387
Craig Topper1a6eac82012-09-21 04:33:26 +0000388/// MergeCXXFunctionDecl - Merge two declarations of the same C++
389/// function, once we already know that they have the same
390/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
391/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000392bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
393 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000394 bool Invalid = false;
395
Chris Lattner3d1cee32008-04-08 05:04:30 +0000396 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 // For non-template functions, default arguments can be added in
398 // later declarations of a function in the same
399 // scope. Declarations in different scopes have completely
400 // distinct sets of default arguments. That is, declarations in
401 // inner scopes do not acquire default arguments from
402 // declarations in outer scopes, and vice versa. In a given
403 // function declaration, all parameters subsequent to a
404 // parameter with a default argument shall have default
405 // arguments supplied in this or previous declarations. A
406 // default argument shall not be redefined by a later
407 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000408 //
409 // C++ [dcl.fct.default]p6:
410 // Except for member functions of class templates, the default arguments
411 // in a member function definition that appears outside of the class
412 // definition are added to the set of default arguments provided by the
413 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000414 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
415 ParmVarDecl *OldParam = Old->getParamDecl(p);
416 ParmVarDecl *NewParam = New->getParamDecl(p);
417
James Molloy9cda03f2012-03-13 08:55:35 +0000418 bool OldParamHasDfl = OldParam->hasDefaultArg();
419 bool NewParamHasDfl = NewParam->hasDefaultArg();
420
421 NamedDecl *ND = Old;
422 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
423 // Ignore default parameters of old decl if they are not in
424 // the same scope.
425 OldParamHasDfl = false;
426
427 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000428
Francois Pichet8d051e02011-04-10 03:03:52 +0000429 unsigned DiagDefaultParamID =
430 diag::err_param_default_argument_redefinition;
431
432 // MSVC accepts that default parameters be redefined for member functions
433 // of template class. The new default parameter's value is ignored.
434 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000435 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000436 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
437 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000438 // Merge the old default argument into the new parameter.
439 NewParam->setHasInheritedDefaultArg();
440 if (OldParam->hasUninstantiatedDefaultArg())
441 NewParam->setUninstantiatedDefaultArg(
442 OldParam->getUninstantiatedDefaultArg());
443 else
444 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000445 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000446 Invalid = false;
447 }
448 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000449
Francois Pichet8cf90492011-04-10 04:58:30 +0000450 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
451 // hint here. Alternatively, we could walk the type-source information
452 // for NewParam to find the last source location in the type... but it
453 // isn't worth the effort right now. This is the kind of test case that
454 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000455 // int f(int);
456 // void g(int (*fp)(int) = f);
457 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000458 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000459 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000460
461 // Look for the function declaration where the default argument was
462 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000463 for (FunctionDecl *Older = Old->getPreviousDecl();
464 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000465 if (!Older->getParamDecl(p)->hasDefaultArg())
466 break;
467
468 OldParam = Older->getParamDecl(p);
469 }
470
471 Diag(OldParam->getLocation(), diag::note_previous_definition)
472 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000473 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000474 // Merge the old default argument into the new parameter.
475 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000476 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000477 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000478 if (OldParam->hasUninstantiatedDefaultArg())
479 NewParam->setUninstantiatedDefaultArg(
480 OldParam->getUninstantiatedDefaultArg());
481 else
John McCall3d6c1782010-05-04 01:53:42 +0000482 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000483 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000484 if (New->getDescribedFunctionTemplate()) {
485 // Paragraph 4, quoted above, only applies to non-template functions.
486 Diag(NewParam->getLocation(),
487 diag::err_param_default_argument_template_redecl)
488 << NewParam->getDefaultArgRange();
489 Diag(Old->getLocation(), diag::note_template_prev_declaration)
490 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000491 } else if (New->getTemplateSpecializationKind()
492 != TSK_ImplicitInstantiation &&
493 New->getTemplateSpecializationKind() != TSK_Undeclared) {
494 // C++ [temp.expr.spec]p21:
495 // Default function arguments shall not be specified in a declaration
496 // or a definition for one of the following explicit specializations:
497 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000498 // - the explicit specialization of a member function template;
499 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000500 // template where the class template specialization to which the
501 // member function specialization belongs is implicitly
502 // instantiated.
503 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
504 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
505 << New->getDeclName()
506 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000507 } else if (New->getDeclContext()->isDependentContext()) {
508 // C++ [dcl.fct.default]p6 (DR217):
509 // Default arguments for a member function of a class template shall
510 // be specified on the initial declaration of the member function
511 // within the class template.
512 //
513 // Reading the tea leaves a bit in DR217 and its reference to DR205
514 // leads me to the conclusion that one cannot add default function
515 // arguments for an out-of-line definition of a member function of a
516 // dependent type.
517 int WhichKind = 2;
518 if (CXXRecordDecl *Record
519 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
520 if (Record->getDescribedClassTemplate())
521 WhichKind = 0;
522 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
523 WhichKind = 1;
524 else
525 WhichKind = 2;
526 }
527
528 Diag(NewParam->getLocation(),
529 diag::err_param_default_argument_member_template_redecl)
530 << WhichKind
531 << NewParam->getDefaultArgRange();
532 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000533 }
534 }
535
Richard Smithb8abff62012-11-28 03:45:24 +0000536 // DR1344: If a default argument is added outside a class definition and that
537 // default argument makes the function a special member function, the program
538 // is ill-formed. This can only happen for constructors.
539 if (isa<CXXConstructorDecl>(New) &&
540 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
541 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
542 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
543 if (NewSM != OldSM) {
544 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
545 assert(NewParam->hasDefaultArg());
546 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
547 << NewParam->getDefaultArgRange() << NewSM;
548 Diag(Old->getLocation(), diag::note_previous_declaration);
549 }
550 }
551
Richard Smithff234882012-02-20 23:28:05 +0000552 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000553 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000554 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000555 if (New->isConstexpr() != Old->isConstexpr()) {
556 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
557 << New << New->isConstexpr();
558 Diag(Old->getLocation(), diag::note_previous_declaration);
559 Invalid = true;
560 }
561
Douglas Gregore13ad832010-02-12 07:32:17 +0000562 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000563 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000564
Douglas Gregorcda9c672009-02-16 17:45:42 +0000565 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000566}
567
Sebastian Redl60618fa2011-03-12 11:50:43 +0000568/// \brief Merge the exception specifications of two variable declarations.
569///
570/// This is called when there's a redeclaration of a VarDecl. The function
571/// checks if the redeclaration might have an exception specification and
572/// validates compatibility and merges the specs if necessary.
573void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
574 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000575 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000576 return;
577
578 assert(Context.hasSameType(New->getType(), Old->getType()) &&
579 "Should only be called if types are otherwise the same.");
580
581 QualType NewType = New->getType();
582 QualType OldType = Old->getType();
583
584 // We're only interested in pointers and references to functions, as well
585 // as pointers to member functions.
586 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
587 NewType = R->getPointeeType();
588 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
589 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
590 NewType = P->getPointeeType();
591 OldType = OldType->getAs<PointerType>()->getPointeeType();
592 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
593 NewType = M->getPointeeType();
594 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
595 }
596
597 if (!NewType->isFunctionProtoType())
598 return;
599
600 // There's lots of special cases for functions. For function pointers, system
601 // libraries are hopefully not as broken so that we don't need these
602 // workarounds.
603 if (CheckEquivalentExceptionSpec(
604 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
605 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
606 New->setInvalidDecl();
607 }
608}
609
Chris Lattner3d1cee32008-04-08 05:04:30 +0000610/// CheckCXXDefaultArguments - Verify that the default arguments for a
611/// function declaration are well-formed according to C++
612/// [dcl.fct.default].
613void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
614 unsigned NumParams = FD->getNumParams();
615 unsigned p;
616
Douglas Gregorc6889e72012-02-14 22:28:59 +0000617 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
618 isa<CXXMethodDecl>(FD) &&
619 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
620
Chris Lattner3d1cee32008-04-08 05:04:30 +0000621 // Find first parameter with a default argument
622 for (p = 0; p < NumParams; ++p) {
623 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000624 if (Param->hasDefaultArg()) {
625 // C++11 [expr.prim.lambda]p5:
626 // [...] Default arguments (8.3.6) shall not be specified in the
627 // parameter-declaration-clause of a lambda-declarator.
628 //
629 // FIXME: Core issue 974 strikes this sentence, we only provide an
630 // extension warning.
631 if (IsLambda)
632 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
633 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000634 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000635 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000636 }
637
638 // C++ [dcl.fct.default]p4:
639 // In a given function declaration, all parameters
640 // subsequent to a parameter with a default argument shall
641 // have default arguments supplied in this or previous
642 // declarations. A default argument shall not be redefined
643 // by a later declaration (not even to the same value).
644 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000645 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000646 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000647 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000648 if (Param->isInvalidDecl())
649 /* We already complained about this parameter. */;
650 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000651 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000652 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000653 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000654 else
Mike Stump1eb44332009-09-09 15:08:12 +0000655 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000656 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Chris Lattner3d1cee32008-04-08 05:04:30 +0000658 LastMissingDefaultArg = p;
659 }
660 }
661
662 if (LastMissingDefaultArg > 0) {
663 // Some default arguments were missing. Clear out all of the
664 // default arguments up to (and including) the last missing
665 // default argument, so that we leave the function parameters
666 // in a semantically valid state.
667 for (p = 0; p <= LastMissingDefaultArg; ++p) {
668 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000669 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000670 Param->setDefaultArg(0);
671 }
672 }
673 }
674}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000675
Richard Smith9f569cc2011-10-01 02:31:28 +0000676// CheckConstexprParameterTypes - Check whether a function's parameter types
677// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000678// diagnostic and return false.
679static bool CheckConstexprParameterTypes(Sema &SemaRef,
680 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000681 unsigned ArgIndex = 0;
682 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
683 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
684 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
685 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
686 SourceLocation ParamLoc = PD->getLocation();
687 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000688 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000689 diag::err_constexpr_non_literal_param,
690 ArgIndex+1, PD->getSourceRange(),
691 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000692 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000693 }
Joao Matos17d35c32012-08-31 22:18:20 +0000694 return true;
695}
696
697/// \brief Get diagnostic %select index for tag kind for
698/// record diagnostic message.
699/// WARNING: Indexes apply to particular diagnostics only!
700///
701/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000702static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000703 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000704 case TTK_Struct: return 0;
705 case TTK_Interface: return 1;
706 case TTK_Class: return 2;
707 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000708 }
Joao Matos17d35c32012-08-31 22:18:20 +0000709}
710
711// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
712// the requirements of a constexpr function definition or a constexpr
713// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000714// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000715//
Richard Smith86c3ae42012-02-13 03:54:03 +0000716// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
717bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000718 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
719 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000720 // C++11 [dcl.constexpr]p4:
721 // The definition of a constexpr constructor shall satisfy the following
722 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000723 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000724 const CXXRecordDecl *RD = MD->getParent();
725 if (RD->getNumVBases()) {
726 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
727 << isa<CXXConstructorDecl>(NewFD)
728 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
729 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
730 E = RD->vbases_end(); I != E; ++I)
731 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000732 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000733 return false;
734 }
Richard Smith35340502012-01-13 04:54:00 +0000735 }
736
737 if (!isa<CXXConstructorDecl>(NewFD)) {
738 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000739 // The definition of a constexpr function shall satisfy the following
740 // constraints:
741 // - it shall not be virtual;
742 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
743 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000744 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000745
Richard Smith86c3ae42012-02-13 03:54:03 +0000746 // If it's not obvious why this function is virtual, find an overridden
747 // function which uses the 'virtual' keyword.
748 const CXXMethodDecl *WrittenVirtual = Method;
749 while (!WrittenVirtual->isVirtualAsWritten())
750 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
751 if (WrittenVirtual != Method)
752 Diag(WrittenVirtual->getLocation(),
753 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000754 return false;
755 }
756
757 // - its return type shall be a literal type;
758 QualType RT = NewFD->getResultType();
759 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000760 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000761 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000762 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000763 }
764
Richard Smith35340502012-01-13 04:54:00 +0000765 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000766 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000767 return false;
768
Richard Smith9f569cc2011-10-01 02:31:28 +0000769 return true;
770}
771
772/// Check the given declaration statement is legal within a constexpr function
773/// body. C++0x [dcl.constexpr]p3,p4.
774///
775/// \return true if the body is OK, false if we have diagnosed a problem.
776static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
777 DeclStmt *DS) {
778 // C++0x [dcl.constexpr]p3 and p4:
779 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
780 // contain only
781 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
782 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
783 switch ((*DclIt)->getKind()) {
784 case Decl::StaticAssert:
785 case Decl::Using:
786 case Decl::UsingShadow:
787 case Decl::UsingDirective:
788 case Decl::UnresolvedUsingTypename:
789 // - static_assert-declarations
790 // - using-declarations,
791 // - using-directives,
792 continue;
793
794 case Decl::Typedef:
795 case Decl::TypeAlias: {
796 // - typedef declarations and alias-declarations that do not define
797 // classes or enumerations,
798 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
799 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
800 // Don't allow variably-modified types in constexpr functions.
801 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
802 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
803 << TL.getSourceRange() << TL.getType()
804 << isa<CXXConstructorDecl>(Dcl);
805 return false;
806 }
807 continue;
808 }
809
810 case Decl::Enum:
811 case Decl::CXXRecord:
812 // As an extension, we allow the declaration (but not the definition) of
813 // classes and enumerations in all declarations, not just in typedef and
814 // alias declarations.
815 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
816 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
817 << isa<CXXConstructorDecl>(Dcl);
818 return false;
819 }
820 continue;
821
822 case Decl::Var:
823 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
824 << isa<CXXConstructorDecl>(Dcl);
825 return false;
826
827 default:
828 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
829 << isa<CXXConstructorDecl>(Dcl);
830 return false;
831 }
832 }
833
834 return true;
835}
836
837/// Check that the given field is initialized within a constexpr constructor.
838///
839/// \param Dcl The constexpr constructor being checked.
840/// \param Field The field being checked. This may be a member of an anonymous
841/// struct or union nested within the class being checked.
842/// \param Inits All declarations, including anonymous struct/union members and
843/// indirect members, for which any initialization was provided.
844/// \param Diagnosed Set to true if an error is produced.
845static void CheckConstexprCtorInitializer(Sema &SemaRef,
846 const FunctionDecl *Dcl,
847 FieldDecl *Field,
848 llvm::SmallSet<Decl*, 16> &Inits,
849 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000850 if (Field->isUnnamedBitfield())
851 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000852
853 if (Field->isAnonymousStructOrUnion() &&
854 Field->getType()->getAsCXXRecordDecl()->isEmpty())
855 return;
856
Richard Smith9f569cc2011-10-01 02:31:28 +0000857 if (!Inits.count(Field)) {
858 if (!Diagnosed) {
859 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
860 Diagnosed = true;
861 }
862 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
863 } else if (Field->isAnonymousStructOrUnion()) {
864 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
865 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
866 I != E; ++I)
867 // If an anonymous union contains an anonymous struct of which any member
868 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000869 if (!RD->isUnion() || Inits.count(*I))
870 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000871 }
872}
873
874/// Check the body for the given constexpr function declaration only contains
875/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
876///
877/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000878bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000879 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000880 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000881 // The definition of a constexpr function shall satisfy the following
882 // constraints: [...]
883 // - its function-body shall be = delete, = default, or a
884 // compound-statement
885 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000886 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000887 // In the definition of a constexpr constructor, [...]
888 // - its function-body shall not be a function-try-block;
889 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
890 << isa<CXXConstructorDecl>(Dcl);
891 return false;
892 }
893
894 // - its function-body shall be [...] a compound-statement that contains only
895 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
896
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000897 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smith9f569cc2011-10-01 02:31:28 +0000898 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
899 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
900 switch ((*BodyIt)->getStmtClass()) {
901 case Stmt::NullStmtClass:
902 // - null statements,
903 continue;
904
905 case Stmt::DeclStmtClass:
906 // - static_assert-declarations
907 // - using-declarations,
908 // - using-directives,
909 // - typedef declarations and alias-declarations that do not define
910 // classes or enumerations,
911 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
912 return false;
913 continue;
914
915 case Stmt::ReturnStmtClass:
916 // - and exactly one return statement;
917 if (isa<CXXConstructorDecl>(Dcl))
918 break;
919
920 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000921 continue;
922
923 default:
924 break;
925 }
926
927 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
928 << isa<CXXConstructorDecl>(Dcl);
929 return false;
930 }
931
932 if (const CXXConstructorDecl *Constructor
933 = dyn_cast<CXXConstructorDecl>(Dcl)) {
934 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000935 // DR1359:
936 // - every non-variant non-static data member and base class sub-object
937 // shall be initialized;
938 // - if the class is a non-empty union, or for each non-empty anonymous
939 // union member of a non-union class, exactly one non-static data member
940 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000941 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000942 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000943 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
944 return false;
945 }
Richard Smith6e433752011-10-10 16:38:04 +0000946 } else if (!Constructor->isDependentContext() &&
947 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000948 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
949
950 // Skip detailed checking if we have enough initializers, and we would
951 // allow at most one initializer per member.
952 bool AnyAnonStructUnionMembers = false;
953 unsigned Fields = 0;
954 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
955 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000956 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000957 AnyAnonStructUnionMembers = true;
958 break;
959 }
960 }
961 if (AnyAnonStructUnionMembers ||
962 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
963 // Check initialization of non-static data members. Base classes are
964 // always initialized so do not need to be checked. Dependent bases
965 // might not have initializers in the member initializer list.
966 llvm::SmallSet<Decl*, 16> Inits;
967 for (CXXConstructorDecl::init_const_iterator
968 I = Constructor->init_begin(), E = Constructor->init_end();
969 I != E; ++I) {
970 if (FieldDecl *FD = (*I)->getMember())
971 Inits.insert(FD);
972 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
973 Inits.insert(ID->chain_begin(), ID->chain_end());
974 }
975
976 bool Diagnosed = false;
977 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
978 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000979 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000980 if (Diagnosed)
981 return false;
982 }
983 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000984 } else {
985 if (ReturnStmts.empty()) {
986 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
987 return false;
988 }
989 if (ReturnStmts.size() > 1) {
990 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
991 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
992 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
993 return false;
994 }
995 }
996
Richard Smith5ba73e12012-02-04 00:33:54 +0000997 // C++11 [dcl.constexpr]p5:
998 // if no function argument values exist such that the function invocation
999 // substitution would produce a constant expression, the program is
1000 // ill-formed; no diagnostic required.
1001 // C++11 [dcl.constexpr]p3:
1002 // - every constructor call and implicit conversion used in initializing the
1003 // return value shall be one of those allowed in a constant expression.
1004 // C++11 [dcl.constexpr]p4:
1005 // - every constructor involved in initializing non-static data members and
1006 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001007 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001008 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001009 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001010 << isa<CXXConstructorDecl>(Dcl);
1011 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1012 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001013 // Don't return false here: we allow this for compatibility in
1014 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001015 }
1016
Richard Smith9f569cc2011-10-01 02:31:28 +00001017 return true;
1018}
1019
Douglas Gregorb48fe382008-10-31 09:07:45 +00001020/// isCurrentClassName - Determine whether the identifier II is the
1021/// name of the class type currently being defined. In the case of
1022/// nested classes, this will only return true if II is the name of
1023/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001024bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1025 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001026 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001027
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001028 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001029 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001030 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001031 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1032 } else
1033 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1034
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001035 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001036 return &II == CurDecl->getIdentifier();
1037 else
1038 return false;
1039}
1040
Douglas Gregor229d47a2012-11-10 07:24:09 +00001041/// \brief Determine whether the given class is a base class of the given
1042/// class, including looking at dependent bases.
1043static bool findCircularInheritance(const CXXRecordDecl *Class,
1044 const CXXRecordDecl *Current) {
1045 SmallVector<const CXXRecordDecl*, 8> Queue;
1046
1047 Class = Class->getCanonicalDecl();
1048 while (true) {
1049 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1050 E = Current->bases_end();
1051 I != E; ++I) {
1052 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1053 if (!Base)
1054 continue;
1055
1056 Base = Base->getDefinition();
1057 if (!Base)
1058 continue;
1059
1060 if (Base->getCanonicalDecl() == Class)
1061 return true;
1062
1063 Queue.push_back(Base);
1064 }
1065
1066 if (Queue.empty())
1067 return false;
1068
1069 Current = Queue.back();
1070 Queue.pop_back();
1071 }
1072
1073 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001074}
1075
Mike Stump1eb44332009-09-09 15:08:12 +00001076/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001077///
1078/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1079/// and returns NULL otherwise.
1080CXXBaseSpecifier *
1081Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1082 SourceRange SpecifierRange,
1083 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001084 TypeSourceInfo *TInfo,
1085 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001086 QualType BaseType = TInfo->getType();
1087
Douglas Gregor2943aed2009-03-03 04:44:36 +00001088 // C++ [class.union]p1:
1089 // A union shall not have base classes.
1090 if (Class->isUnion()) {
1091 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1092 << SpecifierRange;
1093 return 0;
1094 }
1095
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001096 if (EllipsisLoc.isValid() &&
1097 !TInfo->getType()->containsUnexpandedParameterPack()) {
1098 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1099 << TInfo->getTypeLoc().getSourceRange();
1100 EllipsisLoc = SourceLocation();
1101 }
Douglas Gregord777e282012-11-10 01:18:17 +00001102
1103 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1104
1105 if (BaseType->isDependentType()) {
1106 // Make sure that we don't have circular inheritance among our dependent
1107 // bases. For non-dependent bases, the check for completeness below handles
1108 // this.
1109 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1110 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1111 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001112 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001113 Diag(BaseLoc, diag::err_circular_inheritance)
1114 << BaseType << Context.getTypeDeclType(Class);
1115
1116 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1117 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1118 << BaseType;
1119
1120 return 0;
1121 }
1122 }
1123
Mike Stump1eb44332009-09-09 15:08:12 +00001124 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001125 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001126 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001127 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001128
1129 // Base specifiers must be record types.
1130 if (!BaseType->isRecordType()) {
1131 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1132 return 0;
1133 }
1134
1135 // C++ [class.union]p1:
1136 // A union shall not be used as a base class.
1137 if (BaseType->isUnionType()) {
1138 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1139 return 0;
1140 }
1141
1142 // C++ [class.derived]p2:
1143 // The class-name in a base-specifier shall not be an incompletely
1144 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001145 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001146 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001147 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001148 return 0;
John McCall572fc622010-08-17 07:23:57 +00001149 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001150
Eli Friedman1d954f62009-08-15 21:55:26 +00001151 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001152 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001153 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001154 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001155 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001156 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1157 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001158
Anders Carlsson1d209272011-03-25 14:55:14 +00001159 // C++ [class]p3:
1160 // If a class is marked final and it appears as a base-type-specifier in
1161 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001162 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001163 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1164 << CXXBaseDecl->getDeclName();
1165 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1166 << CXXBaseDecl->getDeclName();
1167 return 0;
1168 }
1169
John McCall572fc622010-08-17 07:23:57 +00001170 if (BaseDecl->isInvalidDecl())
1171 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001172
1173 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001174 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001175 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001176 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001177}
1178
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001179/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1180/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001181/// example:
1182/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001183/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001184BaseResult
John McCalld226f652010-08-21 09:40:31 +00001185Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001186 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001187 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001188 ParsedType basetype, SourceLocation BaseLoc,
1189 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001190 if (!classdecl)
1191 return true;
1192
Douglas Gregor40808ce2009-03-09 23:48:35 +00001193 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001194 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001195 if (!Class)
1196 return true;
1197
Richard Smith05321402013-02-19 23:47:15 +00001198 // We do not support any C++11 attributes on base-specifiers yet.
1199 // Diagnose any attributes we see.
1200 if (!Attributes.empty()) {
1201 for (AttributeList *Attr = Attributes.getList(); Attr;
1202 Attr = Attr->getNext()) {
1203 if (Attr->isInvalid() ||
1204 Attr->getKind() == AttributeList::IgnoredAttribute)
1205 continue;
1206 Diag(Attr->getLoc(),
1207 Attr->getKind() == AttributeList::UnknownAttribute
1208 ? diag::warn_unknown_attribute_ignored
1209 : diag::err_base_specifier_attribute)
1210 << Attr->getName();
1211 }
1212 }
1213
Nick Lewycky56062202010-07-26 16:56:01 +00001214 TypeSourceInfo *TInfo = 0;
1215 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001216
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001217 if (EllipsisLoc.isInvalid() &&
1218 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001219 UPPC_BaseType))
1220 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001221
Douglas Gregor2943aed2009-03-03 04:44:36 +00001222 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001223 Virtual, Access, TInfo,
1224 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001225 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001226 else
1227 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Douglas Gregor2943aed2009-03-03 04:44:36 +00001229 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001230}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001231
Douglas Gregor2943aed2009-03-03 04:44:36 +00001232/// \brief Performs the actual work of attaching the given base class
1233/// specifiers to a C++ class.
1234bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1235 unsigned NumBases) {
1236 if (NumBases == 0)
1237 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001238
1239 // Used to keep track of which base types we have already seen, so
1240 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001241 // that the key is always the unqualified canonical type of the base
1242 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001243 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1244
1245 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001246 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001247 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001248 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001249 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001250 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001251 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001252
1253 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1254 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001255 // C++ [class.mi]p3:
1256 // A class shall not be specified as a direct base class of a
1257 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001258 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001259 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001260 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001261 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001262
1263 // Delete the duplicate base class specifier; we're going to
1264 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001265 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001266
1267 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001268 } else {
1269 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001270 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001271 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001272 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1273 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1274 if (Class->isInterface() &&
1275 (!RD->isInterface() ||
1276 KnownBase->getAccessSpecifier() != AS_public)) {
1277 // The Microsoft extension __interface does not permit bases that
1278 // are not themselves public interfaces.
1279 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1280 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1281 << RD->getSourceRange();
1282 Invalid = true;
1283 }
1284 if (RD->hasAttr<WeakAttr>())
1285 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1286 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001287 }
1288 }
1289
1290 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001291 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001292
1293 // Delete the remaining (good) base class specifiers, since their
1294 // data has been copied into the CXXRecordDecl.
1295 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001296 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001297
1298 return Invalid;
1299}
1300
1301/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1302/// class, after checking whether there are any duplicate base
1303/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001304void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001305 unsigned NumBases) {
1306 if (!ClassDecl || !Bases || !NumBases)
1307 return;
1308
1309 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001310 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001311 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001312}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001313
John McCall3cb0ebd2010-03-10 03:28:59 +00001314static CXXRecordDecl *GetClassForType(QualType T) {
1315 if (const RecordType *RT = T->getAs<RecordType>())
1316 return cast<CXXRecordDecl>(RT->getDecl());
1317 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1318 return ICT->getDecl();
1319 else
1320 return 0;
1321}
1322
Douglas Gregora8f32e02009-10-06 17:59:45 +00001323/// \brief Determine whether the type \p Derived is a C++ class that is
1324/// derived from the type \p Base.
1325bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001326 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001327 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001328
1329 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1330 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001331 return false;
1332
John McCall3cb0ebd2010-03-10 03:28:59 +00001333 CXXRecordDecl *BaseRD = GetClassForType(Base);
1334 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001335 return false;
1336
John McCall86ff3082010-02-04 22:26:26 +00001337 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1338 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001339}
1340
1341/// \brief Determine whether the type \p Derived is a C++ class that is
1342/// derived from the type \p Base.
1343bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001344 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001345 return false;
1346
John McCall3cb0ebd2010-03-10 03:28:59 +00001347 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1348 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001349 return false;
1350
John McCall3cb0ebd2010-03-10 03:28:59 +00001351 CXXRecordDecl *BaseRD = GetClassForType(Base);
1352 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001353 return false;
1354
Douglas Gregora8f32e02009-10-06 17:59:45 +00001355 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1356}
1357
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001358void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001359 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001360 assert(BasePathArray.empty() && "Base path array must be empty!");
1361 assert(Paths.isRecordingPaths() && "Must record paths!");
1362
1363 const CXXBasePath &Path = Paths.front();
1364
1365 // We first go backward and check if we have a virtual base.
1366 // FIXME: It would be better if CXXBasePath had the base specifier for
1367 // the nearest virtual base.
1368 unsigned Start = 0;
1369 for (unsigned I = Path.size(); I != 0; --I) {
1370 if (Path[I - 1].Base->isVirtual()) {
1371 Start = I - 1;
1372 break;
1373 }
1374 }
1375
1376 // Now add all bases.
1377 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001378 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001379}
1380
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001381/// \brief Determine whether the given base path includes a virtual
1382/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001383bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1384 for (CXXCastPath::const_iterator B = BasePath.begin(),
1385 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001386 B != BEnd; ++B)
1387 if ((*B)->isVirtual())
1388 return true;
1389
1390 return false;
1391}
1392
Douglas Gregora8f32e02009-10-06 17:59:45 +00001393/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1394/// conversion (where Derived and Base are class types) is
1395/// well-formed, meaning that the conversion is unambiguous (and
1396/// that all of the base classes are accessible). Returns true
1397/// and emits a diagnostic if the code is ill-formed, returns false
1398/// otherwise. Loc is the location where this routine should point to
1399/// if there is an error, and Range is the source range to highlight
1400/// if there is an error.
1401bool
1402Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001403 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001404 unsigned AmbigiousBaseConvID,
1405 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001406 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001407 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001408 // First, determine whether the path from Derived to Base is
1409 // ambiguous. This is slightly more expensive than checking whether
1410 // the Derived to Base conversion exists, because here we need to
1411 // explore multiple paths to determine if there is an ambiguity.
1412 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1413 /*DetectVirtual=*/false);
1414 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1415 assert(DerivationOkay &&
1416 "Can only be used with a derived-to-base conversion");
1417 (void)DerivationOkay;
1418
1419 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001420 if (InaccessibleBaseID) {
1421 // Check that the base class can be accessed.
1422 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1423 InaccessibleBaseID)) {
1424 case AR_inaccessible:
1425 return true;
1426 case AR_accessible:
1427 case AR_dependent:
1428 case AR_delayed:
1429 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001430 }
John McCall6b2accb2010-02-10 09:31:12 +00001431 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001432
1433 // Build a base path if necessary.
1434 if (BasePath)
1435 BuildBasePathArray(Paths, *BasePath);
1436 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001437 }
1438
1439 // We know that the derived-to-base conversion is ambiguous, and
1440 // we're going to produce a diagnostic. Perform the derived-to-base
1441 // search just one more time to compute all of the possible paths so
1442 // that we can print them out. This is more expensive than any of
1443 // the previous derived-to-base checks we've done, but at this point
1444 // performance isn't as much of an issue.
1445 Paths.clear();
1446 Paths.setRecordingPaths(true);
1447 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1448 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1449 (void)StillOkay;
1450
1451 // Build up a textual representation of the ambiguous paths, e.g.,
1452 // D -> B -> A, that will be used to illustrate the ambiguous
1453 // conversions in the diagnostic. We only print one of the paths
1454 // to each base class subobject.
1455 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1456
1457 Diag(Loc, AmbigiousBaseConvID)
1458 << Derived << Base << PathDisplayStr << Range << Name;
1459 return true;
1460}
1461
1462bool
1463Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001464 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001465 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001466 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001467 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001468 IgnoreAccess ? 0
1469 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001470 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001471 Loc, Range, DeclarationName(),
1472 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001473}
1474
1475
1476/// @brief Builds a string representing ambiguous paths from a
1477/// specific derived class to different subobjects of the same base
1478/// class.
1479///
1480/// This function builds a string that can be used in error messages
1481/// to show the different paths that one can take through the
1482/// inheritance hierarchy to go from the derived class to different
1483/// subobjects of a base class. The result looks something like this:
1484/// @code
1485/// struct D -> struct B -> struct A
1486/// struct D -> struct C -> struct A
1487/// @endcode
1488std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1489 std::string PathDisplayStr;
1490 std::set<unsigned> DisplayedPaths;
1491 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1492 Path != Paths.end(); ++Path) {
1493 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1494 // We haven't displayed a path to this particular base
1495 // class subobject yet.
1496 PathDisplayStr += "\n ";
1497 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1498 for (CXXBasePath::const_iterator Element = Path->begin();
1499 Element != Path->end(); ++Element)
1500 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1501 }
1502 }
1503
1504 return PathDisplayStr;
1505}
1506
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001507//===----------------------------------------------------------------------===//
1508// C++ class member Handling
1509//===----------------------------------------------------------------------===//
1510
Abramo Bagnara6206d532010-06-05 05:09:32 +00001511/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001512bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1513 SourceLocation ASLoc,
1514 SourceLocation ColonLoc,
1515 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001516 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001517 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001518 ASLoc, ColonLoc);
1519 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001520 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001521}
1522
Richard Smitha4b39652012-08-06 03:25:17 +00001523/// CheckOverrideControl - Check C++11 override control semantics.
1524void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001525 if (D->isInvalidDecl())
1526 return;
1527
Chris Lattner5f9e2722011-07-23 10:55:15 +00001528 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001529
Richard Smitha4b39652012-08-06 03:25:17 +00001530 // Do we know which functions this declaration might be overriding?
1531 bool OverridesAreKnown = !MD ||
1532 (!MD->getParent()->hasAnyDependentBases() &&
1533 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001534
Richard Smitha4b39652012-08-06 03:25:17 +00001535 if (!MD || !MD->isVirtual()) {
1536 if (OverridesAreKnown) {
1537 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1538 Diag(OA->getLocation(),
1539 diag::override_keyword_only_allowed_on_virtual_member_functions)
1540 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1541 D->dropAttr<OverrideAttr>();
1542 }
1543 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1544 Diag(FA->getLocation(),
1545 diag::override_keyword_only_allowed_on_virtual_member_functions)
1546 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1547 D->dropAttr<FinalAttr>();
1548 }
1549 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001550 return;
1551 }
Richard Smitha4b39652012-08-06 03:25:17 +00001552
1553 if (!OverridesAreKnown)
1554 return;
1555
1556 // C++11 [class.virtual]p5:
1557 // If a virtual function is marked with the virt-specifier override and
1558 // does not override a member function of a base class, the program is
1559 // ill-formed.
1560 bool HasOverriddenMethods =
1561 MD->begin_overridden_methods() != MD->end_overridden_methods();
1562 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1563 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1564 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001565}
1566
Richard Smitha4b39652012-08-06 03:25:17 +00001567/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001568/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001569/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001570bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1571 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001572 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001573 return false;
1574
1575 Diag(New->getLocation(), diag::err_final_function_overridden)
1576 << New->getDeclName();
1577 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1578 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001579}
1580
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001581static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001582 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1583 // FIXME: Destruction of ObjC lifetime types has side-effects.
1584 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1585 return !RD->isCompleteDefinition() ||
1586 !RD->hasTrivialDefaultConstructor() ||
1587 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001588 return false;
1589}
1590
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001591/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1592/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001593/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001594/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1595/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001596NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001597Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001598 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001599 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001600 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001601 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001602 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1603 DeclarationName Name = NameInfo.getName();
1604 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001605
1606 // For anonymous bitfields, the location should point to the type.
1607 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001608 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001609
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001610 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001611
John McCall4bde1e12010-06-04 08:34:12 +00001612 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001613 assert(!DS.isFriendSpecified());
1614
Richard Smith1ab0d902011-06-25 02:28:38 +00001615 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001616
John McCalle402e722012-09-25 07:32:39 +00001617 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1618 // The Microsoft extension __interface only permits public member functions
1619 // and prohibits constructors, destructors, operators, non-public member
1620 // functions, static methods and data members.
1621 unsigned InvalidDecl;
1622 bool ShowDeclName = true;
1623 if (!isFunc)
1624 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1625 else if (AS != AS_public)
1626 InvalidDecl = 2;
1627 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1628 InvalidDecl = 3;
1629 else switch (Name.getNameKind()) {
1630 case DeclarationName::CXXConstructorName:
1631 InvalidDecl = 4;
1632 ShowDeclName = false;
1633 break;
1634
1635 case DeclarationName::CXXDestructorName:
1636 InvalidDecl = 5;
1637 ShowDeclName = false;
1638 break;
1639
1640 case DeclarationName::CXXOperatorName:
1641 case DeclarationName::CXXConversionFunctionName:
1642 InvalidDecl = 6;
1643 break;
1644
1645 default:
1646 InvalidDecl = 0;
1647 break;
1648 }
1649
1650 if (InvalidDecl) {
1651 if (ShowDeclName)
1652 Diag(Loc, diag::err_invalid_member_in_interface)
1653 << (InvalidDecl-1) << Name;
1654 else
1655 Diag(Loc, diag::err_invalid_member_in_interface)
1656 << (InvalidDecl-1) << "";
1657 return 0;
1658 }
1659 }
1660
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001661 // C++ 9.2p6: A member shall not be declared to have automatic storage
1662 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001663 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1664 // data members and cannot be applied to names declared const or static,
1665 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001666 switch (DS.getStorageClassSpec()) {
1667 case DeclSpec::SCS_unspecified:
1668 case DeclSpec::SCS_typedef:
1669 case DeclSpec::SCS_static:
1670 // FALL THROUGH.
1671 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001672 case DeclSpec::SCS_mutable:
1673 if (isFunc) {
1674 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001675 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001676 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001677 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Sebastian Redla11f42f2008-11-17 23:24:37 +00001679 // FIXME: It would be nicer if the keyword was ignored only for this
1680 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001681 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001682 }
1683 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001684 default:
1685 if (DS.getStorageClassSpecLoc().isValid())
1686 Diag(DS.getStorageClassSpecLoc(),
1687 diag::err_storageclass_invalid_for_member);
1688 else
1689 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1690 D.getMutableDeclSpec().ClearStorageClassSpecs();
1691 }
1692
Sebastian Redl669d5d72008-11-14 23:42:31 +00001693 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1694 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001695 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001696
David Blaikie1d87fba2013-01-30 01:22:18 +00001697 if (DS.isConstexprSpecified() && isInstField) {
1698 SemaDiagnosticBuilder B =
1699 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1700 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1701 if (InitStyle == ICIS_NoInit) {
1702 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1703 D.getMutableDeclSpec().ClearConstexprSpec();
1704 const char *PrevSpec;
1705 unsigned DiagID;
1706 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1707 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001708 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001709 assert(!Failed && "Making a constexpr member const shouldn't fail");
1710 } else {
1711 B << 1;
1712 const char *PrevSpec;
1713 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001714 if (D.getMutableDeclSpec().SetStorageClassSpec(
1715 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001716 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001717 "This is the only DeclSpec that should fail to be applied");
1718 B << 1;
1719 } else {
1720 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1721 isInstField = false;
1722 }
1723 }
1724 }
1725
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001726 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001727 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001728 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001729
1730 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001731 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001732 Diag(Loc, diag::err_bad_variable_name)
1733 << Name;
1734 return 0;
1735 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001736
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001737 IdentifierInfo *II = Name.getAsIdentifierInfo();
1738
Douglas Gregorf2503652011-09-21 14:40:46 +00001739 // Member field could not be with "template" keyword.
1740 // So TemplateParameterLists should be empty in this case.
1741 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001742 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001743 if (TemplateParams->size()) {
1744 // There is no such thing as a member field template.
1745 Diag(D.getIdentifierLoc(), diag::err_template_member)
1746 << II
1747 << SourceRange(TemplateParams->getTemplateLoc(),
1748 TemplateParams->getRAngleLoc());
1749 } else {
1750 // There is an extraneous 'template<>' for this member.
1751 Diag(TemplateParams->getTemplateLoc(),
1752 diag::err_template_member_noparams)
1753 << II
1754 << SourceRange(TemplateParams->getTemplateLoc(),
1755 TemplateParams->getRAngleLoc());
1756 }
1757 return 0;
1758 }
1759
Douglas Gregor922fff22010-10-13 22:19:53 +00001760 if (SS.isSet() && !SS.isInvalid()) {
1761 // The user provided a superfluous scope specifier inside a class
1762 // definition:
1763 //
1764 // class X {
1765 // int X::member;
1766 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001767 if (DeclContext *DC = computeDeclContext(SS, false))
1768 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001769 else
1770 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1771 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001772
Douglas Gregor922fff22010-10-13 22:19:53 +00001773 SS.clear();
1774 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001775
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001776 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001777 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001778 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001779 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001780 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001781
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001782 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001783 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001784 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001785 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001786
1787 // Non-instance-fields can't have a bitfield.
1788 if (BitWidth) {
1789 if (Member->isInvalidDecl()) {
1790 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001791 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001792 // C++ 9.6p3: A bit-field shall not be a static member.
1793 // "static member 'A' cannot be a bit-field"
1794 Diag(Loc, diag::err_static_not_bitfield)
1795 << Name << BitWidth->getSourceRange();
1796 } else if (isa<TypedefDecl>(Member)) {
1797 // "typedef member 'x' cannot be a bit-field"
1798 Diag(Loc, diag::err_typedef_not_bitfield)
1799 << Name << BitWidth->getSourceRange();
1800 } else {
1801 // A function typedef ("typedef int f(); f a;").
1802 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1803 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001804 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001805 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001806 }
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Chris Lattner8b963ef2009-03-05 23:01:03 +00001808 BitWidth = 0;
1809 Member->setInvalidDecl();
1810 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001811
1812 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Douglas Gregor37b372b2009-08-20 22:52:58 +00001814 // If we have declared a member function template, set the access of the
1815 // templated declaration as well.
1816 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1817 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001818 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001819
Richard Smitha4b39652012-08-06 03:25:17 +00001820 if (VS.isOverrideSpecified())
1821 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1822 if (VS.isFinalSpecified())
1823 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001824
Douglas Gregorf5251602011-03-08 17:10:18 +00001825 if (VS.getLastLocation().isValid()) {
1826 // Update the end location of a method that has a virt-specifiers.
1827 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1828 MD->setRangeEnd(VS.getLastLocation());
1829 }
Richard Smitha4b39652012-08-06 03:25:17 +00001830
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001831 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001832
Douglas Gregor10bd3682008-11-17 22:58:34 +00001833 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001834
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001835 if (isInstField) {
1836 FieldDecl *FD = cast<FieldDecl>(Member);
1837 FieldCollector->Add(FD);
1838
1839 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1840 FD->getLocation())
1841 != DiagnosticsEngine::Ignored) {
1842 // Remember all explicit private FieldDecls that have a name, no side
1843 // effects and are not part of a dependent type declaration.
1844 if (!FD->isImplicit() && FD->getDeclName() &&
1845 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001846 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001847 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001848 !InitializationHasSideEffects(*FD))
1849 UnusedPrivateFields.insert(FD);
1850 }
1851 }
1852
John McCalld226f652010-08-21 09:40:31 +00001853 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001854}
1855
Hans Wennborg471f9852012-09-18 15:58:06 +00001856namespace {
1857 class UninitializedFieldVisitor
1858 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1859 Sema &S;
1860 ValueDecl *VD;
1861 public:
1862 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1863 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001864 S(S) {
1865 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1866 this->VD = IFD->getAnonField();
1867 else
1868 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001869 }
1870
1871 void HandleExpr(Expr *E) {
1872 if (!E) return;
1873
1874 // Expressions like x(x) sometimes lack the surrounding expressions
1875 // but need to be checked anyways.
1876 HandleValue(E);
1877 Visit(E);
1878 }
1879
1880 void HandleValue(Expr *E) {
1881 E = E->IgnoreParens();
1882
1883 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1884 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001885 return;
1886
1887 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1888 // or union.
1889 MemberExpr *FieldME = ME;
1890
Hans Wennborg471f9852012-09-18 15:58:06 +00001891 Expr *Base = E;
1892 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001893 ME = cast<MemberExpr>(Base);
1894
1895 if (isa<VarDecl>(ME->getMemberDecl()))
1896 return;
1897
1898 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1899 if (!FD->isAnonymousStructOrUnion())
1900 FieldME = ME;
1901
Hans Wennborg471f9852012-09-18 15:58:06 +00001902 Base = ME->getBase();
1903 }
1904
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001905 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00001906 unsigned diag = VD->getType()->isReferenceType()
1907 ? diag::warn_reference_field_is_uninit
1908 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001909 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001910 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001911 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00001912 }
1913
1914 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1915 HandleValue(CO->getTrueExpr());
1916 HandleValue(CO->getFalseExpr());
1917 return;
1918 }
1919
1920 if (BinaryConditionalOperator *BCO =
1921 dyn_cast<BinaryConditionalOperator>(E)) {
1922 HandleValue(BCO->getCommon());
1923 HandleValue(BCO->getFalseExpr());
1924 return;
1925 }
1926
1927 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1928 switch (BO->getOpcode()) {
1929 default:
1930 return;
1931 case(BO_PtrMemD):
1932 case(BO_PtrMemI):
1933 HandleValue(BO->getLHS());
1934 return;
1935 case(BO_Comma):
1936 HandleValue(BO->getRHS());
1937 return;
1938 }
1939 }
1940 }
1941
1942 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1943 if (E->getCastKind() == CK_LValueToRValue)
1944 HandleValue(E->getSubExpr());
1945
1946 Inherited::VisitImplicitCastExpr(E);
1947 }
1948
1949 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1950 Expr *Callee = E->getCallee();
1951 if (isa<MemberExpr>(Callee))
1952 HandleValue(Callee);
1953
1954 Inherited::VisitCXXMemberCallExpr(E);
1955 }
1956 };
1957 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1958 ValueDecl *VD) {
1959 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1960 }
1961} // namespace
1962
Richard Smith7a614d82011-06-11 17:19:42 +00001963/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001964/// in-class initializer for a non-static C++ class member, and after
1965/// instantiating an in-class initializer in a class template. Such actions
1966/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001967void
Richard Smithca523302012-06-10 03:12:00 +00001968Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001969 Expr *InitExpr) {
1970 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001971 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1972 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001973
1974 if (!InitExpr) {
1975 FD->setInvalidDecl();
1976 FD->removeInClassInitializer();
1977 return;
1978 }
1979
Peter Collingbournefef21892011-10-23 18:59:44 +00001980 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1981 FD->setInvalidDecl();
1982 FD->removeInClassInitializer();
1983 return;
1984 }
1985
Hans Wennborg471f9852012-09-18 15:58:06 +00001986 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1987 != DiagnosticsEngine::Ignored) {
1988 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1989 }
1990
Richard Smith7a614d82011-06-11 17:19:42 +00001991 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00001992 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001993 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001994 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001995 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1996 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001997 Expr **Inits = &InitExpr;
1998 unsigned NumInits = 1;
1999 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002000 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002001 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002002 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00002003 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
2004 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00002005 if (Init.isInvalid()) {
2006 FD->setInvalidDecl();
2007 return;
2008 }
Richard Smith7a614d82011-06-11 17:19:42 +00002009 }
2010
Richard Smith41956372013-01-14 22:39:08 +00002011 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002012 // The initialization of each base and member constitutes a
2013 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002014 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002015 if (Init.isInvalid()) {
2016 FD->setInvalidDecl();
2017 return;
2018 }
2019
2020 InitExpr = Init.release();
2021
2022 FD->setInClassInitializer(InitExpr);
2023}
2024
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002025/// \brief Find the direct and/or virtual base specifiers that
2026/// correspond to the given base type, for use in base initialization
2027/// within a constructor.
2028static bool FindBaseInitializer(Sema &SemaRef,
2029 CXXRecordDecl *ClassDecl,
2030 QualType BaseType,
2031 const CXXBaseSpecifier *&DirectBaseSpec,
2032 const CXXBaseSpecifier *&VirtualBaseSpec) {
2033 // First, check for a direct base class.
2034 DirectBaseSpec = 0;
2035 for (CXXRecordDecl::base_class_const_iterator Base
2036 = ClassDecl->bases_begin();
2037 Base != ClassDecl->bases_end(); ++Base) {
2038 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2039 // We found a direct base of this type. That's what we're
2040 // initializing.
2041 DirectBaseSpec = &*Base;
2042 break;
2043 }
2044 }
2045
2046 // Check for a virtual base class.
2047 // FIXME: We might be able to short-circuit this if we know in advance that
2048 // there are no virtual bases.
2049 VirtualBaseSpec = 0;
2050 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2051 // We haven't found a base yet; search the class hierarchy for a
2052 // virtual base class.
2053 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2054 /*DetectVirtual=*/false);
2055 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2056 BaseType, Paths)) {
2057 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2058 Path != Paths.end(); ++Path) {
2059 if (Path->back().Base->isVirtual()) {
2060 VirtualBaseSpec = Path->back().Base;
2061 break;
2062 }
2063 }
2064 }
2065 }
2066
2067 return DirectBaseSpec || VirtualBaseSpec;
2068}
2069
Sebastian Redl6df65482011-09-24 17:48:25 +00002070/// \brief Handle a C++ member initializer using braced-init-list syntax.
2071MemInitResult
2072Sema::ActOnMemInitializer(Decl *ConstructorD,
2073 Scope *S,
2074 CXXScopeSpec &SS,
2075 IdentifierInfo *MemberOrBase,
2076 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002077 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002078 SourceLocation IdLoc,
2079 Expr *InitList,
2080 SourceLocation EllipsisLoc) {
2081 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002082 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002083 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002084}
2085
2086/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002087MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002088Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002089 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002090 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002091 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002092 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002093 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002094 SourceLocation IdLoc,
2095 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002096 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002097 SourceLocation RParenLoc,
2098 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002099 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2100 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002101 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002102 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002103 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002104}
2105
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002106namespace {
2107
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002108// Callback to only accept typo corrections that can be a valid C++ member
2109// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002110class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2111 public:
2112 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2113 : ClassDecl(ClassDecl) {}
2114
2115 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2116 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2117 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2118 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2119 else
2120 return isa<TypeDecl>(ND);
2121 }
2122 return false;
2123 }
2124
2125 private:
2126 CXXRecordDecl *ClassDecl;
2127};
2128
2129}
2130
Sebastian Redl6df65482011-09-24 17:48:25 +00002131/// \brief Handle a C++ member initializer.
2132MemInitResult
2133Sema::BuildMemInitializer(Decl *ConstructorD,
2134 Scope *S,
2135 CXXScopeSpec &SS,
2136 IdentifierInfo *MemberOrBase,
2137 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002138 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002139 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002140 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002141 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002142 if (!ConstructorD)
2143 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002145 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002146
2147 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002148 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002149 if (!Constructor) {
2150 // The user wrote a constructor initializer on a function that is
2151 // not a C++ constructor. Ignore the error for now, because we may
2152 // have more member initializers coming; we'll diagnose it just
2153 // once in ActOnMemInitializers.
2154 return true;
2155 }
2156
2157 CXXRecordDecl *ClassDecl = Constructor->getParent();
2158
2159 // C++ [class.base.init]p2:
2160 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002161 // constructor's class and, if not found in that scope, are looked
2162 // up in the scope containing the constructor's definition.
2163 // [Note: if the constructor's class contains a member with the
2164 // same name as a direct or virtual base class of the class, a
2165 // mem-initializer-id naming the member or base class and composed
2166 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002167 // mem-initializer-id for the hidden base class may be specified
2168 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002169 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002170 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002171 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002172 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002173 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002174 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002175 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2176 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002177 if (EllipsisLoc.isValid())
2178 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002179 << MemberOrBase
2180 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002181
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002182 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002183 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002184 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002185 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002186 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002187 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002188 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002189
2190 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002191 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002192 } else if (DS.getTypeSpecType() == TST_decltype) {
2193 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002194 } else {
2195 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2196 LookupParsedName(R, S, &SS);
2197
2198 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2199 if (!TyD) {
2200 if (R.isAmbiguous()) return true;
2201
John McCallfd225442010-04-09 19:01:14 +00002202 // We don't want access-control diagnostics here.
2203 R.suppressDiagnostics();
2204
Douglas Gregor7a886e12010-01-19 06:46:48 +00002205 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2206 bool NotUnknownSpecialization = false;
2207 DeclContext *DC = computeDeclContext(SS, false);
2208 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2209 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2210
2211 if (!NotUnknownSpecialization) {
2212 // When the scope specifier can refer to a member of an unknown
2213 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002214 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2215 SS.getWithLocInContext(Context),
2216 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002217 if (BaseType.isNull())
2218 return true;
2219
Douglas Gregor7a886e12010-01-19 06:46:48 +00002220 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002221 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002222 }
2223 }
2224
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002225 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002226 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002227 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002228 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002229 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002230 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002231 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2232 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002233 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002234 // We have found a non-static data member with a similar
2235 // name to what was typed; complain and initialize that
2236 // member.
2237 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2238 << MemberOrBase << true << CorrectedQuotedStr
2239 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2240 Diag(Member->getLocation(), diag::note_previous_decl)
2241 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002242
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002243 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002244 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002245 const CXXBaseSpecifier *DirectBaseSpec;
2246 const CXXBaseSpecifier *VirtualBaseSpec;
2247 if (FindBaseInitializer(*this, ClassDecl,
2248 Context.getTypeDeclType(Type),
2249 DirectBaseSpec, VirtualBaseSpec)) {
2250 // We have found a direct or virtual base class with a
2251 // similar name to what was typed; complain and initialize
2252 // that base class.
2253 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002254 << MemberOrBase << false << CorrectedQuotedStr
2255 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002256
2257 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2258 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002259 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002260 diag::note_base_class_specified_here)
2261 << BaseSpec->getType()
2262 << BaseSpec->getSourceRange();
2263
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002264 TyD = Type;
2265 }
2266 }
2267 }
2268
Douglas Gregor7a886e12010-01-19 06:46:48 +00002269 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002270 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002271 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002272 return true;
2273 }
John McCall2b194412009-12-21 10:41:20 +00002274 }
2275
Douglas Gregor7a886e12010-01-19 06:46:48 +00002276 if (BaseType.isNull()) {
2277 BaseType = Context.getTypeDeclType(TyD);
2278 if (SS.isSet()) {
2279 NestedNameSpecifier *Qualifier =
2280 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002281
Douglas Gregor7a886e12010-01-19 06:46:48 +00002282 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002283 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002284 }
John McCall2b194412009-12-21 10:41:20 +00002285 }
2286 }
Mike Stump1eb44332009-09-09 15:08:12 +00002287
John McCalla93c9342009-12-07 02:54:59 +00002288 if (!TInfo)
2289 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002290
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002291 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002292}
2293
Chandler Carruth81c64772011-09-03 01:14:15 +00002294/// Checks a member initializer expression for cases where reference (or
2295/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002296static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2297 Expr *Init,
2298 SourceLocation IdLoc) {
2299 QualType MemberTy = Member->getType();
2300
2301 // We only handle pointers and references currently.
2302 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2303 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2304 return;
2305
2306 const bool IsPointer = MemberTy->isPointerType();
2307 if (IsPointer) {
2308 if (const UnaryOperator *Op
2309 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2310 // The only case we're worried about with pointers requires taking the
2311 // address.
2312 if (Op->getOpcode() != UO_AddrOf)
2313 return;
2314
2315 Init = Op->getSubExpr();
2316 } else {
2317 // We only handle address-of expression initializers for pointers.
2318 return;
2319 }
2320 }
2321
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002322 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2323 // Taking the address of a temporary will be diagnosed as a hard error.
2324 if (IsPointer)
2325 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002326
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002327 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2328 << Member << Init->getSourceRange();
2329 } else if (const DeclRefExpr *DRE
2330 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2331 // We only warn when referring to a non-reference parameter declaration.
2332 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2333 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002334 return;
2335
2336 S.Diag(Init->getExprLoc(),
2337 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2338 : diag::warn_bind_ref_member_to_parameter)
2339 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002340 } else {
2341 // Other initializers are fine.
2342 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002343 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002344
2345 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2346 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002347}
2348
John McCallf312b1e2010-08-26 23:41:50 +00002349MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002350Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002351 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002352 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2353 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2354 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002355 "Member must be a FieldDecl or IndirectFieldDecl");
2356
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002357 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002358 return true;
2359
Douglas Gregor464b2f02010-11-05 22:21:31 +00002360 if (Member->isInvalidDecl())
2361 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002362
John McCallb4190042009-11-04 23:02:40 +00002363 // Diagnose value-uses of fields to initialize themselves, e.g.
2364 // foo(foo)
2365 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002366 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002367 Expr **Args;
2368 unsigned NumArgs;
2369 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2370 Args = ParenList->getExprs();
2371 NumArgs = ParenList->getNumExprs();
Richard Smithc83c2302012-12-19 01:39:02 +00002372 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002373 Args = InitList->getInits();
2374 NumArgs = InitList->getNumInits();
Richard Smithc83c2302012-12-19 01:39:02 +00002375 } else {
2376 // Template instantiation doesn't reconstruct ParenListExprs for us.
2377 Args = &Init;
2378 NumArgs = 1;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002379 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002380
Richard Trieude5e75c2012-06-14 23:11:34 +00002381 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2382 != DiagnosticsEngine::Ignored)
2383 for (unsigned i = 0; i < NumArgs; ++i)
2384 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002385 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002386 // initializing the i'th field, throw a warning if any of the >= i'th
2387 // fields are used, as they are not yet initialized.
2388 // Right now we are only handling the case where the i'th field uses
2389 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002390 // Also need to take into account that some fields may be initialized by
2391 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002392 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002393
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002394 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002395
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002396 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002397 // Can't check initialization for a member of dependent type or when
2398 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002399 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002400 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002401 bool InitList = false;
2402 if (isa<InitListExpr>(Init)) {
2403 InitList = true;
2404 Args = &Init;
2405 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002406
2407 if (isStdInitializerList(Member->getType(), 0)) {
2408 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2409 << /*at end of ctor*/1 << InitRange;
2410 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002411 }
2412
Chandler Carruth894aed92010-12-06 09:23:57 +00002413 // Initialize the member.
2414 InitializedEntity MemberEntity =
2415 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2416 : InitializedEntity::InitializeMember(IndirectMember, 0);
2417 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002418 InitList ? InitializationKind::CreateDirectList(IdLoc)
2419 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2420 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002421
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002422 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2423 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002424 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002425 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002426 if (MemberInit.isInvalid())
2427 return true;
2428
Richard Smith41956372013-01-14 22:39:08 +00002429 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002430 // The initialization of each base and member constitutes a
2431 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002432 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002433 if (MemberInit.isInvalid())
2434 return true;
2435
Richard Smithc83c2302012-12-19 01:39:02 +00002436 Init = MemberInit.get();
2437 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002438 }
2439
Chandler Carruth894aed92010-12-06 09:23:57 +00002440 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002441 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2442 InitRange.getBegin(), Init,
2443 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002444 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002445 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2446 InitRange.getBegin(), Init,
2447 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002448 }
Eli Friedman59c04372009-07-29 19:44:27 +00002449}
2450
John McCallf312b1e2010-08-26 23:41:50 +00002451MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002452Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002453 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002454 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002455 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002456 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002457 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002458 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002459
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002460 bool InitList = true;
2461 Expr **Args = &Init;
2462 unsigned NumArgs = 1;
2463 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2464 InitList = false;
2465 Args = ParenList->getExprs();
2466 NumArgs = ParenList->getNumExprs();
2467 }
2468
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002469 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002470 // Initialize the object.
2471 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2472 QualType(ClassDecl->getTypeForDecl(), 0));
2473 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002474 InitList ? InitializationKind::CreateDirectList(NameLoc)
2475 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2476 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002477 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2478 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002479 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002480 0);
Sean Hunt41717662011-02-26 19:13:13 +00002481 if (DelegationInit.isInvalid())
2482 return true;
2483
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002484 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2485 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002486
Richard Smith41956372013-01-14 22:39:08 +00002487 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002488 // The initialization of each base and member constitutes a
2489 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002490 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2491 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002492 if (DelegationInit.isInvalid())
2493 return true;
2494
Eli Friedmand21016f2012-05-19 23:35:23 +00002495 // If we are in a dependent context, template instantiation will
2496 // perform this type-checking again. Just save the arguments that we
2497 // received in a ParenListExpr.
2498 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2499 // of the information that we have about the base
2500 // initializer. However, deconstructing the ASTs is a dicey process,
2501 // and this approach is far more likely to get the corner cases right.
2502 if (CurContext->isDependentContext())
2503 DelegationInit = Owned(Init);
2504
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002505 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002506 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002507 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002508}
2509
2510MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002511Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002512 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002513 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002514 SourceLocation BaseLoc
2515 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002516
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002517 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2518 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2519 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2520
2521 // C++ [class.base.init]p2:
2522 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002523 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002524 // of that class, the mem-initializer is ill-formed. A
2525 // mem-initializer-list can initialize a base class using any
2526 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002527 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002528
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002529 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002530 if (EllipsisLoc.isValid()) {
2531 // This is a pack expansion.
2532 if (!BaseType->containsUnexpandedParameterPack()) {
2533 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002534 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002535
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002536 EllipsisLoc = SourceLocation();
2537 }
2538 } else {
2539 // Check for any unexpanded parameter packs.
2540 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2541 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002542
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002543 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002544 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002545 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002546
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002547 // Check for direct and virtual base classes.
2548 const CXXBaseSpecifier *DirectBaseSpec = 0;
2549 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2550 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002551 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2552 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002553 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002554
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002555 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2556 VirtualBaseSpec);
2557
2558 // C++ [base.class.init]p2:
2559 // Unless the mem-initializer-id names a nonstatic data member of the
2560 // constructor's class or a direct or virtual base of that class, the
2561 // mem-initializer is ill-formed.
2562 if (!DirectBaseSpec && !VirtualBaseSpec) {
2563 // If the class has any dependent bases, then it's possible that
2564 // one of those types will resolve to the same type as
2565 // BaseType. Therefore, just treat this as a dependent base
2566 // class initialization. FIXME: Should we try to check the
2567 // initialization anyway? It seems odd.
2568 if (ClassDecl->hasAnyDependentBases())
2569 Dependent = true;
2570 else
2571 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2572 << BaseType << Context.getTypeDeclType(ClassDecl)
2573 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2574 }
2575 }
2576
2577 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002578 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002579
Sebastian Redl6df65482011-09-24 17:48:25 +00002580 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2581 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002582 InitRange.getBegin(), Init,
2583 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002584 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002585
2586 // C++ [base.class.init]p2:
2587 // If a mem-initializer-id is ambiguous because it designates both
2588 // a direct non-virtual base class and an inherited virtual base
2589 // class, the mem-initializer is ill-formed.
2590 if (DirectBaseSpec && VirtualBaseSpec)
2591 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002592 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002593
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002594 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002595 if (!BaseSpec)
2596 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2597
2598 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002599 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002600 Expr **Args = &Init;
2601 unsigned NumArgs = 1;
2602 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002603 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002604 Args = ParenList->getExprs();
2605 NumArgs = ParenList->getNumExprs();
2606 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002607
2608 InitializedEntity BaseEntity =
2609 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2610 InitializationKind Kind =
2611 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2612 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2613 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002614 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2615 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002616 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002617 if (BaseInit.isInvalid())
2618 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002619
Richard Smith41956372013-01-14 22:39:08 +00002620 // C++11 [class.base.init]p7:
2621 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002622 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002623 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002624 if (BaseInit.isInvalid())
2625 return true;
2626
2627 // If we are in a dependent context, template instantiation will
2628 // perform this type-checking again. Just save the arguments that we
2629 // received in a ParenListExpr.
2630 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2631 // of the information that we have about the base
2632 // initializer. However, deconstructing the ASTs is a dicey process,
2633 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002634 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002635 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002636
Sean Huntcbb67482011-01-08 20:30:50 +00002637 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002638 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002639 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002640 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002641 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002642}
2643
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002644// Create a static_cast\<T&&>(expr).
2645static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2646 QualType ExprType = E->getType();
2647 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2648 SourceLocation ExprLoc = E->getLocStart();
2649 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2650 TargetType, ExprLoc);
2651
2652 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2653 SourceRange(ExprLoc, ExprLoc),
2654 E->getSourceRange()).take();
2655}
2656
Anders Carlssone5ef7402010-04-23 03:10:23 +00002657/// ImplicitInitializerKind - How an implicit base or member initializer should
2658/// initialize its base or member.
2659enum ImplicitInitializerKind {
2660 IIK_Default,
2661 IIK_Copy,
2662 IIK_Move
2663};
2664
Anders Carlssondefefd22010-04-23 02:00:02 +00002665static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002666BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002667 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002668 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002669 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002670 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002671 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002672 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2673 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002674
John McCall60d7b3a2010-08-24 06:29:42 +00002675 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002676
2677 switch (ImplicitInitKind) {
2678 case IIK_Default: {
2679 InitializationKind InitKind
2680 = InitializationKind::CreateDefault(Constructor->getLocation());
2681 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002682 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002683 break;
2684 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002685
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002686 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002687 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002688 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002689 ParmVarDecl *Param = Constructor->getParamDecl(0);
2690 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002691
Anders Carlssone5ef7402010-04-23 03:10:23 +00002692 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002693 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002694 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002695 Constructor->getLocation(), ParamType,
2696 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002697
Eli Friedman5f2987c2012-02-02 03:46:19 +00002698 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2699
Anders Carlssonc7957502010-04-24 22:02:54 +00002700 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002701 QualType ArgTy =
2702 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2703 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002704
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002705 if (Moving) {
2706 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2707 }
2708
John McCallf871d0c2010-08-07 06:22:56 +00002709 CXXCastPath BasePath;
2710 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002711 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2712 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002713 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002714 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002715
Anders Carlssone5ef7402010-04-23 03:10:23 +00002716 InitializationKind InitKind
2717 = InitializationKind::CreateDirect(Constructor->getLocation(),
2718 SourceLocation(), SourceLocation());
2719 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2720 &CopyCtorArg, 1);
2721 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002722 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002723 break;
2724 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002725 }
John McCall9ae2f072010-08-23 23:25:46 +00002726
Douglas Gregor53c374f2010-12-07 00:41:46 +00002727 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002728 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002729 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002730
Anders Carlssondefefd22010-04-23 02:00:02 +00002731 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002732 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002733 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2734 SourceLocation()),
2735 BaseSpec->isVirtual(),
2736 SourceLocation(),
2737 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002738 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002739 SourceLocation());
2740
Anders Carlssondefefd22010-04-23 02:00:02 +00002741 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002742}
2743
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002744static bool RefersToRValueRef(Expr *MemRef) {
2745 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2746 return Referenced->getType()->isRValueReferenceType();
2747}
2748
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002749static bool
2750BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002751 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002752 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002753 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002754 if (Field->isInvalidDecl())
2755 return true;
2756
Chandler Carruthf186b542010-06-29 23:50:44 +00002757 SourceLocation Loc = Constructor->getLocation();
2758
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002759 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2760 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002761 ParmVarDecl *Param = Constructor->getParamDecl(0);
2762 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002763
2764 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002765 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2766 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002767
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002768 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002769 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002770 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002771 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002772
Eli Friedman5f2987c2012-02-02 03:46:19 +00002773 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2774
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002775 if (Moving) {
2776 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2777 }
2778
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002779 // Build a reference to this field within the parameter.
2780 CXXScopeSpec SS;
2781 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2782 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002783 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2784 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002785 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002786 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002787 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002788 ParamType, Loc,
2789 /*IsArrow=*/false,
2790 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002791 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002792 /*FirstQualifierInScope=*/0,
2793 MemberLookup,
2794 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002795 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002796 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002797
2798 // C++11 [class.copy]p15:
2799 // - if a member m has rvalue reference type T&&, it is direct-initialized
2800 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002801 if (RefersToRValueRef(CtorArg.get())) {
2802 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002803 }
2804
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002805 // When the field we are copying is an array, create index variables for
2806 // each dimension of the array. We use these index variables to subscript
2807 // the source array, and other clients (e.g., CodeGen) will perform the
2808 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002809 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002810 QualType BaseType = Field->getType();
2811 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002812 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002813 while (const ConstantArrayType *Array
2814 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002815 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002816 // Create the iteration variable for this array index.
2817 IdentifierInfo *IterationVarName = 0;
2818 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002819 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002820 llvm::raw_svector_ostream OS(Str);
2821 OS << "__i" << IndexVariables.size();
2822 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2823 }
2824 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002825 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002826 IterationVarName, SizeType,
2827 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002828 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002829 IndexVariables.push_back(IterationVar);
2830
2831 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002832 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002833 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002834 assert(!IterationVarRef.isInvalid() &&
2835 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002836 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2837 assert(!IterationVarRef.isInvalid() &&
2838 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002839
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002840 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002841 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002842 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002843 Loc);
2844 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002845 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002846
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002847 BaseType = Array->getElementType();
2848 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002849
2850 // The array subscript expression is an lvalue, which is wrong for moving.
2851 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002852 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002853
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002854 // Construct the entity that we will be initializing. For an array, this
2855 // will be first element in the array, which may require several levels
2856 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002857 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002858 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002859 if (Indirect)
2860 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2861 else
2862 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002863 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2864 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2865 0,
2866 Entities.back()));
2867
2868 // Direct-initialize to use the copy constructor.
2869 InitializationKind InitKind =
2870 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2871
Sebastian Redl74e611a2011-09-04 18:14:28 +00002872 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002873 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002874 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002875
John McCall60d7b3a2010-08-24 06:29:42 +00002876 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002877 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002878 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002879 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002880 if (MemberInit.isInvalid())
2881 return true;
2882
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002883 if (Indirect) {
2884 assert(IndexVariables.size() == 0 &&
2885 "Indirect field improperly initialized");
2886 CXXMemberInit
2887 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2888 Loc, Loc,
2889 MemberInit.takeAs<Expr>(),
2890 Loc);
2891 } else
2892 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2893 Loc, MemberInit.takeAs<Expr>(),
2894 Loc,
2895 IndexVariables.data(),
2896 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002897 return false;
2898 }
2899
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002900 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2901
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002902 QualType FieldBaseElementType =
2903 SemaRef.Context.getBaseElementType(Field->getType());
2904
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002905 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002906 InitializedEntity InitEntity
2907 = Indirect? InitializedEntity::InitializeMember(Indirect)
2908 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002909 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002910 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002911
2912 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002913 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002914 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002915
Douglas Gregor53c374f2010-12-07 00:41:46 +00002916 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002917 if (MemberInit.isInvalid())
2918 return true;
2919
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002920 if (Indirect)
2921 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2922 Indirect, Loc,
2923 Loc,
2924 MemberInit.get(),
2925 Loc);
2926 else
2927 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2928 Field, Loc, Loc,
2929 MemberInit.get(),
2930 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002931 return false;
2932 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002933
Sean Hunt1f2f3842011-05-17 00:19:05 +00002934 if (!Field->getParent()->isUnion()) {
2935 if (FieldBaseElementType->isReferenceType()) {
2936 SemaRef.Diag(Constructor->getLocation(),
2937 diag::err_uninitialized_member_in_ctor)
2938 << (int)Constructor->isImplicit()
2939 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2940 << 0 << Field->getDeclName();
2941 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2942 return true;
2943 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002944
Sean Hunt1f2f3842011-05-17 00:19:05 +00002945 if (FieldBaseElementType.isConstQualified()) {
2946 SemaRef.Diag(Constructor->getLocation(),
2947 diag::err_uninitialized_member_in_ctor)
2948 << (int)Constructor->isImplicit()
2949 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2950 << 1 << Field->getDeclName();
2951 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2952 return true;
2953 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002954 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002955
David Blaikie4e4d0842012-03-11 07:00:24 +00002956 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002957 FieldBaseElementType->isObjCRetainableType() &&
2958 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2959 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002960 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002961 // Default-initialize Objective-C pointers to NULL.
2962 CXXMemberInit
2963 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2964 Loc, Loc,
2965 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2966 Loc);
2967 return false;
2968 }
2969
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002970 // Nothing to initialize.
2971 CXXMemberInit = 0;
2972 return false;
2973}
John McCallf1860e52010-05-20 23:23:51 +00002974
2975namespace {
2976struct BaseAndFieldInfo {
2977 Sema &S;
2978 CXXConstructorDecl *Ctor;
2979 bool AnyErrorsInInits;
2980 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002981 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002982 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002983
2984 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2985 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002986 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2987 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002988 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002989 else if (Generated && Ctor->isMoveConstructor())
2990 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002991 else
2992 IIK = IIK_Default;
2993 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002994
2995 bool isImplicitCopyOrMove() const {
2996 switch (IIK) {
2997 case IIK_Copy:
2998 case IIK_Move:
2999 return true;
3000
3001 case IIK_Default:
3002 return false;
3003 }
David Blaikie30263482012-01-20 21:50:17 +00003004
3005 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003006 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003007
3008 bool addFieldInitializer(CXXCtorInitializer *Init) {
3009 AllToInit.push_back(Init);
3010
3011 // Check whether this initializer makes the field "used".
3012 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
3013 S.UnusedPrivateFields.remove(Init->getAnyMember());
3014
3015 return false;
3016 }
John McCallf1860e52010-05-20 23:23:51 +00003017};
3018}
3019
Richard Smitha4950662011-09-19 13:34:43 +00003020/// \brief Determine whether the given indirect field declaration is somewhere
3021/// within an anonymous union.
3022static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3023 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3024 CEnd = F->chain_end();
3025 C != CEnd; ++C)
3026 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3027 if (Record->isUnion())
3028 return true;
3029
3030 return false;
3031}
3032
Douglas Gregorddb21472011-11-02 23:04:16 +00003033/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3034/// array type.
3035static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3036 if (T->isIncompleteArrayType())
3037 return true;
3038
3039 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3040 if (!ArrayT->getSize())
3041 return true;
3042
3043 T = ArrayT->getElementType();
3044 }
3045
3046 return false;
3047}
3048
Richard Smith7a614d82011-06-11 17:19:42 +00003049static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003050 FieldDecl *Field,
3051 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003052
Chandler Carruthe861c602010-06-30 02:59:29 +00003053 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003054 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3055 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003056
Richard Smith0b8220a2012-08-07 21:30:42 +00003057 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003058 // has a brace-or-equal-initializer, the entity is initialized as specified
3059 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003060 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003061 CXXCtorInitializer *Init;
3062 if (Indirect)
3063 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3064 SourceLocation(),
3065 SourceLocation(), 0,
3066 SourceLocation());
3067 else
3068 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3069 SourceLocation(),
3070 SourceLocation(), 0,
3071 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003072 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003073 }
3074
Richard Smithc115f632011-09-18 11:14:50 +00003075 // Don't build an implicit initializer for union members if none was
3076 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003077 if (Field->getParent()->isUnion() ||
3078 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003079 return false;
3080
Douglas Gregorddb21472011-11-02 23:04:16 +00003081 // Don't initialize incomplete or zero-length arrays.
3082 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3083 return false;
3084
John McCallf1860e52010-05-20 23:23:51 +00003085 // Don't try to build an implicit initializer if there were semantic
3086 // errors in any of the initializers (and therefore we might be
3087 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003088 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003089 return false;
3090
Sean Huntcbb67482011-01-08 20:30:50 +00003091 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003092 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3093 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003094 return true;
John McCallf1860e52010-05-20 23:23:51 +00003095
Richard Smith0b8220a2012-08-07 21:30:42 +00003096 if (!Init)
3097 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003098
Richard Smith0b8220a2012-08-07 21:30:42 +00003099 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003100}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003101
3102bool
3103Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3104 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003105 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003106 Constructor->setNumCtorInitializers(1);
3107 CXXCtorInitializer **initializer =
3108 new (Context) CXXCtorInitializer*[1];
3109 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3110 Constructor->setCtorInitializers(initializer);
3111
Sean Huntb76af9c2011-05-03 23:05:34 +00003112 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003113 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003114 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3115 }
3116
Sean Huntc1598702011-05-05 00:05:47 +00003117 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003118
Sean Hunt059ce0d2011-05-01 07:04:31 +00003119 return false;
3120}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003121
David Blaikie93c86172013-01-17 05:26:25 +00003122bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3123 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003124 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003125 // Just store the initializers as written, they will be checked during
3126 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003127 if (!Initializers.empty()) {
3128 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003129 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003130 new (Context) CXXCtorInitializer*[Initializers.size()];
3131 memcpy(baseOrMemberInitializers, Initializers.data(),
3132 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003133 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003134 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003135
3136 // Let template instantiation know whether we had errors.
3137 if (AnyErrors)
3138 Constructor->setInvalidDecl();
3139
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003140 return false;
3141 }
3142
John McCallf1860e52010-05-20 23:23:51 +00003143 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003144
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003145 // We need to build the initializer AST according to order of construction
3146 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003147 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003148 if (!ClassDecl)
3149 return true;
3150
Eli Friedman80c30da2009-11-09 19:20:36 +00003151 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003152
David Blaikie93c86172013-01-17 05:26:25 +00003153 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003154 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003155
3156 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003157 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003158 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003159 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003160 }
3161
Anders Carlsson711f34a2010-04-21 19:52:01 +00003162 // Keep track of the direct virtual bases.
3163 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3164 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3165 E = ClassDecl->bases_end(); I != E; ++I) {
3166 if (I->isVirtual())
3167 DirectVBases.insert(I);
3168 }
3169
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003170 // Push virtual bases before others.
3171 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3172 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3173
Sean Huntcbb67482011-01-08 20:30:50 +00003174 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003175 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3176 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003177 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003178 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003179 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003180 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003181 VBase, IsInheritedVirtualBase,
3182 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003183 HadError = true;
3184 continue;
3185 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003186
John McCallf1860e52010-05-20 23:23:51 +00003187 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003188 }
3189 }
Mike Stump1eb44332009-09-09 15:08:12 +00003190
John McCallf1860e52010-05-20 23:23:51 +00003191 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003192 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3193 E = ClassDecl->bases_end(); Base != E; ++Base) {
3194 // Virtuals are in the virtual base list and already constructed.
3195 if (Base->isVirtual())
3196 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003197
Sean Huntcbb67482011-01-08 20:30:50 +00003198 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003199 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3200 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003201 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003202 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003203 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003204 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003205 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003206 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003207 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003208 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003209
John McCallf1860e52010-05-20 23:23:51 +00003210 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003211 }
3212 }
Mike Stump1eb44332009-09-09 15:08:12 +00003213
John McCallf1860e52010-05-20 23:23:51 +00003214 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003215 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3216 MemEnd = ClassDecl->decls_end();
3217 Mem != MemEnd; ++Mem) {
3218 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003219 // C++ [class.bit]p2:
3220 // A declaration for a bit-field that omits the identifier declares an
3221 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3222 // initialized.
3223 if (F->isUnnamedBitfield())
3224 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003225
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003226 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003227 // handle anonymous struct/union fields based on their individual
3228 // indirect fields.
3229 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3230 continue;
3231
3232 if (CollectFieldInitializer(*this, Info, F))
3233 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003234 continue;
3235 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003236
3237 // Beyond this point, we only consider default initialization.
3238 if (Info.IIK != IIK_Default)
3239 continue;
3240
3241 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3242 if (F->getType()->isIncompleteArrayType()) {
3243 assert(ClassDecl->hasFlexibleArrayMember() &&
3244 "Incomplete array type is not valid");
3245 continue;
3246 }
3247
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003248 // Initialize each field of an anonymous struct individually.
3249 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3250 HadError = true;
3251
3252 continue;
3253 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003254 }
Mike Stump1eb44332009-09-09 15:08:12 +00003255
David Blaikie93c86172013-01-17 05:26:25 +00003256 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003257 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003258 Constructor->setNumCtorInitializers(NumInitializers);
3259 CXXCtorInitializer **baseOrMemberInitializers =
3260 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003261 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003262 NumInitializers * sizeof(CXXCtorInitializer*));
3263 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003264
John McCallef027fe2010-03-16 21:39:52 +00003265 // Constructors implicitly reference the base and member
3266 // destructors.
3267 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3268 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003269 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003270
3271 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003272}
3273
David Blaikieee000bb2013-01-17 08:49:22 +00003274static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003275 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003276 const RecordDecl *RD = RT->getDecl();
3277 if (RD->isAnonymousStructOrUnion()) {
3278 for (RecordDecl::field_iterator Field = RD->field_begin(),
3279 E = RD->field_end(); Field != E; ++Field)
3280 PopulateKeysForFields(*Field, IdealInits);
3281 return;
3282 }
Eli Friedman6347f422009-07-21 19:28:10 +00003283 }
David Blaikieee000bb2013-01-17 08:49:22 +00003284 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003285}
3286
Anders Carlssonea356fb2010-04-02 05:42:15 +00003287static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003288 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003289}
3290
Anders Carlssonea356fb2010-04-02 05:42:15 +00003291static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003292 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003293 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003294 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003295
David Blaikieee000bb2013-01-17 08:49:22 +00003296 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003297}
3298
David Blaikie93c86172013-01-17 05:26:25 +00003299static void DiagnoseBaseOrMemInitializerOrder(
3300 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3301 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003302 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003303 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003304
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003305 // Don't check initializers order unless the warning is enabled at the
3306 // location of at least one initializer.
3307 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003308 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003309 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003310 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3311 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003312 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003313 ShouldCheckOrder = true;
3314 break;
3315 }
3316 }
3317 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003318 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003319
John McCalld6ca8da2010-04-10 07:37:23 +00003320 // Build the list of bases and members in the order that they'll
3321 // actually be initialized. The explicit initializers should be in
3322 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003323 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003324
Anders Carlsson071d6102010-04-02 03:38:04 +00003325 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3326
John McCalld6ca8da2010-04-10 07:37:23 +00003327 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003328 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003329 ClassDecl->vbases_begin(),
3330 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003331 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003332
John McCalld6ca8da2010-04-10 07:37:23 +00003333 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003334 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003335 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003336 if (Base->isVirtual())
3337 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003338 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003339 }
Mike Stump1eb44332009-09-09 15:08:12 +00003340
John McCalld6ca8da2010-04-10 07:37:23 +00003341 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003342 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003343 E = ClassDecl->field_end(); Field != E; ++Field) {
3344 if (Field->isUnnamedBitfield())
3345 continue;
3346
David Blaikieee000bb2013-01-17 08:49:22 +00003347 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003348 }
3349
John McCalld6ca8da2010-04-10 07:37:23 +00003350 unsigned NumIdealInits = IdealInitKeys.size();
3351 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003352
Sean Huntcbb67482011-01-08 20:30:50 +00003353 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003354 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003355 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003356 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003357
3358 // Scan forward to try to find this initializer in the idealized
3359 // initializers list.
3360 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3361 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003362 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003363
3364 // If we didn't find this initializer, it must be because we
3365 // scanned past it on a previous iteration. That can only
3366 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003367 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003368 Sema::SemaDiagnosticBuilder D =
3369 SemaRef.Diag(PrevInit->getSourceLocation(),
3370 diag::warn_initializer_out_of_order);
3371
Francois Pichet00eb3f92010-12-04 09:14:42 +00003372 if (PrevInit->isAnyMemberInitializer())
3373 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003374 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003375 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003376
Francois Pichet00eb3f92010-12-04 09:14:42 +00003377 if (Init->isAnyMemberInitializer())
3378 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003379 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003380 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003381
3382 // Move back to the initializer's location in the ideal list.
3383 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3384 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003385 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003386
3387 assert(IdealIndex != NumIdealInits &&
3388 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003389 }
John McCalld6ca8da2010-04-10 07:37:23 +00003390
3391 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003392 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003393}
3394
John McCall3c3ccdb2010-04-10 09:28:51 +00003395namespace {
3396bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003397 CXXCtorInitializer *Init,
3398 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003399 if (!PrevInit) {
3400 PrevInit = Init;
3401 return false;
3402 }
3403
3404 if (FieldDecl *Field = Init->getMember())
3405 S.Diag(Init->getSourceLocation(),
3406 diag::err_multiple_mem_initialization)
3407 << Field->getDeclName()
3408 << Init->getSourceRange();
3409 else {
John McCallf4c73712011-01-19 06:33:43 +00003410 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003411 assert(BaseClass && "neither field nor base");
3412 S.Diag(Init->getSourceLocation(),
3413 diag::err_multiple_base_initialization)
3414 << QualType(BaseClass, 0)
3415 << Init->getSourceRange();
3416 }
3417 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3418 << 0 << PrevInit->getSourceRange();
3419
3420 return true;
3421}
3422
Sean Huntcbb67482011-01-08 20:30:50 +00003423typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003424typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3425
3426bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003427 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003428 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003429 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003430 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003431 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003432
3433 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003434 if (Parent->isUnion()) {
3435 UnionEntry &En = Unions[Parent];
3436 if (En.first && En.first != Child) {
3437 S.Diag(Init->getSourceLocation(),
3438 diag::err_multiple_mem_union_initialization)
3439 << Field->getDeclName()
3440 << Init->getSourceRange();
3441 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3442 << 0 << En.second->getSourceRange();
3443 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003444 }
3445 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003446 En.first = Child;
3447 En.second = Init;
3448 }
David Blaikie6fe29652011-11-17 06:01:57 +00003449 if (!Parent->isAnonymousStructOrUnion())
3450 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003451 }
3452
3453 Child = Parent;
3454 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003455 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003456
3457 return false;
3458}
3459}
3460
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003461/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003462void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003463 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003464 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003465 bool AnyErrors) {
3466 if (!ConstructorDecl)
3467 return;
3468
3469 AdjustDeclIfTemplate(ConstructorDecl);
3470
3471 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003472 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003473
3474 if (!Constructor) {
3475 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3476 return;
3477 }
3478
John McCall3c3ccdb2010-04-10 09:28:51 +00003479 // Mapping for the duplicate initializers check.
3480 // For member initializers, this is keyed with a FieldDecl*.
3481 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003482 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003483
3484 // Mapping for the inconsistent anonymous-union initializers check.
3485 RedundantUnionMap MemberUnions;
3486
Anders Carlssonea356fb2010-04-02 05:42:15 +00003487 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003488 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003489 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003490
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003491 // Set the source order index.
3492 Init->setSourceOrder(i);
3493
Francois Pichet00eb3f92010-12-04 09:14:42 +00003494 if (Init->isAnyMemberInitializer()) {
3495 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003496 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3497 CheckRedundantUnionInit(*this, Init, MemberUnions))
3498 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003499 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003500 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3501 if (CheckRedundantInit(*this, Init, Members[Key]))
3502 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003503 } else {
3504 assert(Init->isDelegatingInitializer());
3505 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003506 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003507 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003508 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003509 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003510 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003511 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003512 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003513 // Return immediately as the initializer is set.
3514 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003515 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003516 }
3517
Anders Carlssonea356fb2010-04-02 05:42:15 +00003518 if (HadError)
3519 return;
3520
David Blaikie93c86172013-01-17 05:26:25 +00003521 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003522
David Blaikie93c86172013-01-17 05:26:25 +00003523 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003524}
3525
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003526void
John McCallef027fe2010-03-16 21:39:52 +00003527Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3528 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003529 // Ignore dependent contexts. Also ignore unions, since their members never
3530 // have destructors implicitly called.
3531 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003532 return;
John McCall58e6f342010-03-16 05:22:47 +00003533
3534 // FIXME: all the access-control diagnostics are positioned on the
3535 // field/base declaration. That's probably good; that said, the
3536 // user might reasonably want to know why the destructor is being
3537 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003538
Anders Carlsson9f853df2009-11-17 04:44:12 +00003539 // Non-static data members.
3540 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3541 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003542 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003543 if (Field->isInvalidDecl())
3544 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003545
3546 // Don't destroy incomplete or zero-length arrays.
3547 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3548 continue;
3549
Anders Carlsson9f853df2009-11-17 04:44:12 +00003550 QualType FieldType = Context.getBaseElementType(Field->getType());
3551
3552 const RecordType* RT = FieldType->getAs<RecordType>();
3553 if (!RT)
3554 continue;
3555
3556 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003557 if (FieldClassDecl->isInvalidDecl())
3558 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003559 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003560 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003561 // The destructor for an implicit anonymous union member is never invoked.
3562 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3563 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003564
Douglas Gregordb89f282010-07-01 22:47:18 +00003565 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003566 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003567 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003568 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003569 << Field->getDeclName()
3570 << FieldType);
3571
Eli Friedman5f2987c2012-02-02 03:46:19 +00003572 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003573 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003574 }
3575
John McCall58e6f342010-03-16 05:22:47 +00003576 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3577
Anders Carlsson9f853df2009-11-17 04:44:12 +00003578 // Bases.
3579 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3580 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003581 // Bases are always records in a well-formed non-dependent class.
3582 const RecordType *RT = Base->getType()->getAs<RecordType>();
3583
3584 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003585 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003586 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003587
John McCall58e6f342010-03-16 05:22:47 +00003588 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003589 // If our base class is invalid, we probably can't get its dtor anyway.
3590 if (BaseClassDecl->isInvalidDecl())
3591 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003592 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003593 continue;
John McCall58e6f342010-03-16 05:22:47 +00003594
Douglas Gregordb89f282010-07-01 22:47:18 +00003595 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003596 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003597
3598 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003599 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003600 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003601 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003602 << Base->getSourceRange(),
3603 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003604
Eli Friedman5f2987c2012-02-02 03:46:19 +00003605 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003606 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003607 }
3608
3609 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003610 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3611 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003612
3613 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003614 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003615
3616 // Ignore direct virtual bases.
3617 if (DirectVirtualBases.count(RT))
3618 continue;
3619
John McCall58e6f342010-03-16 05:22:47 +00003620 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003621 // If our base class is invalid, we probably can't get its dtor anyway.
3622 if (BaseClassDecl->isInvalidDecl())
3623 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003624 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003625 continue;
John McCall58e6f342010-03-16 05:22:47 +00003626
Douglas Gregordb89f282010-07-01 22:47:18 +00003627 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003628 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003629 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003630 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003631 << VBase->getType(),
3632 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003633
Eli Friedman5f2987c2012-02-02 03:46:19 +00003634 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003635 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003636 }
3637}
3638
John McCalld226f652010-08-21 09:40:31 +00003639void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003640 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003641 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003642
Mike Stump1eb44332009-09-09 15:08:12 +00003643 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003644 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003645 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003646}
3647
Mike Stump1eb44332009-09-09 15:08:12 +00003648bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003649 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003650 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3651 unsigned DiagID;
3652 AbstractDiagSelID SelID;
3653
3654 public:
3655 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3656 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3657
3658 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003659 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003660 if (SelID == -1)
3661 S.Diag(Loc, DiagID) << T;
3662 else
3663 S.Diag(Loc, DiagID) << SelID << T;
3664 }
3665 } Diagnoser(DiagID, SelID);
3666
3667 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003668}
3669
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003670bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003671 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003672 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003673 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003674
Anders Carlsson11f21a02009-03-23 19:10:31 +00003675 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003676 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003677
Ted Kremenek6217b802009-07-29 21:53:49 +00003678 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003679 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003680 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003681 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003682
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003683 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003684 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003685 }
Mike Stump1eb44332009-09-09 15:08:12 +00003686
Ted Kremenek6217b802009-07-29 21:53:49 +00003687 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003688 if (!RT)
3689 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003690
John McCall86ff3082010-02-04 22:26:26 +00003691 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003692
John McCall94c3b562010-08-18 09:41:07 +00003693 // We can't answer whether something is abstract until it has a
3694 // definition. If it's currently being defined, we'll walk back
3695 // over all the declarations when we have a full definition.
3696 const CXXRecordDecl *Def = RD->getDefinition();
3697 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003698 return false;
3699
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003700 if (!RD->isAbstract())
3701 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003702
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003703 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003704 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003705
John McCall94c3b562010-08-18 09:41:07 +00003706 return true;
3707}
3708
3709void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3710 // Check if we've already emitted the list of pure virtual functions
3711 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003712 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003713 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003714
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003715 CXXFinalOverriderMap FinalOverriders;
3716 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003717
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003718 // Keep a set of seen pure methods so we won't diagnose the same method
3719 // more than once.
3720 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3721
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003722 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3723 MEnd = FinalOverriders.end();
3724 M != MEnd;
3725 ++M) {
3726 for (OverridingMethods::iterator SO = M->second.begin(),
3727 SOEnd = M->second.end();
3728 SO != SOEnd; ++SO) {
3729 // C++ [class.abstract]p4:
3730 // A class is abstract if it contains or inherits at least one
3731 // pure virtual function for which the final overrider is pure
3732 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003733
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003734 //
3735 if (SO->second.size() != 1)
3736 continue;
3737
3738 if (!SO->second.front().Method->isPure())
3739 continue;
3740
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003741 if (!SeenPureMethods.insert(SO->second.front().Method))
3742 continue;
3743
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003744 Diag(SO->second.front().Method->getLocation(),
3745 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003746 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003747 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003748 }
3749
3750 if (!PureVirtualClassDiagSet)
3751 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3752 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003753}
3754
Anders Carlsson8211eff2009-03-24 01:19:16 +00003755namespace {
John McCall94c3b562010-08-18 09:41:07 +00003756struct AbstractUsageInfo {
3757 Sema &S;
3758 CXXRecordDecl *Record;
3759 CanQualType AbstractType;
3760 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003761
John McCall94c3b562010-08-18 09:41:07 +00003762 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3763 : S(S), Record(Record),
3764 AbstractType(S.Context.getCanonicalType(
3765 S.Context.getTypeDeclType(Record))),
3766 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003767
John McCall94c3b562010-08-18 09:41:07 +00003768 void DiagnoseAbstractType() {
3769 if (Invalid) return;
3770 S.DiagnoseAbstractType(Record);
3771 Invalid = true;
3772 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003773
John McCall94c3b562010-08-18 09:41:07 +00003774 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3775};
3776
3777struct CheckAbstractUsage {
3778 AbstractUsageInfo &Info;
3779 const NamedDecl *Ctx;
3780
3781 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3782 : Info(Info), Ctx(Ctx) {}
3783
3784 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3785 switch (TL.getTypeLocClass()) {
3786#define ABSTRACT_TYPELOC(CLASS, PARENT)
3787#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003788 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003789#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003790 }
John McCall94c3b562010-08-18 09:41:07 +00003791 }
Mike Stump1eb44332009-09-09 15:08:12 +00003792
John McCall94c3b562010-08-18 09:41:07 +00003793 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3794 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3795 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003796 if (!TL.getArg(I))
3797 continue;
3798
John McCall94c3b562010-08-18 09:41:07 +00003799 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3800 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003801 }
John McCall94c3b562010-08-18 09:41:07 +00003802 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003803
John McCall94c3b562010-08-18 09:41:07 +00003804 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3805 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3806 }
Mike Stump1eb44332009-09-09 15:08:12 +00003807
John McCall94c3b562010-08-18 09:41:07 +00003808 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3809 // Visit the type parameters from a permissive context.
3810 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3811 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3812 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3813 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3814 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3815 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003816 }
John McCall94c3b562010-08-18 09:41:07 +00003817 }
Mike Stump1eb44332009-09-09 15:08:12 +00003818
John McCall94c3b562010-08-18 09:41:07 +00003819 // Visit pointee types from a permissive context.
3820#define CheckPolymorphic(Type) \
3821 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3822 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3823 }
3824 CheckPolymorphic(PointerTypeLoc)
3825 CheckPolymorphic(ReferenceTypeLoc)
3826 CheckPolymorphic(MemberPointerTypeLoc)
3827 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003828 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003829
John McCall94c3b562010-08-18 09:41:07 +00003830 /// Handle all the types we haven't given a more specific
3831 /// implementation for above.
3832 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3833 // Every other kind of type that we haven't called out already
3834 // that has an inner type is either (1) sugar or (2) contains that
3835 // inner type in some way as a subobject.
3836 if (TypeLoc Next = TL.getNextTypeLoc())
3837 return Visit(Next, Sel);
3838
3839 // If there's no inner type and we're in a permissive context,
3840 // don't diagnose.
3841 if (Sel == Sema::AbstractNone) return;
3842
3843 // Check whether the type matches the abstract type.
3844 QualType T = TL.getType();
3845 if (T->isArrayType()) {
3846 Sel = Sema::AbstractArrayType;
3847 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003848 }
John McCall94c3b562010-08-18 09:41:07 +00003849 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3850 if (CT != Info.AbstractType) return;
3851
3852 // It matched; do some magic.
3853 if (Sel == Sema::AbstractArrayType) {
3854 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3855 << T << TL.getSourceRange();
3856 } else {
3857 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3858 << Sel << T << TL.getSourceRange();
3859 }
3860 Info.DiagnoseAbstractType();
3861 }
3862};
3863
3864void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3865 Sema::AbstractDiagSelID Sel) {
3866 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3867}
3868
3869}
3870
3871/// Check for invalid uses of an abstract type in a method declaration.
3872static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3873 CXXMethodDecl *MD) {
3874 // No need to do the check on definitions, which require that
3875 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003876 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003877 return;
3878
3879 // For safety's sake, just ignore it if we don't have type source
3880 // information. This should never happen for non-implicit methods,
3881 // but...
3882 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3883 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3884}
3885
3886/// Check for invalid uses of an abstract type within a class definition.
3887static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3888 CXXRecordDecl *RD) {
3889 for (CXXRecordDecl::decl_iterator
3890 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3891 Decl *D = *I;
3892 if (D->isImplicit()) continue;
3893
3894 // Methods and method templates.
3895 if (isa<CXXMethodDecl>(D)) {
3896 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3897 } else if (isa<FunctionTemplateDecl>(D)) {
3898 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3899 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3900
3901 // Fields and static variables.
3902 } else if (isa<FieldDecl>(D)) {
3903 FieldDecl *FD = cast<FieldDecl>(D);
3904 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3905 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3906 } else if (isa<VarDecl>(D)) {
3907 VarDecl *VD = cast<VarDecl>(D);
3908 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3909 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3910
3911 // Nested classes and class templates.
3912 } else if (isa<CXXRecordDecl>(D)) {
3913 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3914 } else if (isa<ClassTemplateDecl>(D)) {
3915 CheckAbstractClassUsage(Info,
3916 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3917 }
3918 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003919}
3920
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003921/// \brief Perform semantic checks on a class definition that has been
3922/// completing, introducing implicitly-declared members, checking for
3923/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003924void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003925 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003926 return;
3927
John McCall94c3b562010-08-18 09:41:07 +00003928 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3929 AbstractUsageInfo Info(*this, Record);
3930 CheckAbstractClassUsage(Info, Record);
3931 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003932
3933 // If this is not an aggregate type and has no user-declared constructor,
3934 // complain about any non-static data members of reference or const scalar
3935 // type, since they will never get initializers.
3936 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003937 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3938 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003939 bool Complained = false;
3940 for (RecordDecl::field_iterator F = Record->field_begin(),
3941 FEnd = Record->field_end();
3942 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003943 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003944 continue;
3945
Douglas Gregor325e5932010-04-15 00:00:53 +00003946 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003947 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003948 if (!Complained) {
3949 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3950 << Record->getTagKind() << Record;
3951 Complained = true;
3952 }
3953
3954 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3955 << F->getType()->isReferenceType()
3956 << F->getDeclName();
3957 }
3958 }
3959 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003960
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003961 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003962 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003963
3964 if (Record->getIdentifier()) {
3965 // C++ [class.mem]p13:
3966 // If T is the name of a class, then each of the following shall have a
3967 // name different from T:
3968 // - every member of every anonymous union that is a member of class T.
3969 //
3970 // C++ [class.mem]p14:
3971 // In addition, if class T has a user-declared constructor (12.1), every
3972 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00003973 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3974 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3975 ++I) {
3976 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00003977 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3978 isa<IndirectFieldDecl>(D)) {
3979 Diag(D->getLocation(), diag::err_member_name_of_class)
3980 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003981 break;
3982 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003983 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003984 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003985
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003986 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003987 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003988 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003989 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003990 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3991 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3992 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003993
David Blaikieb6b5b972012-09-21 03:21:07 +00003994 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
3995 Diag(Record->getLocation(), diag::warn_abstract_final_class);
3996 DiagnoseAbstractType(Record);
3997 }
3998
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003999 if (!Record->isDependentType()) {
4000 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4001 MEnd = Record->method_end();
4002 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004003 // See if a method overloads virtual methods in a base
4004 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004005 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004006 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004007
4008 // Check whether the explicitly-defaulted special members are valid.
4009 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4010 CheckExplicitlyDefaultedSpecialMember(*M);
4011
4012 // For an explicitly defaulted or deleted special member, we defer
4013 // determining triviality until the class is complete. That time is now!
4014 if (!M->isImplicit() && !M->isUserProvided()) {
4015 CXXSpecialMember CSM = getSpecialMember(*M);
4016 if (CSM != CXXInvalid) {
4017 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4018
4019 // Inform the class that we've finished declaring this member.
4020 Record->finishedDefaultedOrDeletedMember(*M);
4021 }
4022 }
4023 }
4024 }
4025
4026 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4027 // function that is not a constructor declares that member function to be
4028 // const. [...] The class of which that function is a member shall be
4029 // a literal type.
4030 //
4031 // If the class has virtual bases, any constexpr members will already have
4032 // been diagnosed by the checks performed on the member declaration, so
4033 // suppress this (less useful) diagnostic.
4034 //
4035 // We delay this until we know whether an explicitly-defaulted (or deleted)
4036 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004037 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004038 !Record->isLiteral() && !Record->getNumVBases()) {
4039 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4040 MEnd = Record->method_end();
4041 M != MEnd; ++M) {
4042 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4043 switch (Record->getTemplateSpecializationKind()) {
4044 case TSK_ImplicitInstantiation:
4045 case TSK_ExplicitInstantiationDeclaration:
4046 case TSK_ExplicitInstantiationDefinition:
4047 // If a template instantiates to a non-literal type, but its members
4048 // instantiate to constexpr functions, the template is technically
4049 // ill-formed, but we allow it for sanity.
4050 continue;
4051
4052 case TSK_Undeclared:
4053 case TSK_ExplicitSpecialization:
4054 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4055 diag::err_constexpr_method_non_literal);
4056 break;
4057 }
4058
4059 // Only produce one error per class.
4060 break;
4061 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004062 }
4063 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004064
4065 // Declare inherited constructors. We do this eagerly here because:
4066 // - The standard requires an eager diagnostic for conflicting inherited
4067 // constructors from different classes.
4068 // - The lazy declaration of the other implicit constructors is so as to not
4069 // waste space and performance on classes that are not meant to be
4070 // instantiated (e.g. meta-functions). This doesn't apply to classes that
4071 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004072 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004073}
4074
Richard Smith7756afa2012-06-10 05:43:50 +00004075/// Is the special member function which would be selected to perform the
4076/// specified operation on the specified class type a constexpr constructor?
4077static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4078 Sema::CXXSpecialMember CSM,
4079 bool ConstArg) {
4080 Sema::SpecialMemberOverloadResult *SMOR =
4081 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4082 false, false, false, false);
4083 if (!SMOR || !SMOR->getMethod())
4084 // A constructor we wouldn't select can't be "involved in initializing"
4085 // anything.
4086 return true;
4087 return SMOR->getMethod()->isConstexpr();
4088}
4089
4090/// Determine whether the specified special member function would be constexpr
4091/// if it were implicitly defined.
4092static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4093 Sema::CXXSpecialMember CSM,
4094 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004095 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004096 return false;
4097
4098 // C++11 [dcl.constexpr]p4:
4099 // In the definition of a constexpr constructor [...]
4100 switch (CSM) {
4101 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004102 // Since default constructor lookup is essentially trivial (and cannot
4103 // involve, for instance, template instantiation), we compute whether a
4104 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4105 //
4106 // This is important for performance; we need to know whether the default
4107 // constructor is constexpr to determine whether the type is a literal type.
4108 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4109
Richard Smith7756afa2012-06-10 05:43:50 +00004110 case Sema::CXXCopyConstructor:
4111 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004112 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004113 break;
4114
4115 case Sema::CXXCopyAssignment:
4116 case Sema::CXXMoveAssignment:
4117 case Sema::CXXDestructor:
4118 case Sema::CXXInvalid:
4119 return false;
4120 }
4121
4122 // -- if the class is a non-empty union, or for each non-empty anonymous
4123 // union member of a non-union class, exactly one non-static data member
4124 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004125 //
4126 // If we squint, this is guaranteed, since exactly one non-static data member
4127 // will be initialized (if the constructor isn't deleted), we just don't know
4128 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004129 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004130 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004131
4132 // -- the class shall not have any virtual base classes;
4133 if (ClassDecl->getNumVBases())
4134 return false;
4135
4136 // -- every constructor involved in initializing [...] base class
4137 // sub-objects shall be a constexpr constructor;
4138 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4139 BEnd = ClassDecl->bases_end();
4140 B != BEnd; ++B) {
4141 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4142 if (!BaseType) continue;
4143
4144 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4145 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4146 return false;
4147 }
4148
4149 // -- every constructor involved in initializing non-static data members
4150 // [...] shall be a constexpr constructor;
4151 // -- every non-static data member and base class sub-object shall be
4152 // initialized
4153 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4154 FEnd = ClassDecl->field_end();
4155 F != FEnd; ++F) {
4156 if (F->isInvalidDecl())
4157 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004158 if (const RecordType *RecordTy =
4159 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004160 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4161 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4162 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004163 }
4164 }
4165
4166 // All OK, it's constexpr!
4167 return true;
4168}
4169
Richard Smithb9d0b762012-07-27 04:22:15 +00004170static Sema::ImplicitExceptionSpecification
4171computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4172 switch (S.getSpecialMember(MD)) {
4173 case Sema::CXXDefaultConstructor:
4174 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4175 case Sema::CXXCopyConstructor:
4176 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4177 case Sema::CXXCopyAssignment:
4178 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4179 case Sema::CXXMoveConstructor:
4180 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4181 case Sema::CXXMoveAssignment:
4182 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4183 case Sema::CXXDestructor:
4184 return S.ComputeDefaultedDtorExceptionSpec(MD);
4185 case Sema::CXXInvalid:
4186 break;
4187 }
4188 llvm_unreachable("only special members have implicit exception specs");
4189}
4190
Richard Smithdd25e802012-07-30 23:48:14 +00004191static void
4192updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4193 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4194 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4195 ExceptSpec.getEPI(EPI);
4196 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4197 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4198 FPT->getNumArgs(), EPI));
4199 FD->setType(QualType(NewFPT, 0));
4200}
4201
Richard Smithb9d0b762012-07-27 04:22:15 +00004202void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4203 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4204 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4205 return;
4206
Richard Smithdd25e802012-07-30 23:48:14 +00004207 // Evaluate the exception specification.
4208 ImplicitExceptionSpecification ExceptSpec =
4209 computeImplicitExceptionSpec(*this, Loc, MD);
4210
4211 // Update the type of the special member to use it.
4212 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4213
4214 // A user-provided destructor can be defined outside the class. When that
4215 // happens, be sure to update the exception specification on both
4216 // declarations.
4217 const FunctionProtoType *CanonicalFPT =
4218 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4219 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4220 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4221 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004222}
4223
Richard Smith3003e1d2012-05-15 04:39:51 +00004224void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4225 CXXRecordDecl *RD = MD->getParent();
4226 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004227
Richard Smith3003e1d2012-05-15 04:39:51 +00004228 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4229 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004230
4231 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004232 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004233 bool First = MD == MD->getCanonicalDecl();
4234
4235 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004236
4237 // C++11 [dcl.fct.def.default]p1:
4238 // A function that is explicitly defaulted shall
4239 // -- be a special member function (checked elsewhere),
4240 // -- have the same type (except for ref-qualifiers, and except that a
4241 // copy operation can take a non-const reference) as an implicit
4242 // declaration, and
4243 // -- not have default arguments.
4244 unsigned ExpectedParams = 1;
4245 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4246 ExpectedParams = 0;
4247 if (MD->getNumParams() != ExpectedParams) {
4248 // This also checks for default arguments: a copy or move constructor with a
4249 // default argument is classified as a default constructor, and assignment
4250 // operations and destructors can't have default arguments.
4251 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4252 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004253 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004254 } else if (MD->isVariadic()) {
4255 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4256 << CSM << MD->getSourceRange();
4257 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004258 }
4259
Richard Smith3003e1d2012-05-15 04:39:51 +00004260 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004261
Richard Smith7756afa2012-06-10 05:43:50 +00004262 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004263 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004264 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004265 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004266 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004267
Richard Smith3003e1d2012-05-15 04:39:51 +00004268 QualType ReturnType = Context.VoidTy;
4269 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4270 // Check for return type matching.
4271 ReturnType = Type->getResultType();
4272 QualType ExpectedReturnType =
4273 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4274 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4275 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4276 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4277 HadError = true;
4278 }
4279
4280 // A defaulted special member cannot have cv-qualifiers.
4281 if (Type->getTypeQuals()) {
4282 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4283 << (CSM == CXXMoveAssignment);
4284 HadError = true;
4285 }
4286 }
4287
4288 // Check for parameter type matching.
4289 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004290 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004291 if (ExpectedParams && ArgType->isReferenceType()) {
4292 // Argument must be reference to possibly-const T.
4293 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004294 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004295
4296 if (ReferentType.isVolatileQualified()) {
4297 Diag(MD->getLocation(),
4298 diag::err_defaulted_special_member_volatile_param) << CSM;
4299 HadError = true;
4300 }
4301
Richard Smith7756afa2012-06-10 05:43:50 +00004302 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004303 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4304 Diag(MD->getLocation(),
4305 diag::err_defaulted_special_member_copy_const_param)
4306 << (CSM == CXXCopyAssignment);
4307 // FIXME: Explain why this special member can't be const.
4308 } else {
4309 Diag(MD->getLocation(),
4310 diag::err_defaulted_special_member_move_const_param)
4311 << (CSM == CXXMoveAssignment);
4312 }
4313 HadError = true;
4314 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004315 } else if (ExpectedParams) {
4316 // A copy assignment operator can take its argument by value, but a
4317 // defaulted one cannot.
4318 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004319 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004320 HadError = true;
4321 }
Sean Huntbe631222011-05-17 20:44:43 +00004322
Richard Smith61802452011-12-22 02:22:31 +00004323 // C++11 [dcl.fct.def.default]p2:
4324 // An explicitly-defaulted function may be declared constexpr only if it
4325 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004326 // Do not apply this rule to members of class templates, since core issue 1358
4327 // makes such functions always instantiate to constexpr functions. For
4328 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004329 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4330 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004331 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4332 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4333 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004334 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004335 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004336 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004337
Richard Smith61802452011-12-22 02:22:31 +00004338 // and may have an explicit exception-specification only if it is compatible
4339 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004340 if (Type->hasExceptionSpec()) {
4341 // Delay the check if this is the first declaration of the special member,
4342 // since we may not have parsed some necessary in-class initializers yet.
4343 if (First)
4344 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4345 else
4346 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4347 }
Richard Smith61802452011-12-22 02:22:31 +00004348
4349 // If a function is explicitly defaulted on its first declaration,
4350 if (First) {
4351 // -- it is implicitly considered to be constexpr if the implicit
4352 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004353 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004354
Richard Smith3003e1d2012-05-15 04:39:51 +00004355 // -- it is implicitly considered to have the same exception-specification
4356 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004357 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4358 EPI.ExceptionSpecType = EST_Unevaluated;
4359 EPI.ExceptionSpecDecl = MD;
4360 MD->setType(Context.getFunctionType(ReturnType, &ArgType,
4361 ExpectedParams, EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004362 }
4363
Richard Smith3003e1d2012-05-15 04:39:51 +00004364 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004365 if (First) {
4366 MD->setDeletedAsWritten();
4367 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004368 // C++11 [dcl.fct.def.default]p4:
4369 // [For a] user-provided explicitly-defaulted function [...] if such a
4370 // function is implicitly defined as deleted, the program is ill-formed.
4371 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4372 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004373 }
4374 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004375
Richard Smith3003e1d2012-05-15 04:39:51 +00004376 if (HadError)
4377 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004378}
4379
Richard Smith1d28caf2012-12-11 01:14:52 +00004380/// Check whether the exception specification provided for an
4381/// explicitly-defaulted special member matches the exception specification
4382/// that would have been generated for an implicit special member, per
4383/// C++11 [dcl.fct.def.default]p2.
4384void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4385 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4386 // Compute the implicit exception specification.
4387 FunctionProtoType::ExtProtoInfo EPI;
4388 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4389 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4390 Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4391
4392 // Ensure that it matches.
4393 CheckEquivalentExceptionSpec(
4394 PDiag(diag::err_incorrect_defaulted_exception_spec)
4395 << getSpecialMember(MD), PDiag(),
4396 ImplicitType, SourceLocation(),
4397 SpecifiedType, MD->getLocation());
4398}
4399
4400void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4401 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4402 I != N; ++I)
4403 CheckExplicitlyDefaultedMemberExceptionSpec(
4404 DelayedDefaultedMemberExceptionSpecs[I].first,
4405 DelayedDefaultedMemberExceptionSpecs[I].second);
4406
4407 DelayedDefaultedMemberExceptionSpecs.clear();
4408}
4409
Richard Smith7d5088a2012-02-18 02:02:13 +00004410namespace {
4411struct SpecialMemberDeletionInfo {
4412 Sema &S;
4413 CXXMethodDecl *MD;
4414 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004415 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004416
4417 // Properties of the special member, computed for convenience.
4418 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4419 SourceLocation Loc;
4420
4421 bool AllFieldsAreConst;
4422
4423 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004424 Sema::CXXSpecialMember CSM, bool Diagnose)
4425 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004426 IsConstructor(false), IsAssignment(false), IsMove(false),
4427 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4428 AllFieldsAreConst(true) {
4429 switch (CSM) {
4430 case Sema::CXXDefaultConstructor:
4431 case Sema::CXXCopyConstructor:
4432 IsConstructor = true;
4433 break;
4434 case Sema::CXXMoveConstructor:
4435 IsConstructor = true;
4436 IsMove = true;
4437 break;
4438 case Sema::CXXCopyAssignment:
4439 IsAssignment = true;
4440 break;
4441 case Sema::CXXMoveAssignment:
4442 IsAssignment = true;
4443 IsMove = true;
4444 break;
4445 case Sema::CXXDestructor:
4446 break;
4447 case Sema::CXXInvalid:
4448 llvm_unreachable("invalid special member kind");
4449 }
4450
4451 if (MD->getNumParams()) {
4452 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4453 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4454 }
4455 }
4456
4457 bool inUnion() const { return MD->getParent()->isUnion(); }
4458
4459 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004460 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4461 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004462 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004463 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4464 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4465 Quals = 0;
4466 return S.LookupSpecialMember(Class, CSM,
4467 ConstArg || (Quals & Qualifiers::Const),
4468 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004469 MD->getRefQualifier() == RQ_RValue,
4470 TQ & Qualifiers::Const,
4471 TQ & Qualifiers::Volatile);
4472 }
4473
Richard Smith6c4c36c2012-03-30 20:53:28 +00004474 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004475
Richard Smith6c4c36c2012-03-30 20:53:28 +00004476 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004477 bool shouldDeleteForField(FieldDecl *FD);
4478 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004479
Richard Smith517bb842012-07-18 03:51:16 +00004480 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4481 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004482 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4483 Sema::SpecialMemberOverloadResult *SMOR,
4484 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004485
4486 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004487};
4488}
4489
John McCall12d8d802012-04-09 20:53:23 +00004490/// Is the given special member inaccessible when used on the given
4491/// sub-object.
4492bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4493 CXXMethodDecl *target) {
4494 /// If we're operating on a base class, the object type is the
4495 /// type of this special member.
4496 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004497 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004498 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4499 objectTy = S.Context.getTypeDeclType(MD->getParent());
4500 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4501
4502 // If we're operating on a field, the object type is the type of the field.
4503 } else {
4504 objectTy = S.Context.getTypeDeclType(target->getParent());
4505 }
4506
4507 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4508}
4509
Richard Smith6c4c36c2012-03-30 20:53:28 +00004510/// Check whether we should delete a special member due to the implicit
4511/// definition containing a call to a special member of a subobject.
4512bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4513 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4514 bool IsDtorCallInCtor) {
4515 CXXMethodDecl *Decl = SMOR->getMethod();
4516 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4517
4518 int DiagKind = -1;
4519
4520 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4521 DiagKind = !Decl ? 0 : 1;
4522 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4523 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004524 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004525 DiagKind = 3;
4526 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4527 !Decl->isTrivial()) {
4528 // A member of a union must have a trivial corresponding special member.
4529 // As a weird special case, a destructor call from a union's constructor
4530 // must be accessible and non-deleted, but need not be trivial. Such a
4531 // destructor is never actually called, but is semantically checked as
4532 // if it were.
4533 DiagKind = 4;
4534 }
4535
4536 if (DiagKind == -1)
4537 return false;
4538
4539 if (Diagnose) {
4540 if (Field) {
4541 S.Diag(Field->getLocation(),
4542 diag::note_deleted_special_member_class_subobject)
4543 << CSM << MD->getParent() << /*IsField*/true
4544 << Field << DiagKind << IsDtorCallInCtor;
4545 } else {
4546 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4547 S.Diag(Base->getLocStart(),
4548 diag::note_deleted_special_member_class_subobject)
4549 << CSM << MD->getParent() << /*IsField*/false
4550 << Base->getType() << DiagKind << IsDtorCallInCtor;
4551 }
4552
4553 if (DiagKind == 1)
4554 S.NoteDeletedFunction(Decl);
4555 // FIXME: Explain inaccessibility if DiagKind == 3.
4556 }
4557
4558 return true;
4559}
4560
Richard Smith9a561d52012-02-26 09:11:52 +00004561/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004562/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004563bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004564 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004565 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004566
4567 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004568 // -- any direct or virtual base class, or non-static data member with no
4569 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004570 // either M has no default constructor or overload resolution as applied
4571 // to M's default constructor results in an ambiguity or in a function
4572 // that is deleted or inaccessible
4573 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4574 // -- a direct or virtual base class B that cannot be copied/moved because
4575 // overload resolution, as applied to B's corresponding special member,
4576 // results in an ambiguity or a function that is deleted or inaccessible
4577 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004578 // C++11 [class.dtor]p5:
4579 // -- any direct or virtual base class [...] has a type with a destructor
4580 // that is deleted or inaccessible
4581 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004582 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004583 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004584 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004585
Richard Smith6c4c36c2012-03-30 20:53:28 +00004586 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4587 // -- any direct or virtual base class or non-static data member has a
4588 // type with a destructor that is deleted or inaccessible
4589 if (IsConstructor) {
4590 Sema::SpecialMemberOverloadResult *SMOR =
4591 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4592 false, false, false, false, false);
4593 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4594 return true;
4595 }
4596
Richard Smith9a561d52012-02-26 09:11:52 +00004597 return false;
4598}
4599
4600/// Check whether we should delete a special member function due to the class
4601/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004602bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004603 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004604 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004605}
4606
4607/// Check whether we should delete a special member function due to the class
4608/// having a particular non-static data member.
4609bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4610 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4611 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4612
4613 if (CSM == Sema::CXXDefaultConstructor) {
4614 // For a default constructor, all references must be initialized in-class
4615 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004616 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4617 if (Diagnose)
4618 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4619 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004620 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004621 }
Richard Smith79363f52012-02-27 06:07:25 +00004622 // C++11 [class.ctor]p5: any non-variant non-static data member of
4623 // const-qualified type (or array thereof) with no
4624 // brace-or-equal-initializer does not have a user-provided default
4625 // constructor.
4626 if (!inUnion() && FieldType.isConstQualified() &&
4627 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004628 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4629 if (Diagnose)
4630 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004631 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004632 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004633 }
4634
4635 if (inUnion() && !FieldType.isConstQualified())
4636 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004637 } else if (CSM == Sema::CXXCopyConstructor) {
4638 // For a copy constructor, data members must not be of rvalue reference
4639 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004640 if (FieldType->isRValueReferenceType()) {
4641 if (Diagnose)
4642 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4643 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004644 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004645 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004646 } else if (IsAssignment) {
4647 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004648 if (FieldType->isReferenceType()) {
4649 if (Diagnose)
4650 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4651 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004652 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004653 }
4654 if (!FieldRecord && FieldType.isConstQualified()) {
4655 // C++11 [class.copy]p23:
4656 // -- a non-static data member of const non-class type (or array thereof)
4657 if (Diagnose)
4658 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004659 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004660 return true;
4661 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004662 }
4663
4664 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004665 // Some additional restrictions exist on the variant members.
4666 if (!inUnion() && FieldRecord->isUnion() &&
4667 FieldRecord->isAnonymousStructOrUnion()) {
4668 bool AllVariantFieldsAreConst = true;
4669
Richard Smithdf8dc862012-03-29 19:00:10 +00004670 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004671 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4672 UE = FieldRecord->field_end();
4673 UI != UE; ++UI) {
4674 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004675
4676 if (!UnionFieldType.isConstQualified())
4677 AllVariantFieldsAreConst = false;
4678
Richard Smith9a561d52012-02-26 09:11:52 +00004679 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4680 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004681 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4682 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004683 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004684 }
4685
4686 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004687 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004688 FieldRecord->field_begin() != FieldRecord->field_end()) {
4689 if (Diagnose)
4690 S.Diag(FieldRecord->getLocation(),
4691 diag::note_deleted_default_ctor_all_const)
4692 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004693 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004694 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004695
Richard Smithdf8dc862012-03-29 19:00:10 +00004696 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004697 // This is technically non-conformant, but sanity demands it.
4698 return false;
4699 }
4700
Richard Smith517bb842012-07-18 03:51:16 +00004701 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4702 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004703 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004704 }
4705
4706 return false;
4707}
4708
4709/// C++11 [class.ctor] p5:
4710/// A defaulted default constructor for a class X is defined as deleted if
4711/// X is a union and all of its variant members are of const-qualified type.
4712bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004713 // This is a silly definition, because it gives an empty union a deleted
4714 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004715 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4716 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4717 if (Diagnose)
4718 S.Diag(MD->getParent()->getLocation(),
4719 diag::note_deleted_default_ctor_all_const)
4720 << MD->getParent() << /*not anonymous union*/0;
4721 return true;
4722 }
4723 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004724}
4725
4726/// Determine whether a defaulted special member function should be defined as
4727/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4728/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004729bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4730 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004731 if (MD->isInvalidDecl())
4732 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004733 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004734 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004735 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004736 return false;
4737
Richard Smith7d5088a2012-02-18 02:02:13 +00004738 // C++11 [expr.lambda.prim]p19:
4739 // The closure type associated with a lambda-expression has a
4740 // deleted (8.4.3) default constructor and a deleted copy
4741 // assignment operator.
4742 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004743 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4744 if (Diagnose)
4745 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004746 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004747 }
4748
Richard Smith5bdaac52012-04-02 20:59:25 +00004749 // For an anonymous struct or union, the copy and assignment special members
4750 // will never be used, so skip the check. For an anonymous union declared at
4751 // namespace scope, the constructor and destructor are used.
4752 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4753 RD->isAnonymousStructOrUnion())
4754 return false;
4755
Richard Smith6c4c36c2012-03-30 20:53:28 +00004756 // C++11 [class.copy]p7, p18:
4757 // If the class definition declares a move constructor or move assignment
4758 // operator, an implicitly declared copy constructor or copy assignment
4759 // operator is defined as deleted.
4760 if (MD->isImplicit() &&
4761 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4762 CXXMethodDecl *UserDeclaredMove = 0;
4763
4764 // In Microsoft mode, a user-declared move only causes the deletion of the
4765 // corresponding copy operation, not both copy operations.
4766 if (RD->hasUserDeclaredMoveConstructor() &&
4767 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4768 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004769
4770 // Find any user-declared move constructor.
4771 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4772 E = RD->ctor_end(); I != E; ++I) {
4773 if (I->isMoveConstructor()) {
4774 UserDeclaredMove = *I;
4775 break;
4776 }
4777 }
Richard Smith1c931be2012-04-02 18:40:40 +00004778 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004779 } else if (RD->hasUserDeclaredMoveAssignment() &&
4780 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4781 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004782
4783 // Find any user-declared move assignment operator.
4784 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4785 E = RD->method_end(); I != E; ++I) {
4786 if (I->isMoveAssignmentOperator()) {
4787 UserDeclaredMove = *I;
4788 break;
4789 }
4790 }
Richard Smith1c931be2012-04-02 18:40:40 +00004791 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004792 }
4793
4794 if (UserDeclaredMove) {
4795 Diag(UserDeclaredMove->getLocation(),
4796 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004797 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004798 << UserDeclaredMove->isMoveAssignmentOperator();
4799 return true;
4800 }
4801 }
Sean Hunte16da072011-10-10 06:18:57 +00004802
Richard Smith5bdaac52012-04-02 20:59:25 +00004803 // Do access control from the special member function
4804 ContextRAII MethodContext(*this, MD);
4805
Richard Smith9a561d52012-02-26 09:11:52 +00004806 // C++11 [class.dtor]p5:
4807 // -- for a virtual destructor, lookup of the non-array deallocation function
4808 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004809 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004810 FunctionDecl *OperatorDelete = 0;
4811 DeclarationName Name =
4812 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4813 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004814 OperatorDelete, false)) {
4815 if (Diagnose)
4816 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004817 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004818 }
Richard Smith9a561d52012-02-26 09:11:52 +00004819 }
4820
Richard Smith6c4c36c2012-03-30 20:53:28 +00004821 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004822
Sean Huntcdee3fe2011-05-11 22:34:38 +00004823 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004824 BE = RD->bases_end(); BI != BE; ++BI)
4825 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004826 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004827 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004828
4829 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004830 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004831 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004832 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004833
4834 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004835 FE = RD->field_end(); FI != FE; ++FI)
4836 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004837 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004838 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004839
Richard Smith7d5088a2012-02-18 02:02:13 +00004840 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004841 return true;
4842
4843 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004844}
4845
Richard Smithac713512012-12-08 02:53:02 +00004846/// Perform lookup for a special member of the specified kind, and determine
4847/// whether it is trivial. If the triviality can be determined without the
4848/// lookup, skip it. This is intended for use when determining whether a
4849/// special member of a containing object is trivial, and thus does not ever
4850/// perform overload resolution for default constructors.
4851///
4852/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4853/// member that was most likely to be intended to be trivial, if any.
4854static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4855 Sema::CXXSpecialMember CSM, unsigned Quals,
4856 CXXMethodDecl **Selected) {
4857 if (Selected)
4858 *Selected = 0;
4859
4860 switch (CSM) {
4861 case Sema::CXXInvalid:
4862 llvm_unreachable("not a special member");
4863
4864 case Sema::CXXDefaultConstructor:
4865 // C++11 [class.ctor]p5:
4866 // A default constructor is trivial if:
4867 // - all the [direct subobjects] have trivial default constructors
4868 //
4869 // Note, no overload resolution is performed in this case.
4870 if (RD->hasTrivialDefaultConstructor())
4871 return true;
4872
4873 if (Selected) {
4874 // If there's a default constructor which could have been trivial, dig it
4875 // out. Otherwise, if there's any user-provided default constructor, point
4876 // to that as an example of why there's not a trivial one.
4877 CXXConstructorDecl *DefCtor = 0;
4878 if (RD->needsImplicitDefaultConstructor())
4879 S.DeclareImplicitDefaultConstructor(RD);
4880 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4881 CE = RD->ctor_end(); CI != CE; ++CI) {
4882 if (!CI->isDefaultConstructor())
4883 continue;
4884 DefCtor = *CI;
4885 if (!DefCtor->isUserProvided())
4886 break;
4887 }
4888
4889 *Selected = DefCtor;
4890 }
4891
4892 return false;
4893
4894 case Sema::CXXDestructor:
4895 // C++11 [class.dtor]p5:
4896 // A destructor is trivial if:
4897 // - all the direct [subobjects] have trivial destructors
4898 if (RD->hasTrivialDestructor())
4899 return true;
4900
4901 if (Selected) {
4902 if (RD->needsImplicitDestructor())
4903 S.DeclareImplicitDestructor(RD);
4904 *Selected = RD->getDestructor();
4905 }
4906
4907 return false;
4908
4909 case Sema::CXXCopyConstructor:
4910 // C++11 [class.copy]p12:
4911 // A copy constructor is trivial if:
4912 // - the constructor selected to copy each direct [subobject] is trivial
4913 if (RD->hasTrivialCopyConstructor()) {
4914 if (Quals == Qualifiers::Const)
4915 // We must either select the trivial copy constructor or reach an
4916 // ambiguity; no need to actually perform overload resolution.
4917 return true;
4918 } else if (!Selected) {
4919 return false;
4920 }
4921 // In C++98, we are not supposed to perform overload resolution here, but we
4922 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4923 // cases like B as having a non-trivial copy constructor:
4924 // struct A { template<typename T> A(T&); };
4925 // struct B { mutable A a; };
4926 goto NeedOverloadResolution;
4927
4928 case Sema::CXXCopyAssignment:
4929 // C++11 [class.copy]p25:
4930 // A copy assignment operator is trivial if:
4931 // - the assignment operator selected to copy each direct [subobject] is
4932 // trivial
4933 if (RD->hasTrivialCopyAssignment()) {
4934 if (Quals == Qualifiers::Const)
4935 return true;
4936 } else if (!Selected) {
4937 return false;
4938 }
4939 // In C++98, we are not supposed to perform overload resolution here, but we
4940 // treat that as a language defect.
4941 goto NeedOverloadResolution;
4942
4943 case Sema::CXXMoveConstructor:
4944 case Sema::CXXMoveAssignment:
4945 NeedOverloadResolution:
4946 Sema::SpecialMemberOverloadResult *SMOR =
4947 S.LookupSpecialMember(RD, CSM,
4948 Quals & Qualifiers::Const,
4949 Quals & Qualifiers::Volatile,
4950 /*RValueThis*/false, /*ConstThis*/false,
4951 /*VolatileThis*/false);
4952
4953 // The standard doesn't describe how to behave if the lookup is ambiguous.
4954 // We treat it as not making the member non-trivial, just like the standard
4955 // mandates for the default constructor. This should rarely matter, because
4956 // the member will also be deleted.
4957 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4958 return true;
4959
4960 if (!SMOR->getMethod()) {
4961 assert(SMOR->getKind() ==
4962 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
4963 return false;
4964 }
4965
4966 // We deliberately don't check if we found a deleted special member. We're
4967 // not supposed to!
4968 if (Selected)
4969 *Selected = SMOR->getMethod();
4970 return SMOR->getMethod()->isTrivial();
4971 }
4972
4973 llvm_unreachable("unknown special method kind");
4974}
4975
Benjamin Kramera574c892013-02-15 12:30:38 +00004976static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00004977 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
4978 CI != CE; ++CI)
4979 if (!CI->isImplicit())
4980 return *CI;
4981
4982 // Look for constructor templates.
4983 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
4984 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
4985 if (CXXConstructorDecl *CD =
4986 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
4987 return CD;
4988 }
4989
4990 return 0;
4991}
4992
4993/// The kind of subobject we are checking for triviality. The values of this
4994/// enumeration are used in diagnostics.
4995enum TrivialSubobjectKind {
4996 /// The subobject is a base class.
4997 TSK_BaseClass,
4998 /// The subobject is a non-static data member.
4999 TSK_Field,
5000 /// The object is actually the complete object.
5001 TSK_CompleteObject
5002};
5003
5004/// Check whether the special member selected for a given type would be trivial.
5005static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5006 QualType SubType,
5007 Sema::CXXSpecialMember CSM,
5008 TrivialSubobjectKind Kind,
5009 bool Diagnose) {
5010 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5011 if (!SubRD)
5012 return true;
5013
5014 CXXMethodDecl *Selected;
5015 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5016 Diagnose ? &Selected : 0))
5017 return true;
5018
5019 if (Diagnose) {
5020 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5021 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5022 << Kind << SubType.getUnqualifiedType();
5023 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5024 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5025 } else if (!Selected)
5026 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5027 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5028 else if (Selected->isUserProvided()) {
5029 if (Kind == TSK_CompleteObject)
5030 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5031 << Kind << SubType.getUnqualifiedType() << CSM;
5032 else {
5033 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5034 << Kind << SubType.getUnqualifiedType() << CSM;
5035 S.Diag(Selected->getLocation(), diag::note_declared_at);
5036 }
5037 } else {
5038 if (Kind != TSK_CompleteObject)
5039 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5040 << Kind << SubType.getUnqualifiedType() << CSM;
5041
5042 // Explain why the defaulted or deleted special member isn't trivial.
5043 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5044 }
5045 }
5046
5047 return false;
5048}
5049
5050/// Check whether the members of a class type allow a special member to be
5051/// trivial.
5052static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5053 Sema::CXXSpecialMember CSM,
5054 bool ConstArg, bool Diagnose) {
5055 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5056 FE = RD->field_end(); FI != FE; ++FI) {
5057 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5058 continue;
5059
5060 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5061
5062 // Pretend anonymous struct or union members are members of this class.
5063 if (FI->isAnonymousStructOrUnion()) {
5064 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5065 CSM, ConstArg, Diagnose))
5066 return false;
5067 continue;
5068 }
5069
5070 // C++11 [class.ctor]p5:
5071 // A default constructor is trivial if [...]
5072 // -- no non-static data member of its class has a
5073 // brace-or-equal-initializer
5074 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5075 if (Diagnose)
5076 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5077 return false;
5078 }
5079
5080 // Objective C ARC 4.3.5:
5081 // [...] nontrivally ownership-qualified types are [...] not trivially
5082 // default constructible, copy constructible, move constructible, copy
5083 // assignable, move assignable, or destructible [...]
5084 if (S.getLangOpts().ObjCAutoRefCount &&
5085 FieldType.hasNonTrivialObjCLifetime()) {
5086 if (Diagnose)
5087 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5088 << RD << FieldType.getObjCLifetime();
5089 return false;
5090 }
5091
5092 if (ConstArg && !FI->isMutable())
5093 FieldType.addConst();
5094 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5095 TSK_Field, Diagnose))
5096 return false;
5097 }
5098
5099 return true;
5100}
5101
5102/// Diagnose why the specified class does not have a trivial special member of
5103/// the given kind.
5104void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5105 QualType Ty = Context.getRecordType(RD);
5106 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5107 Ty.addConst();
5108
5109 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5110 TSK_CompleteObject, /*Diagnose*/true);
5111}
5112
5113/// Determine whether a defaulted or deleted special member function is trivial,
5114/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5115/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5116bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5117 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005118 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5119
5120 CXXRecordDecl *RD = MD->getParent();
5121
5122 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005123
5124 // C++11 [class.copy]p12, p25:
5125 // A [special member] is trivial if its declared parameter type is the same
5126 // as if it had been implicitly declared [...]
5127 switch (CSM) {
5128 case CXXDefaultConstructor:
5129 case CXXDestructor:
5130 // Trivial default constructors and destructors cannot have parameters.
5131 break;
5132
5133 case CXXCopyConstructor:
5134 case CXXCopyAssignment: {
5135 // Trivial copy operations always have const, non-volatile parameter types.
5136 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005137 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005138 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5139 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5140 if (Diagnose)
5141 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5142 << Param0->getSourceRange() << Param0->getType()
5143 << Context.getLValueReferenceType(
5144 Context.getRecordType(RD).withConst());
5145 return false;
5146 }
5147 break;
5148 }
5149
5150 case CXXMoveConstructor:
5151 case CXXMoveAssignment: {
5152 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005153 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005154 const RValueReferenceType *RT =
5155 Param0->getType()->getAs<RValueReferenceType>();
5156 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5157 if (Diagnose)
5158 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5159 << Param0->getSourceRange() << Param0->getType()
5160 << Context.getRValueReferenceType(Context.getRecordType(RD));
5161 return false;
5162 }
5163 break;
5164 }
5165
5166 case CXXInvalid:
5167 llvm_unreachable("not a special member");
5168 }
5169
5170 // FIXME: We require that the parameter-declaration-clause is equivalent to
5171 // that of an implicit declaration, not just that the declared parameter type
5172 // matches, in order to prevent absuridities like a function simultaneously
5173 // being a trivial copy constructor and a non-trivial default constructor.
5174 // This issue has not yet been assigned a core issue number.
5175 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5176 if (Diagnose)
5177 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5178 diag::note_nontrivial_default_arg)
5179 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5180 return false;
5181 }
5182 if (MD->isVariadic()) {
5183 if (Diagnose)
5184 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5185 return false;
5186 }
5187
5188 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5189 // A copy/move [constructor or assignment operator] is trivial if
5190 // -- the [member] selected to copy/move each direct base class subobject
5191 // is trivial
5192 //
5193 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5194 // A [default constructor or destructor] is trivial if
5195 // -- all the direct base classes have trivial [default constructors or
5196 // destructors]
5197 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5198 BE = RD->bases_end(); BI != BE; ++BI)
5199 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5200 ConstArg ? BI->getType().withConst()
5201 : BI->getType(),
5202 CSM, TSK_BaseClass, Diagnose))
5203 return false;
5204
5205 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5206 // A copy/move [constructor or assignment operator] for a class X is
5207 // trivial if
5208 // -- for each non-static data member of X that is of class type (or array
5209 // thereof), the constructor selected to copy/move that member is
5210 // trivial
5211 //
5212 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5213 // A [default constructor or destructor] is trivial if
5214 // -- for all of the non-static data members of its class that are of class
5215 // type (or array thereof), each such class has a trivial [default
5216 // constructor or destructor]
5217 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5218 return false;
5219
5220 // C++11 [class.dtor]p5:
5221 // A destructor is trivial if [...]
5222 // -- the destructor is not virtual
5223 if (CSM == CXXDestructor && MD->isVirtual()) {
5224 if (Diagnose)
5225 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5226 return false;
5227 }
5228
5229 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5230 // A [special member] for class X is trivial if [...]
5231 // -- class X has no virtual functions and no virtual base classes
5232 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5233 if (!Diagnose)
5234 return false;
5235
5236 if (RD->getNumVBases()) {
5237 // Check for virtual bases. We already know that the corresponding
5238 // member in all bases is trivial, so vbases must all be direct.
5239 CXXBaseSpecifier &BS = *RD->vbases_begin();
5240 assert(BS.isVirtual());
5241 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5242 return false;
5243 }
5244
5245 // Must have a virtual method.
5246 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5247 ME = RD->method_end(); MI != ME; ++MI) {
5248 if (MI->isVirtual()) {
5249 SourceLocation MLoc = MI->getLocStart();
5250 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5251 return false;
5252 }
5253 }
5254
5255 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5256 }
5257
5258 // Looks like it's trivial!
5259 return true;
5260}
5261
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005262/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005263namespace {
5264 struct FindHiddenVirtualMethodData {
5265 Sema *S;
5266 CXXMethodDecl *Method;
5267 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005268 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005269 };
5270}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005271
David Blaikie5f750682012-10-19 00:53:08 +00005272/// \brief Check whether any most overriden method from MD in Methods
5273static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5274 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5275 if (MD->size_overridden_methods() == 0)
5276 return Methods.count(MD->getCanonicalDecl());
5277 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5278 E = MD->end_overridden_methods();
5279 I != E; ++I)
5280 if (CheckMostOverridenMethods(*I, Methods))
5281 return true;
5282 return false;
5283}
5284
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005285/// \brief Member lookup function that determines whether a given C++
5286/// method overloads virtual methods in a base class without overriding any,
5287/// to be used with CXXRecordDecl::lookupInBases().
5288static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5289 CXXBasePath &Path,
5290 void *UserData) {
5291 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5292
5293 FindHiddenVirtualMethodData &Data
5294 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5295
5296 DeclarationName Name = Data.Method->getDeclName();
5297 assert(Name.getNameKind() == DeclarationName::Identifier);
5298
5299 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005300 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005301 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005302 !Path.Decls.empty();
5303 Path.Decls = Path.Decls.slice(1)) {
5304 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005305 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005306 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005307 foundSameNameMethod = true;
5308 // Interested only in hidden virtual methods.
5309 if (!MD->isVirtual())
5310 continue;
5311 // If the method we are checking overrides a method from its base
5312 // don't warn about the other overloaded methods.
5313 if (!Data.S->IsOverload(Data.Method, MD, false))
5314 return true;
5315 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005316 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005317 overloadedMethods.push_back(MD);
5318 }
5319 }
5320
5321 if (foundSameNameMethod)
5322 Data.OverloadedMethods.append(overloadedMethods.begin(),
5323 overloadedMethods.end());
5324 return foundSameNameMethod;
5325}
5326
David Blaikie5f750682012-10-19 00:53:08 +00005327/// \brief Add the most overriden methods from MD to Methods
5328static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5329 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5330 if (MD->size_overridden_methods() == 0)
5331 Methods.insert(MD->getCanonicalDecl());
5332 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5333 E = MD->end_overridden_methods();
5334 I != E; ++I)
5335 AddMostOverridenMethods(*I, Methods);
5336}
5337
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005338/// \brief See if a method overloads virtual methods in a base class without
5339/// overriding any.
5340void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5341 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005342 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005343 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005344 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005345 return;
5346
5347 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5348 /*bool RecordPaths=*/false,
5349 /*bool DetectVirtual=*/false);
5350 FindHiddenVirtualMethodData Data;
5351 Data.Method = MD;
5352 Data.S = this;
5353
5354 // Keep the base methods that were overriden or introduced in the subclass
5355 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005356 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5357 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5358 NamedDecl *ND = *I;
5359 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005360 ND = shad->getTargetDecl();
5361 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5362 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005363 }
5364
5365 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5366 !Data.OverloadedMethods.empty()) {
5367 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5368 << MD << (Data.OverloadedMethods.size() > 1);
5369
5370 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5371 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5372 Diag(overloadedMD->getLocation(),
5373 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5374 }
5375 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005376}
5377
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005378void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005379 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005380 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005381 SourceLocation RBrac,
5382 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005383 if (!TagDecl)
5384 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005385
Douglas Gregor42af25f2009-05-11 19:58:34 +00005386 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005387
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005388 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5389 if (l->getKind() != AttributeList::AT_Visibility)
5390 continue;
5391 l->setInvalid();
5392 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5393 l->getName();
5394 }
5395
David Blaikie77b6de02011-09-22 02:58:26 +00005396 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005397 // strict aliasing violation!
5398 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005399 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005400
Douglas Gregor23c94db2010-07-02 17:43:08 +00005401 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005402 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005403}
5404
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005405/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5406/// special functions, such as the default constructor, copy
5407/// constructor, or destructor, to the given C++ class (C++
5408/// [special]p1). This routine can only be executed just before the
5409/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005410void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005411 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005412 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005413
Richard Smithbc2a35d2012-12-08 08:32:28 +00005414 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005415 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005416
Richard Smithbc2a35d2012-12-08 08:32:28 +00005417 // If the properties or semantics of the copy constructor couldn't be
5418 // determined while the class was being declared, force a declaration
5419 // of it now.
5420 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5421 DeclareImplicitCopyConstructor(ClassDecl);
5422 }
5423
Richard Smith80ad52f2013-01-02 11:42:31 +00005424 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005425 ++ASTContext::NumImplicitMoveConstructors;
5426
Richard Smithbc2a35d2012-12-08 08:32:28 +00005427 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5428 DeclareImplicitMoveConstructor(ClassDecl);
5429 }
5430
Douglas Gregora376d102010-07-02 21:50:04 +00005431 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5432 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005433
5434 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005435 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005436 // it shows up in the right place in the vtable and that we diagnose
5437 // problems with the implicit exception specification.
5438 if (ClassDecl->isDynamicClass() ||
5439 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005440 DeclareImplicitCopyAssignment(ClassDecl);
5441 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005442
Richard Smith80ad52f2013-01-02 11:42:31 +00005443 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005444 ++ASTContext::NumImplicitMoveAssignmentOperators;
5445
5446 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005447 if (ClassDecl->isDynamicClass() ||
5448 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005449 DeclareImplicitMoveAssignment(ClassDecl);
5450 }
5451
Douglas Gregor4923aa22010-07-02 20:37:36 +00005452 if (!ClassDecl->hasUserDeclaredDestructor()) {
5453 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005454
5455 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005456 // have to declare the destructor immediately. This ensures that, e.g., it
5457 // shows up in the right place in the vtable and that we diagnose problems
5458 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005459 if (ClassDecl->isDynamicClass() ||
5460 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005461 DeclareImplicitDestructor(ClassDecl);
5462 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005463}
5464
Francois Pichet8387e2a2011-04-22 22:18:13 +00005465void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5466 if (!D)
5467 return;
5468
5469 int NumParamList = D->getNumTemplateParameterLists();
5470 for (int i = 0; i < NumParamList; i++) {
5471 TemplateParameterList* Params = D->getTemplateParameterList(i);
5472 for (TemplateParameterList::iterator Param = Params->begin(),
5473 ParamEnd = Params->end();
5474 Param != ParamEnd; ++Param) {
5475 NamedDecl *Named = cast<NamedDecl>(*Param);
5476 if (Named->getDeclName()) {
5477 S->AddDecl(Named);
5478 IdResolver.AddDecl(Named);
5479 }
5480 }
5481 }
5482}
5483
John McCalld226f652010-08-21 09:40:31 +00005484void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005485 if (!D)
5486 return;
5487
5488 TemplateParameterList *Params = 0;
5489 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5490 Params = Template->getTemplateParameters();
5491 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5492 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5493 Params = PartialSpec->getTemplateParameters();
5494 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005495 return;
5496
Douglas Gregor6569d682009-05-27 23:11:45 +00005497 for (TemplateParameterList::iterator Param = Params->begin(),
5498 ParamEnd = Params->end();
5499 Param != ParamEnd; ++Param) {
5500 NamedDecl *Named = cast<NamedDecl>(*Param);
5501 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005502 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005503 IdResolver.AddDecl(Named);
5504 }
5505 }
5506}
5507
John McCalld226f652010-08-21 09:40:31 +00005508void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005509 if (!RecordD) return;
5510 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005511 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005512 PushDeclContext(S, Record);
5513}
5514
John McCalld226f652010-08-21 09:40:31 +00005515void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005516 if (!RecordD) return;
5517 PopDeclContext();
5518}
5519
Douglas Gregor72b505b2008-12-16 21:30:33 +00005520/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5521/// parsing a top-level (non-nested) C++ class, and we are now
5522/// parsing those parts of the given Method declaration that could
5523/// not be parsed earlier (C++ [class.mem]p2), such as default
5524/// arguments. This action should enter the scope of the given
5525/// Method declaration as if we had just parsed the qualified method
5526/// name. However, it should not bring the parameters into scope;
5527/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005528void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005529}
5530
5531/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5532/// C++ method declaration. We're (re-)introducing the given
5533/// function parameter into scope for use in parsing later parts of
5534/// the method declaration. For example, we could see an
5535/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005536void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005537 if (!ParamD)
5538 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005539
John McCalld226f652010-08-21 09:40:31 +00005540 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005541
5542 // If this parameter has an unparsed default argument, clear it out
5543 // to make way for the parsed default argument.
5544 if (Param->hasUnparsedDefaultArg())
5545 Param->setDefaultArg(0);
5546
John McCalld226f652010-08-21 09:40:31 +00005547 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005548 if (Param->getDeclName())
5549 IdResolver.AddDecl(Param);
5550}
5551
5552/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5553/// processing the delayed method declaration for Method. The method
5554/// declaration is now considered finished. There may be a separate
5555/// ActOnStartOfFunctionDef action later (not necessarily
5556/// immediately!) for this method, if it was also defined inside the
5557/// class body.
John McCalld226f652010-08-21 09:40:31 +00005558void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005559 if (!MethodD)
5560 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005561
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005562 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005563
John McCalld226f652010-08-21 09:40:31 +00005564 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005565
5566 // Now that we have our default arguments, check the constructor
5567 // again. It could produce additional diagnostics or affect whether
5568 // the class has implicitly-declared destructors, among other
5569 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005570 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5571 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005572
5573 // Check the default arguments, which we may have added.
5574 if (!Method->isInvalidDecl())
5575 CheckCXXDefaultArguments(Method);
5576}
5577
Douglas Gregor42a552f2008-11-05 20:51:48 +00005578/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005579/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005580/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005581/// emit diagnostics and set the invalid bit to true. In any case, the type
5582/// will be updated to reflect a well-formed type for the constructor and
5583/// returned.
5584QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005585 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005586 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005587
5588 // C++ [class.ctor]p3:
5589 // A constructor shall not be virtual (10.3) or static (9.4). A
5590 // constructor can be invoked for a const, volatile or const
5591 // volatile object. A constructor shall not be declared const,
5592 // volatile, or const volatile (9.3.2).
5593 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005594 if (!D.isInvalidType())
5595 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5596 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5597 << SourceRange(D.getIdentifierLoc());
5598 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005599 }
John McCalld931b082010-08-26 03:08:43 +00005600 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005601 if (!D.isInvalidType())
5602 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5603 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5604 << SourceRange(D.getIdentifierLoc());
5605 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005606 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005607 }
Mike Stump1eb44332009-09-09 15:08:12 +00005608
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005609 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005610 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005611 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005612 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5613 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005614 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005615 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5616 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005617 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005618 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5619 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005620 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005621 }
Mike Stump1eb44332009-09-09 15:08:12 +00005622
Douglas Gregorc938c162011-01-26 05:01:58 +00005623 // C++0x [class.ctor]p4:
5624 // A constructor shall not be declared with a ref-qualifier.
5625 if (FTI.hasRefQualifier()) {
5626 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5627 << FTI.RefQualifierIsLValueRef
5628 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5629 D.setInvalidType();
5630 }
5631
Douglas Gregor42a552f2008-11-05 20:51:48 +00005632 // Rebuild the function type "R" without any type qualifiers (in
5633 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005634 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005635 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005636 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5637 return R;
5638
5639 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5640 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005641 EPI.RefQualifier = RQ_None;
5642
Chris Lattner65401802009-04-25 08:28:21 +00005643 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005644 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005645}
5646
Douglas Gregor72b505b2008-12-16 21:30:33 +00005647/// CheckConstructor - Checks a fully-formed constructor for
5648/// well-formedness, issuing any diagnostics required. Returns true if
5649/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005650void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005651 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005652 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5653 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005654 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005655
5656 // C++ [class.copy]p3:
5657 // A declaration of a constructor for a class X is ill-formed if
5658 // its first parameter is of type (optionally cv-qualified) X and
5659 // either there are no other parameters or else all other
5660 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005661 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005662 ((Constructor->getNumParams() == 1) ||
5663 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005664 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5665 Constructor->getTemplateSpecializationKind()
5666 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005667 QualType ParamType = Constructor->getParamDecl(0)->getType();
5668 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5669 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005670 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005671 const char *ConstRef
5672 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5673 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005674 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005675 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005676
5677 // FIXME: Rather that making the constructor invalid, we should endeavor
5678 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005679 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005680 }
5681 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005682}
5683
John McCall15442822010-08-04 01:04:25 +00005684/// CheckDestructor - Checks a fully-formed destructor definition for
5685/// well-formedness, issuing any diagnostics required. Returns true
5686/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005687bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005688 CXXRecordDecl *RD = Destructor->getParent();
5689
5690 if (Destructor->isVirtual()) {
5691 SourceLocation Loc;
5692
5693 if (!Destructor->isImplicit())
5694 Loc = Destructor->getLocation();
5695 else
5696 Loc = RD->getLocation();
5697
5698 // If we have a virtual destructor, look up the deallocation function
5699 FunctionDecl *OperatorDelete = 0;
5700 DeclarationName Name =
5701 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005702 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005703 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005704
Eli Friedman5f2987c2012-02-02 03:46:19 +00005705 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005706
5707 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005708 }
Anders Carlsson37909802009-11-30 21:24:50 +00005709
5710 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005711}
5712
Mike Stump1eb44332009-09-09 15:08:12 +00005713static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005714FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5715 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5716 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005717 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005718}
5719
Douglas Gregor42a552f2008-11-05 20:51:48 +00005720/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5721/// the well-formednes of the destructor declarator @p D with type @p
5722/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005723/// emit diagnostics and set the declarator to invalid. Even if this happens,
5724/// will be updated to reflect a well-formed type for the destructor and
5725/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005726QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005727 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005728 // C++ [class.dtor]p1:
5729 // [...] A typedef-name that names a class is a class-name
5730 // (7.1.3); however, a typedef-name that names a class shall not
5731 // be used as the identifier in the declarator for a destructor
5732 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005733 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005734 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005735 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005736 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005737 else if (const TemplateSpecializationType *TST =
5738 DeclaratorType->getAs<TemplateSpecializationType>())
5739 if (TST->isTypeAlias())
5740 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5741 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005742
5743 // C++ [class.dtor]p2:
5744 // A destructor is used to destroy objects of its class type. A
5745 // destructor takes no parameters, and no return type can be
5746 // specified for it (not even void). The address of a destructor
5747 // shall not be taken. A destructor shall not be static. A
5748 // destructor can be invoked for a const, volatile or const
5749 // volatile object. A destructor shall not be declared const,
5750 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005751 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005752 if (!D.isInvalidType())
5753 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5754 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005755 << SourceRange(D.getIdentifierLoc())
5756 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5757
John McCalld931b082010-08-26 03:08:43 +00005758 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005759 }
Chris Lattner65401802009-04-25 08:28:21 +00005760 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005761 // Destructors don't have return types, but the parser will
5762 // happily parse something like:
5763 //
5764 // class X {
5765 // float ~X();
5766 // };
5767 //
5768 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005769 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5770 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5771 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005772 }
Mike Stump1eb44332009-09-09 15:08:12 +00005773
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005774 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005775 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005776 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005777 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5778 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005779 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005780 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5781 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005782 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005783 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5784 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005785 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005786 }
5787
Douglas Gregorc938c162011-01-26 05:01:58 +00005788 // C++0x [class.dtor]p2:
5789 // A destructor shall not be declared with a ref-qualifier.
5790 if (FTI.hasRefQualifier()) {
5791 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5792 << FTI.RefQualifierIsLValueRef
5793 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5794 D.setInvalidType();
5795 }
5796
Douglas Gregor42a552f2008-11-05 20:51:48 +00005797 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005798 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005799 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5800
5801 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005802 FTI.freeArgs();
5803 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005804 }
5805
Mike Stump1eb44332009-09-09 15:08:12 +00005806 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005807 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005808 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005809 D.setInvalidType();
5810 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005811
5812 // Rebuild the function type "R" without any type qualifiers or
5813 // parameters (in case any of the errors above fired) and with
5814 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005815 // types.
John McCalle23cf432010-12-14 08:05:40 +00005816 if (!D.isInvalidType())
5817 return R;
5818
Douglas Gregord92ec472010-07-01 05:10:53 +00005819 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005820 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5821 EPI.Variadic = false;
5822 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005823 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005824 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005825}
5826
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005827/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5828/// well-formednes of the conversion function declarator @p D with
5829/// type @p R. If there are any errors in the declarator, this routine
5830/// will emit diagnostics and return true. Otherwise, it will return
5831/// false. Either way, the type @p R will be updated to reflect a
5832/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005833void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005834 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005835 // C++ [class.conv.fct]p1:
5836 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005837 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005838 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005839 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005840 if (!D.isInvalidType())
5841 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5842 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5843 << SourceRange(D.getIdentifierLoc());
5844 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005845 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005846 }
John McCalla3f81372010-04-13 00:04:31 +00005847
5848 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5849
Chris Lattner6e475012009-04-25 08:35:12 +00005850 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005851 // Conversion functions don't have return types, but the parser will
5852 // happily parse something like:
5853 //
5854 // class X {
5855 // float operator bool();
5856 // };
5857 //
5858 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005859 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5860 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5861 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005862 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005863 }
5864
John McCalla3f81372010-04-13 00:04:31 +00005865 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5866
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005867 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005868 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005869 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5870
5871 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005872 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005873 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005874 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005875 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005876 D.setInvalidType();
5877 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005878
John McCalla3f81372010-04-13 00:04:31 +00005879 // Diagnose "&operator bool()" and other such nonsense. This
5880 // is actually a gcc extension which we don't support.
5881 if (Proto->getResultType() != ConvType) {
5882 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5883 << Proto->getResultType();
5884 D.setInvalidType();
5885 ConvType = Proto->getResultType();
5886 }
5887
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005888 // C++ [class.conv.fct]p4:
5889 // The conversion-type-id shall not represent a function type nor
5890 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005891 if (ConvType->isArrayType()) {
5892 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5893 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005894 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005895 } else if (ConvType->isFunctionType()) {
5896 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5897 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005898 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005899 }
5900
5901 // Rebuild the function type "R" without any parameters (in case any
5902 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005903 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005904 if (D.isInvalidType())
5905 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005906
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005907 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005908 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005909 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005910 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005911 diag::warn_cxx98_compat_explicit_conversion_functions :
5912 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005913 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005914}
5915
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005916/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5917/// the declaration of the given C++ conversion function. This routine
5918/// is responsible for recording the conversion function in the C++
5919/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005920Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005921 assert(Conversion && "Expected to receive a conversion function declaration");
5922
Douglas Gregor9d350972008-12-12 08:25:50 +00005923 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005924
5925 // Make sure we aren't redeclaring the conversion function.
5926 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005927
5928 // C++ [class.conv.fct]p1:
5929 // [...] A conversion function is never used to convert a
5930 // (possibly cv-qualified) object to the (possibly cv-qualified)
5931 // same object type (or a reference to it), to a (possibly
5932 // cv-qualified) base class of that type (or a reference to it),
5933 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005934 // FIXME: Suppress this warning if the conversion function ends up being a
5935 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005936 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005937 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005938 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005939 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005940 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5941 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005942 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005943 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005944 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5945 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005946 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005947 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005948 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005949 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005950 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005951 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005952 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005953 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005954 }
5955
Douglas Gregore80622f2010-09-29 04:25:11 +00005956 if (FunctionTemplateDecl *ConversionTemplate
5957 = Conversion->getDescribedFunctionTemplate())
5958 return ConversionTemplate;
5959
John McCalld226f652010-08-21 09:40:31 +00005960 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005961}
5962
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005963//===----------------------------------------------------------------------===//
5964// Namespace Handling
5965//===----------------------------------------------------------------------===//
5966
Richard Smithd1a55a62012-10-04 22:13:39 +00005967/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
5968/// reopened.
5969static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
5970 SourceLocation Loc,
5971 IdentifierInfo *II, bool *IsInline,
5972 NamespaceDecl *PrevNS) {
5973 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00005974
Richard Smithc969e6a2012-10-05 01:46:25 +00005975 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
5976 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
5977 // inline namespaces, with the intention of bringing names into namespace std.
5978 //
5979 // We support this just well enough to get that case working; this is not
5980 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00005981 if (*IsInline && II && II->getName().startswith("__atomic") &&
5982 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00005983 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00005984 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
5985 NS = NS->getPreviousDecl())
5986 NS->setInline(*IsInline);
5987 // Patch up the lookup table for the containing namespace. This isn't really
5988 // correct, but it's good enough for this particular case.
5989 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
5990 E = PrevNS->decls_end(); I != E; ++I)
5991 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
5992 PrevNS->getParent()->makeDeclVisibleInContext(ND);
5993 return;
5994 }
5995
5996 if (PrevNS->isInline())
5997 // The user probably just forgot the 'inline', so suggest that it
5998 // be added back.
5999 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6000 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6001 else
6002 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6003 << IsInline;
6004
6005 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6006 *IsInline = PrevNS->isInline();
6007}
John McCallea318642010-08-26 09:15:37 +00006008
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006009/// ActOnStartNamespaceDef - This is called at the start of a namespace
6010/// definition.
John McCalld226f652010-08-21 09:40:31 +00006011Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006012 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006013 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006014 SourceLocation IdentLoc,
6015 IdentifierInfo *II,
6016 SourceLocation LBrace,
6017 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006018 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6019 // For anonymous namespace, take the location of the left brace.
6020 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006021 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006022 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006023 bool IsStd = false;
6024 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006025 Scope *DeclRegionScope = NamespcScope->getParent();
6026
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006027 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006028 if (II) {
6029 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006030 // The identifier in an original-namespace-definition shall not
6031 // have been previously defined in the declarative region in
6032 // which the original-namespace-definition appears. The
6033 // identifier in an original-namespace-definition is the name of
6034 // the namespace. Subsequently in that declarative region, it is
6035 // treated as an original-namespace-name.
6036 //
6037 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006038 // look through using directives, just look for any ordinary names.
6039
6040 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006041 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6042 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006043 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006044 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6045 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6046 ++I) {
6047 if ((*I)->getIdentifierNamespace() & IDNS) {
6048 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006049 break;
6050 }
6051 }
6052
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006053 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6054
6055 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006056 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006057 if (IsInline != PrevNS->isInline())
6058 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6059 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006060 } else if (PrevDecl) {
6061 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006062 Diag(Loc, diag::err_redefinition_different_kind)
6063 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006064 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006065 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006066 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006067 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006068 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006069 // This is the first "real" definition of the namespace "std", so update
6070 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006071 PrevNS = getStdNamespace();
6072 IsStd = true;
6073 AddToKnown = !IsInline;
6074 } else {
6075 // We've seen this namespace for the first time.
6076 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006077 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006078 } else {
John McCall9aeed322009-10-01 00:25:31 +00006079 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006080
6081 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006082 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006083 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006084 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006085 } else {
6086 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006087 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006088 }
6089
Richard Smithd1a55a62012-10-04 22:13:39 +00006090 if (PrevNS && IsInline != PrevNS->isInline())
6091 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6092 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006093 }
6094
6095 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6096 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006097 if (IsInvalid)
6098 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006099
6100 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006101
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006102 // FIXME: Should we be merging attributes?
6103 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006104 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006105
6106 if (IsStd)
6107 StdNamespace = Namespc;
6108 if (AddToKnown)
6109 KnownNamespaces[Namespc] = false;
6110
6111 if (II) {
6112 PushOnScopeChains(Namespc, DeclRegionScope);
6113 } else {
6114 // Link the anonymous namespace into its parent.
6115 DeclContext *Parent = CurContext->getRedeclContext();
6116 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6117 TU->setAnonymousNamespace(Namespc);
6118 } else {
6119 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006120 }
John McCall9aeed322009-10-01 00:25:31 +00006121
Douglas Gregora4181472010-03-24 00:46:35 +00006122 CurContext->addDecl(Namespc);
6123
John McCall9aeed322009-10-01 00:25:31 +00006124 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6125 // behaves as if it were replaced by
6126 // namespace unique { /* empty body */ }
6127 // using namespace unique;
6128 // namespace unique { namespace-body }
6129 // where all occurrences of 'unique' in a translation unit are
6130 // replaced by the same identifier and this identifier differs
6131 // from all other identifiers in the entire program.
6132
6133 // We just create the namespace with an empty name and then add an
6134 // implicit using declaration, just like the standard suggests.
6135 //
6136 // CodeGen enforces the "universally unique" aspect by giving all
6137 // declarations semantically contained within an anonymous
6138 // namespace internal linkage.
6139
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006140 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006141 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006142 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006143 /* 'using' */ LBrace,
6144 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006145 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006146 /* identifier */ SourceLocation(),
6147 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006148 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006149 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006150 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006151 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006152 }
6153
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006154 ActOnDocumentableDecl(Namespc);
6155
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006156 // Although we could have an invalid decl (i.e. the namespace name is a
6157 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006158 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6159 // for the namespace has the declarations that showed up in that particular
6160 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006161 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006162 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006163}
6164
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006165/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6166/// is a namespace alias, returns the namespace it points to.
6167static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6168 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6169 return AD->getNamespace();
6170 return dyn_cast_or_null<NamespaceDecl>(D);
6171}
6172
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006173/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6174/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006175void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006176 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6177 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006178 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006179 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006180 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006181 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006182}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006183
John McCall384aff82010-08-25 07:42:41 +00006184CXXRecordDecl *Sema::getStdBadAlloc() const {
6185 return cast_or_null<CXXRecordDecl>(
6186 StdBadAlloc.get(Context.getExternalSource()));
6187}
6188
6189NamespaceDecl *Sema::getStdNamespace() const {
6190 return cast_or_null<NamespaceDecl>(
6191 StdNamespace.get(Context.getExternalSource()));
6192}
6193
Douglas Gregor66992202010-06-29 17:53:46 +00006194/// \brief Retrieve the special "std" namespace, which may require us to
6195/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006196NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006197 if (!StdNamespace) {
6198 // The "std" namespace has not yet been defined, so build one implicitly.
6199 StdNamespace = NamespaceDecl::Create(Context,
6200 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006201 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006202 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006203 &PP.getIdentifierTable().get("std"),
6204 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006205 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006206 }
6207
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006208 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006209}
6210
Sebastian Redl395e04d2012-01-17 22:49:33 +00006211bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006212 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006213 "Looking for std::initializer_list outside of C++.");
6214
6215 // We're looking for implicit instantiations of
6216 // template <typename E> class std::initializer_list.
6217
6218 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6219 return false;
6220
Sebastian Redl84760e32012-01-17 22:49:58 +00006221 ClassTemplateDecl *Template = 0;
6222 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006223
Sebastian Redl84760e32012-01-17 22:49:58 +00006224 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006225
Sebastian Redl84760e32012-01-17 22:49:58 +00006226 ClassTemplateSpecializationDecl *Specialization =
6227 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6228 if (!Specialization)
6229 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006230
Sebastian Redl84760e32012-01-17 22:49:58 +00006231 Template = Specialization->getSpecializedTemplate();
6232 Arguments = Specialization->getTemplateArgs().data();
6233 } else if (const TemplateSpecializationType *TST =
6234 Ty->getAs<TemplateSpecializationType>()) {
6235 Template = dyn_cast_or_null<ClassTemplateDecl>(
6236 TST->getTemplateName().getAsTemplateDecl());
6237 Arguments = TST->getArgs();
6238 }
6239 if (!Template)
6240 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006241
6242 if (!StdInitializerList) {
6243 // Haven't recognized std::initializer_list yet, maybe this is it.
6244 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6245 if (TemplateClass->getIdentifier() !=
6246 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006247 !getStdNamespace()->InEnclosingNamespaceSetOf(
6248 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006249 return false;
6250 // This is a template called std::initializer_list, but is it the right
6251 // template?
6252 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006253 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006254 return false;
6255 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6256 return false;
6257
6258 // It's the right template.
6259 StdInitializerList = Template;
6260 }
6261
6262 if (Template != StdInitializerList)
6263 return false;
6264
6265 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006266 if (Element)
6267 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006268 return true;
6269}
6270
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006271static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6272 NamespaceDecl *Std = S.getStdNamespace();
6273 if (!Std) {
6274 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6275 return 0;
6276 }
6277
6278 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6279 Loc, Sema::LookupOrdinaryName);
6280 if (!S.LookupQualifiedName(Result, Std)) {
6281 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6282 return 0;
6283 }
6284 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6285 if (!Template) {
6286 Result.suppressDiagnostics();
6287 // We found something weird. Complain about the first thing we found.
6288 NamedDecl *Found = *Result.begin();
6289 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6290 return 0;
6291 }
6292
6293 // We found some template called std::initializer_list. Now verify that it's
6294 // correct.
6295 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006296 if (Params->getMinRequiredArguments() != 1 ||
6297 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006298 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6299 return 0;
6300 }
6301
6302 return Template;
6303}
6304
6305QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6306 if (!StdInitializerList) {
6307 StdInitializerList = LookupStdInitializerList(*this, Loc);
6308 if (!StdInitializerList)
6309 return QualType();
6310 }
6311
6312 TemplateArgumentListInfo Args(Loc, Loc);
6313 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6314 Context.getTrivialTypeSourceInfo(Element,
6315 Loc)));
6316 return Context.getCanonicalType(
6317 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6318}
6319
Sebastian Redl98d36062012-01-17 22:50:14 +00006320bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6321 // C++ [dcl.init.list]p2:
6322 // A constructor is an initializer-list constructor if its first parameter
6323 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6324 // std::initializer_list<E> for some type E, and either there are no other
6325 // parameters or else all other parameters have default arguments.
6326 if (Ctor->getNumParams() < 1 ||
6327 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6328 return false;
6329
6330 QualType ArgType = Ctor->getParamDecl(0)->getType();
6331 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6332 ArgType = RT->getPointeeType().getUnqualifiedType();
6333
6334 return isStdInitializerList(ArgType, 0);
6335}
6336
Douglas Gregor9172aa62011-03-26 22:25:30 +00006337/// \brief Determine whether a using statement is in a context where it will be
6338/// apply in all contexts.
6339static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6340 switch (CurContext->getDeclKind()) {
6341 case Decl::TranslationUnit:
6342 return true;
6343 case Decl::LinkageSpec:
6344 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6345 default:
6346 return false;
6347 }
6348}
6349
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006350namespace {
6351
6352// Callback to only accept typo corrections that are namespaces.
6353class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6354 public:
6355 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6356 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6357 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6358 }
6359 return false;
6360 }
6361};
6362
6363}
6364
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006365static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6366 CXXScopeSpec &SS,
6367 SourceLocation IdentLoc,
6368 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006369 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006370 R.clear();
6371 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006372 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006373 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006374 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6375 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006376 if (DeclContext *DC = S.computeDeclContext(SS, false))
6377 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6378 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006379 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6380 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006381 else
6382 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6383 << Ident << CorrectedQuotedStr
6384 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006385
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006386 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6387 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006388
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006389 R.addDecl(Corrected.getCorrectionDecl());
6390 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006391 }
6392 return false;
6393}
6394
John McCalld226f652010-08-21 09:40:31 +00006395Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006396 SourceLocation UsingLoc,
6397 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006398 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006399 SourceLocation IdentLoc,
6400 IdentifierInfo *NamespcName,
6401 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006402 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6403 assert(NamespcName && "Invalid NamespcName.");
6404 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006405
6406 // This can only happen along a recovery path.
6407 while (S->getFlags() & Scope::TemplateParamScope)
6408 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006409 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006410
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006411 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006412 NestedNameSpecifier *Qualifier = 0;
6413 if (SS.isSet())
6414 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6415
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006416 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006417 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6418 LookupParsedName(R, S, &SS);
6419 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006420 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006421
Douglas Gregor66992202010-06-29 17:53:46 +00006422 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006423 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006424 // Allow "using namespace std;" or "using namespace ::std;" even if
6425 // "std" hasn't been defined yet, for GCC compatibility.
6426 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6427 NamespcName->isStr("std")) {
6428 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006429 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006430 R.resolveKind();
6431 }
6432 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006433 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006434 }
6435
John McCallf36e02d2009-10-09 21:13:30 +00006436 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006437 NamedDecl *Named = R.getFoundDecl();
6438 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6439 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006440 // C++ [namespace.udir]p1:
6441 // A using-directive specifies that the names in the nominated
6442 // namespace can be used in the scope in which the
6443 // using-directive appears after the using-directive. During
6444 // unqualified name lookup (3.4.1), the names appear as if they
6445 // were declared in the nearest enclosing namespace which
6446 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006447 // namespace. [Note: in this context, "contains" means "contains
6448 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006449
6450 // Find enclosing context containing both using-directive and
6451 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006452 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006453 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6454 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6455 CommonAncestor = CommonAncestor->getParent();
6456
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006457 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006458 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006459 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006460
Douglas Gregor9172aa62011-03-26 22:25:30 +00006461 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006462 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006463 Diag(IdentLoc, diag::warn_using_directive_in_header);
6464 }
6465
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006466 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006467 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006468 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006469 }
6470
Richard Smith6b3d3e52013-02-20 19:22:51 +00006471 if (UDir)
6472 ProcessDeclAttributeList(S, UDir, AttrList);
6473
John McCalld226f652010-08-21 09:40:31 +00006474 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006475}
6476
6477void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006478 // If the scope has an associated entity and the using directive is at
6479 // namespace or translation unit scope, add the UsingDirectiveDecl into
6480 // its lookup structure so qualified name lookup can find it.
6481 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6482 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006483 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006484 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006485 // Otherwise, it is at block sope. The using-directives will affect lookup
6486 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006487 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006488}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006489
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006490
John McCalld226f652010-08-21 09:40:31 +00006491Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006492 AccessSpecifier AS,
6493 bool HasUsingKeyword,
6494 SourceLocation UsingLoc,
6495 CXXScopeSpec &SS,
6496 UnqualifiedId &Name,
6497 AttributeList *AttrList,
6498 bool IsTypeName,
6499 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006500 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006501
Douglas Gregor12c118a2009-11-04 16:30:06 +00006502 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006503 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006504 case UnqualifiedId::IK_Identifier:
6505 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006506 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006507 case UnqualifiedId::IK_ConversionFunctionId:
6508 break;
6509
6510 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006511 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006512 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006513 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006514 getLangOpts().CPlusPlus11 ?
Richard Smitha1366cb2012-04-27 19:33:05 +00006515 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
6516 // instead once inheriting constructors work.
6517 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00006518 diag::err_using_decl_constructor)
6519 << SS.getRange();
6520
Richard Smith80ad52f2013-01-02 11:42:31 +00006521 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006522
John McCalld226f652010-08-21 09:40:31 +00006523 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006524
6525 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006526 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006527 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006528 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006529
6530 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006531 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006532 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006533 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006534 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006535
6536 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6537 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006538 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006539 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006540
John McCall60fa3cf2009-12-11 02:10:03 +00006541 // Warn about using declarations.
6542 // TODO: store that the declaration was written without 'using' and
6543 // talk about access decls instead of using decls in the
6544 // diagnostics.
6545 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006546 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006547
6548 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006549 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006550 }
6551
Douglas Gregor56c04582010-12-16 00:46:58 +00006552 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6553 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6554 return 0;
6555
John McCall9488ea12009-11-17 05:59:44 +00006556 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006557 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006558 /* IsInstantiation */ false,
6559 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006560 if (UD)
6561 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006562
John McCalld226f652010-08-21 09:40:31 +00006563 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006564}
6565
Douglas Gregor09acc982010-07-07 23:08:52 +00006566/// \brief Determine whether a using declaration considers the given
6567/// declarations as "equivalent", e.g., if they are redeclarations of
6568/// the same entity or are both typedefs of the same type.
6569static bool
6570IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6571 bool &SuppressRedeclaration) {
6572 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6573 SuppressRedeclaration = false;
6574 return true;
6575 }
6576
Richard Smith162e1c12011-04-15 14:24:37 +00006577 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6578 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006579 SuppressRedeclaration = true;
6580 return Context.hasSameType(TD1->getUnderlyingType(),
6581 TD2->getUnderlyingType());
6582 }
6583
6584 return false;
6585}
6586
6587
John McCall9f54ad42009-12-10 09:41:52 +00006588/// Determines whether to create a using shadow decl for a particular
6589/// decl, given the set of decls existing prior to this using lookup.
6590bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6591 const LookupResult &Previous) {
6592 // Diagnose finding a decl which is not from a base class of the
6593 // current class. We do this now because there are cases where this
6594 // function will silently decide not to build a shadow decl, which
6595 // will pre-empt further diagnostics.
6596 //
6597 // We don't need to do this in C++0x because we do the check once on
6598 // the qualifier.
6599 //
6600 // FIXME: diagnose the following if we care enough:
6601 // struct A { int foo; };
6602 // struct B : A { using A::foo; };
6603 // template <class T> struct C : A {};
6604 // template <class T> struct D : C<T> { using B::foo; } // <---
6605 // This is invalid (during instantiation) in C++03 because B::foo
6606 // resolves to the using decl in B, which is not a base class of D<T>.
6607 // We can't diagnose it immediately because C<T> is an unknown
6608 // specialization. The UsingShadowDecl in D<T> then points directly
6609 // to A::foo, which will look well-formed when we instantiate.
6610 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006611 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006612 DeclContext *OrigDC = Orig->getDeclContext();
6613
6614 // Handle enums and anonymous structs.
6615 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6616 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6617 while (OrigRec->isAnonymousStructOrUnion())
6618 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6619
6620 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6621 if (OrigDC == CurContext) {
6622 Diag(Using->getLocation(),
6623 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006624 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006625 Diag(Orig->getLocation(), diag::note_using_decl_target);
6626 return true;
6627 }
6628
Douglas Gregordc355712011-02-25 00:36:19 +00006629 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006630 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006631 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006632 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006633 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006634 Diag(Orig->getLocation(), diag::note_using_decl_target);
6635 return true;
6636 }
6637 }
6638
6639 if (Previous.empty()) return false;
6640
6641 NamedDecl *Target = Orig;
6642 if (isa<UsingShadowDecl>(Target))
6643 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6644
John McCalld7533ec2009-12-11 02:33:26 +00006645 // If the target happens to be one of the previous declarations, we
6646 // don't have a conflict.
6647 //
6648 // FIXME: but we might be increasing its access, in which case we
6649 // should redeclare it.
6650 NamedDecl *NonTag = 0, *Tag = 0;
6651 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6652 I != E; ++I) {
6653 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006654 bool Result;
6655 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6656 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006657
6658 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6659 }
6660
John McCall9f54ad42009-12-10 09:41:52 +00006661 if (Target->isFunctionOrFunctionTemplate()) {
6662 FunctionDecl *FD;
6663 if (isa<FunctionTemplateDecl>(Target))
6664 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6665 else
6666 FD = cast<FunctionDecl>(Target);
6667
6668 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006669 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006670 case Ovl_Overload:
6671 return false;
6672
6673 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006674 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006675 break;
6676
6677 // We found a decl with the exact signature.
6678 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006679 // If we're in a record, we want to hide the target, so we
6680 // return true (without a diagnostic) to tell the caller not to
6681 // build a shadow decl.
6682 if (CurContext->isRecord())
6683 return true;
6684
6685 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006686 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006687 break;
6688 }
6689
6690 Diag(Target->getLocation(), diag::note_using_decl_target);
6691 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6692 return true;
6693 }
6694
6695 // Target is not a function.
6696
John McCall9f54ad42009-12-10 09:41:52 +00006697 if (isa<TagDecl>(Target)) {
6698 // No conflict between a tag and a non-tag.
6699 if (!Tag) return false;
6700
John McCall41ce66f2009-12-10 19:51:03 +00006701 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006702 Diag(Target->getLocation(), diag::note_using_decl_target);
6703 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6704 return true;
6705 }
6706
6707 // No conflict between a tag and a non-tag.
6708 if (!NonTag) return false;
6709
John McCall41ce66f2009-12-10 19:51:03 +00006710 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006711 Diag(Target->getLocation(), diag::note_using_decl_target);
6712 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6713 return true;
6714}
6715
John McCall9488ea12009-11-17 05:59:44 +00006716/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006717UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006718 UsingDecl *UD,
6719 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006720
6721 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006722 NamedDecl *Target = Orig;
6723 if (isa<UsingShadowDecl>(Target)) {
6724 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6725 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006726 }
6727
6728 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006729 = UsingShadowDecl::Create(Context, CurContext,
6730 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006731 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006732
6733 Shadow->setAccess(UD->getAccess());
6734 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6735 Shadow->setInvalidDecl();
6736
John McCall9488ea12009-11-17 05:59:44 +00006737 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006738 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006739 else
John McCall604e7f12009-12-08 07:46:18 +00006740 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006741
John McCall604e7f12009-12-08 07:46:18 +00006742
John McCall9f54ad42009-12-10 09:41:52 +00006743 return Shadow;
6744}
John McCall604e7f12009-12-08 07:46:18 +00006745
John McCall9f54ad42009-12-10 09:41:52 +00006746/// Hides a using shadow declaration. This is required by the current
6747/// using-decl implementation when a resolvable using declaration in a
6748/// class is followed by a declaration which would hide or override
6749/// one or more of the using decl's targets; for example:
6750///
6751/// struct Base { void foo(int); };
6752/// struct Derived : Base {
6753/// using Base::foo;
6754/// void foo(int);
6755/// };
6756///
6757/// The governing language is C++03 [namespace.udecl]p12:
6758///
6759/// When a using-declaration brings names from a base class into a
6760/// derived class scope, member functions in the derived class
6761/// override and/or hide member functions with the same name and
6762/// parameter types in a base class (rather than conflicting).
6763///
6764/// There are two ways to implement this:
6765/// (1) optimistically create shadow decls when they're not hidden
6766/// by existing declarations, or
6767/// (2) don't create any shadow decls (or at least don't make them
6768/// visible) until we've fully parsed/instantiated the class.
6769/// The problem with (1) is that we might have to retroactively remove
6770/// a shadow decl, which requires several O(n) operations because the
6771/// decl structures are (very reasonably) not designed for removal.
6772/// (2) avoids this but is very fiddly and phase-dependent.
6773void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006774 if (Shadow->getDeclName().getNameKind() ==
6775 DeclarationName::CXXConversionFunctionName)
6776 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6777
John McCall9f54ad42009-12-10 09:41:52 +00006778 // Remove it from the DeclContext...
6779 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006780
John McCall9f54ad42009-12-10 09:41:52 +00006781 // ...and the scope, if applicable...
6782 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006783 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006784 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006785 }
6786
John McCall9f54ad42009-12-10 09:41:52 +00006787 // ...and the using decl.
6788 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6789
6790 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006791 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006792}
6793
John McCall7ba107a2009-11-18 02:36:19 +00006794/// Builds a using declaration.
6795///
6796/// \param IsInstantiation - Whether this call arises from an
6797/// instantiation of an unresolved using declaration. We treat
6798/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006799NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6800 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006801 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006802 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006803 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006804 bool IsInstantiation,
6805 bool IsTypeName,
6806 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006807 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006808 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006809 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006810
Anders Carlsson550b14b2009-08-28 05:49:21 +00006811 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006812
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006813 if (SS.isEmpty()) {
6814 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006815 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006816 }
Mike Stump1eb44332009-09-09 15:08:12 +00006817
John McCall9f54ad42009-12-10 09:41:52 +00006818 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006819 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006820 ForRedeclaration);
6821 Previous.setHideTags(false);
6822 if (S) {
6823 LookupName(Previous, S);
6824
6825 // It is really dumb that we have to do this.
6826 LookupResult::Filter F = Previous.makeFilter();
6827 while (F.hasNext()) {
6828 NamedDecl *D = F.next();
6829 if (!isDeclInScope(D, CurContext, S))
6830 F.erase();
6831 }
6832 F.done();
6833 } else {
6834 assert(IsInstantiation && "no scope in non-instantiation");
6835 assert(CurContext->isRecord() && "scope not record in instantiation");
6836 LookupQualifiedName(Previous, CurContext);
6837 }
6838
John McCall9f54ad42009-12-10 09:41:52 +00006839 // Check for invalid redeclarations.
6840 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6841 return 0;
6842
6843 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006844 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6845 return 0;
6846
John McCallaf8e6ed2009-11-12 03:15:40 +00006847 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006848 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006849 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006850 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006851 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006852 // FIXME: not all declaration name kinds are legal here
6853 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6854 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006855 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006856 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006857 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006858 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6859 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006860 }
John McCalled976492009-12-04 22:46:56 +00006861 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006862 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6863 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006864 }
John McCalled976492009-12-04 22:46:56 +00006865 D->setAccess(AS);
6866 CurContext->addDecl(D);
6867
6868 if (!LookupContext) return D;
6869 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006870
John McCall77bb1aa2010-05-01 00:40:08 +00006871 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006872 UD->setInvalidDecl();
6873 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006874 }
6875
Richard Smithc5a89a12012-04-02 01:30:27 +00006876 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006877 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006878 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006879 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006880 return UD;
6881 }
6882
6883 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006884
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006885 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006886
John McCall604e7f12009-12-08 07:46:18 +00006887 // Unlike most lookups, we don't always want to hide tag
6888 // declarations: tag names are visible through the using declaration
6889 // even if hidden by ordinary names, *except* in a dependent context
6890 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006891 if (!IsInstantiation)
6892 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006893
John McCallb9abd8722012-04-07 03:04:20 +00006894 // For the purposes of this lookup, we have a base object type
6895 // equal to that of the current context.
6896 if (CurContext->isRecord()) {
6897 R.setBaseObjectType(
6898 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6899 }
6900
John McCalla24dc2e2009-11-17 02:14:36 +00006901 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006902
John McCallf36e02d2009-10-09 21:13:30 +00006903 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006904 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006905 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006906 UD->setInvalidDecl();
6907 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006908 }
6909
John McCalled976492009-12-04 22:46:56 +00006910 if (R.isAmbiguous()) {
6911 UD->setInvalidDecl();
6912 return UD;
6913 }
Mike Stump1eb44332009-09-09 15:08:12 +00006914
John McCall7ba107a2009-11-18 02:36:19 +00006915 if (IsTypeName) {
6916 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006917 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006918 Diag(IdentLoc, diag::err_using_typename_non_type);
6919 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6920 Diag((*I)->getUnderlyingDecl()->getLocation(),
6921 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006922 UD->setInvalidDecl();
6923 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006924 }
6925 } else {
6926 // If we asked for a non-typename and we got a type, error out,
6927 // but only if this is an instantiation of an unresolved using
6928 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006929 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006930 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6931 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006932 UD->setInvalidDecl();
6933 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006934 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006935 }
6936
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006937 // C++0x N2914 [namespace.udecl]p6:
6938 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006939 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006940 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6941 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006942 UD->setInvalidDecl();
6943 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006944 }
Mike Stump1eb44332009-09-09 15:08:12 +00006945
John McCall9f54ad42009-12-10 09:41:52 +00006946 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6947 if (!CheckUsingShadowDecl(UD, *I, Previous))
6948 BuildUsingShadowDecl(S, UD, *I);
6949 }
John McCall9488ea12009-11-17 05:59:44 +00006950
6951 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006952}
6953
Sebastian Redlf677ea32011-02-05 19:23:19 +00006954/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006955bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6956 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006957
Douglas Gregordc355712011-02-25 00:36:19 +00006958 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006959 assert(SourceType &&
6960 "Using decl naming constructor doesn't have type in scope spec.");
6961 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6962
6963 // Check whether the named type is a direct base class.
6964 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6965 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6966 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6967 BaseIt != BaseE; ++BaseIt) {
6968 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6969 if (CanonicalSourceType == BaseType)
6970 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006971 if (BaseIt->getType()->isDependentType())
6972 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006973 }
6974
6975 if (BaseIt == BaseE) {
6976 // Did not find SourceType in the bases.
6977 Diag(UD->getUsingLocation(),
6978 diag::err_using_decl_constructor_not_in_direct_base)
6979 << UD->getNameInfo().getSourceRange()
6980 << QualType(SourceType, 0) << TargetClass;
6981 return true;
6982 }
6983
Richard Smithc5a89a12012-04-02 01:30:27 +00006984 if (!CurContext->isDependentContext())
6985 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006986
6987 return false;
6988}
6989
John McCall9f54ad42009-12-10 09:41:52 +00006990/// Checks that the given using declaration is not an invalid
6991/// redeclaration. Note that this is checking only for the using decl
6992/// itself, not for any ill-formedness among the UsingShadowDecls.
6993bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6994 bool isTypeName,
6995 const CXXScopeSpec &SS,
6996 SourceLocation NameLoc,
6997 const LookupResult &Prev) {
6998 // C++03 [namespace.udecl]p8:
6999 // C++0x [namespace.udecl]p10:
7000 // A using-declaration is a declaration and can therefore be used
7001 // repeatedly where (and only where) multiple declarations are
7002 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007003 //
John McCall8a726212010-11-29 18:01:58 +00007004 // That's in non-member contexts.
7005 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007006 return false;
7007
7008 NestedNameSpecifier *Qual
7009 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7010
7011 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7012 NamedDecl *D = *I;
7013
7014 bool DTypename;
7015 NestedNameSpecifier *DQual;
7016 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7017 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007018 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007019 } else if (UnresolvedUsingValueDecl *UD
7020 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7021 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007022 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007023 } else if (UnresolvedUsingTypenameDecl *UD
7024 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7025 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007026 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007027 } else continue;
7028
7029 // using decls differ if one says 'typename' and the other doesn't.
7030 // FIXME: non-dependent using decls?
7031 if (isTypeName != DTypename) continue;
7032
7033 // using decls differ if they name different scopes (but note that
7034 // template instantiation can cause this check to trigger when it
7035 // didn't before instantiation).
7036 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7037 Context.getCanonicalNestedNameSpecifier(DQual))
7038 continue;
7039
7040 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007041 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007042 return true;
7043 }
7044
7045 return false;
7046}
7047
John McCall604e7f12009-12-08 07:46:18 +00007048
John McCalled976492009-12-04 22:46:56 +00007049/// Checks that the given nested-name qualifier used in a using decl
7050/// in the current context is appropriately related to the current
7051/// scope. If an error is found, diagnoses it and returns true.
7052bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7053 const CXXScopeSpec &SS,
7054 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007055 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007056
John McCall604e7f12009-12-08 07:46:18 +00007057 if (!CurContext->isRecord()) {
7058 // C++03 [namespace.udecl]p3:
7059 // C++0x [namespace.udecl]p8:
7060 // A using-declaration for a class member shall be a member-declaration.
7061
7062 // If we weren't able to compute a valid scope, it must be a
7063 // dependent class scope.
7064 if (!NamedContext || NamedContext->isRecord()) {
7065 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7066 << SS.getRange();
7067 return true;
7068 }
7069
7070 // Otherwise, everything is known to be fine.
7071 return false;
7072 }
7073
7074 // The current scope is a record.
7075
7076 // If the named context is dependent, we can't decide much.
7077 if (!NamedContext) {
7078 // FIXME: in C++0x, we can diagnose if we can prove that the
7079 // nested-name-specifier does not refer to a base class, which is
7080 // still possible in some cases.
7081
7082 // Otherwise we have to conservatively report that things might be
7083 // okay.
7084 return false;
7085 }
7086
7087 if (!NamedContext->isRecord()) {
7088 // Ideally this would point at the last name in the specifier,
7089 // but we don't have that level of source info.
7090 Diag(SS.getRange().getBegin(),
7091 diag::err_using_decl_nested_name_specifier_is_not_class)
7092 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7093 return true;
7094 }
7095
Douglas Gregor6fb07292010-12-21 07:41:49 +00007096 if (!NamedContext->isDependentContext() &&
7097 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7098 return true;
7099
Richard Smith80ad52f2013-01-02 11:42:31 +00007100 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007101 // C++0x [namespace.udecl]p3:
7102 // In a using-declaration used as a member-declaration, the
7103 // nested-name-specifier shall name a base class of the class
7104 // being defined.
7105
7106 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7107 cast<CXXRecordDecl>(NamedContext))) {
7108 if (CurContext == NamedContext) {
7109 Diag(NameLoc,
7110 diag::err_using_decl_nested_name_specifier_is_current_class)
7111 << SS.getRange();
7112 return true;
7113 }
7114
7115 Diag(SS.getRange().getBegin(),
7116 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7117 << (NestedNameSpecifier*) SS.getScopeRep()
7118 << cast<CXXRecordDecl>(CurContext)
7119 << SS.getRange();
7120 return true;
7121 }
7122
7123 return false;
7124 }
7125
7126 // C++03 [namespace.udecl]p4:
7127 // A using-declaration used as a member-declaration shall refer
7128 // to a member of a base class of the class being defined [etc.].
7129
7130 // Salient point: SS doesn't have to name a base class as long as
7131 // lookup only finds members from base classes. Therefore we can
7132 // diagnose here only if we can prove that that can't happen,
7133 // i.e. if the class hierarchies provably don't intersect.
7134
7135 // TODO: it would be nice if "definitely valid" results were cached
7136 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7137 // need to be repeated.
7138
7139 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007140 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007141
7142 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7143 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7144 Data->Bases.insert(Base);
7145 return true;
7146 }
7147
7148 bool hasDependentBases(const CXXRecordDecl *Class) {
7149 return !Class->forallBases(collect, this);
7150 }
7151
7152 /// Returns true if the base is dependent or is one of the
7153 /// accumulated base classes.
7154 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7155 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7156 return !Data->Bases.count(Base);
7157 }
7158
7159 bool mightShareBases(const CXXRecordDecl *Class) {
7160 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7161 }
7162 };
7163
7164 UserData Data;
7165
7166 // Returns false if we find a dependent base.
7167 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7168 return false;
7169
7170 // Returns false if the class has a dependent base or if it or one
7171 // of its bases is present in the base set of the current context.
7172 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7173 return false;
7174
7175 Diag(SS.getRange().getBegin(),
7176 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7177 << (NestedNameSpecifier*) SS.getScopeRep()
7178 << cast<CXXRecordDecl>(CurContext)
7179 << SS.getRange();
7180
7181 return true;
John McCalled976492009-12-04 22:46:56 +00007182}
7183
Richard Smith162e1c12011-04-15 14:24:37 +00007184Decl *Sema::ActOnAliasDeclaration(Scope *S,
7185 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007186 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007187 SourceLocation UsingLoc,
7188 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007189 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007190 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007191 // Skip up to the relevant declaration scope.
7192 while (S->getFlags() & Scope::TemplateParamScope)
7193 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007194 assert((S->getFlags() & Scope::DeclScope) &&
7195 "got alias-declaration outside of declaration scope");
7196
7197 if (Type.isInvalid())
7198 return 0;
7199
7200 bool Invalid = false;
7201 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7202 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007203 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007204
7205 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7206 return 0;
7207
7208 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007209 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007210 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007211 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7212 TInfo->getTypeLoc().getBeginLoc());
7213 }
Richard Smith162e1c12011-04-15 14:24:37 +00007214
7215 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7216 LookupName(Previous, S);
7217
7218 // Warn about shadowing the name of a template parameter.
7219 if (Previous.isSingleResult() &&
7220 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007221 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007222 Previous.clear();
7223 }
7224
7225 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7226 "name in alias declaration must be an identifier");
7227 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7228 Name.StartLocation,
7229 Name.Identifier, TInfo);
7230
7231 NewTD->setAccess(AS);
7232
7233 if (Invalid)
7234 NewTD->setInvalidDecl();
7235
Richard Smith6b3d3e52013-02-20 19:22:51 +00007236 ProcessDeclAttributeList(S, NewTD, AttrList);
7237
Richard Smith3e4c6c42011-05-05 21:57:07 +00007238 CheckTypedefForVariablyModifiedType(S, NewTD);
7239 Invalid |= NewTD->isInvalidDecl();
7240
Richard Smith162e1c12011-04-15 14:24:37 +00007241 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007242
7243 NamedDecl *NewND;
7244 if (TemplateParamLists.size()) {
7245 TypeAliasTemplateDecl *OldDecl = 0;
7246 TemplateParameterList *OldTemplateParams = 0;
7247
7248 if (TemplateParamLists.size() != 1) {
7249 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007250 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7251 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007252 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007253 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007254
7255 // Only consider previous declarations in the same scope.
7256 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7257 /*ExplicitInstantiationOrSpecialization*/false);
7258 if (!Previous.empty()) {
7259 Redeclaration = true;
7260
7261 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7262 if (!OldDecl && !Invalid) {
7263 Diag(UsingLoc, diag::err_redefinition_different_kind)
7264 << Name.Identifier;
7265
7266 NamedDecl *OldD = Previous.getRepresentativeDecl();
7267 if (OldD->getLocation().isValid())
7268 Diag(OldD->getLocation(), diag::note_previous_definition);
7269
7270 Invalid = true;
7271 }
7272
7273 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7274 if (TemplateParameterListsAreEqual(TemplateParams,
7275 OldDecl->getTemplateParameters(),
7276 /*Complain=*/true,
7277 TPL_TemplateMatch))
7278 OldTemplateParams = OldDecl->getTemplateParameters();
7279 else
7280 Invalid = true;
7281
7282 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7283 if (!Invalid &&
7284 !Context.hasSameType(OldTD->getUnderlyingType(),
7285 NewTD->getUnderlyingType())) {
7286 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7287 // but we can't reasonably accept it.
7288 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7289 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7290 if (OldTD->getLocation().isValid())
7291 Diag(OldTD->getLocation(), diag::note_previous_definition);
7292 Invalid = true;
7293 }
7294 }
7295 }
7296
7297 // Merge any previous default template arguments into our parameters,
7298 // and check the parameter list.
7299 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7300 TPC_TypeAliasTemplate))
7301 return 0;
7302
7303 TypeAliasTemplateDecl *NewDecl =
7304 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7305 Name.Identifier, TemplateParams,
7306 NewTD);
7307
7308 NewDecl->setAccess(AS);
7309
7310 if (Invalid)
7311 NewDecl->setInvalidDecl();
7312 else if (OldDecl)
7313 NewDecl->setPreviousDeclaration(OldDecl);
7314
7315 NewND = NewDecl;
7316 } else {
7317 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7318 NewND = NewTD;
7319 }
Richard Smith162e1c12011-04-15 14:24:37 +00007320
7321 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007322 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007323
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007324 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007325 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007326}
7327
John McCalld226f652010-08-21 09:40:31 +00007328Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007329 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007330 SourceLocation AliasLoc,
7331 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007332 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007333 SourceLocation IdentLoc,
7334 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007335
Anders Carlsson81c85c42009-03-28 23:53:49 +00007336 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007337 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7338 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007339
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007340 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007341 NamedDecl *PrevDecl
7342 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7343 ForRedeclaration);
7344 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7345 PrevDecl = 0;
7346
7347 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007348 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007349 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007350 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007351 // FIXME: At some point, we'll want to create the (redundant)
7352 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007353 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007354 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007355 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007356 }
Mike Stump1eb44332009-09-09 15:08:12 +00007357
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007358 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7359 diag::err_redefinition_different_kind;
7360 Diag(AliasLoc, DiagID) << Alias;
7361 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007362 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007363 }
7364
John McCalla24dc2e2009-11-17 02:14:36 +00007365 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007366 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007367
John McCallf36e02d2009-10-09 21:13:30 +00007368 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007369 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007370 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007371 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007372 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007373 }
Mike Stump1eb44332009-09-09 15:08:12 +00007374
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007375 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007376 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007377 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007378 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007379
John McCall3dbd3d52010-02-16 06:53:13 +00007380 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007381 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007382}
7383
Sean Hunt001cad92011-05-10 00:49:42 +00007384Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007385Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7386 CXXMethodDecl *MD) {
7387 CXXRecordDecl *ClassDecl = MD->getParent();
7388
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007389 // C++ [except.spec]p14:
7390 // An implicitly declared special member function (Clause 12) shall have an
7391 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007392 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007393 if (ClassDecl->isInvalidDecl())
7394 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007395
Sebastian Redl60618fa2011-03-12 11:50:43 +00007396 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007397 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7398 BEnd = ClassDecl->bases_end();
7399 B != BEnd; ++B) {
7400 if (B->isVirtual()) // Handled below.
7401 continue;
7402
Douglas Gregor18274032010-07-03 00:47:00 +00007403 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7404 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007405 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7406 // If this is a deleted function, add it anyway. This might be conformant
7407 // with the standard. This might not. I'm not sure. It might not matter.
7408 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007409 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007410 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007411 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007412
7413 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007414 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7415 BEnd = ClassDecl->vbases_end();
7416 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007417 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7418 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007419 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7420 // If this is a deleted function, add it anyway. This might be conformant
7421 // with the standard. This might not. I'm not sure. It might not matter.
7422 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007423 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007424 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007425 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007426
7427 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007428 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7429 FEnd = ClassDecl->field_end();
7430 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007431 if (F->hasInClassInitializer()) {
7432 if (Expr *E = F->getInClassInitializer())
7433 ExceptSpec.CalledExpr(E);
7434 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007435 // DR1351:
7436 // If the brace-or-equal-initializer of a non-static data member
7437 // invokes a defaulted default constructor of its class or of an
7438 // enclosing class in a potentially evaluated subexpression, the
7439 // program is ill-formed.
7440 //
7441 // This resolution is unworkable: the exception specification of the
7442 // default constructor can be needed in an unevaluated context, in
7443 // particular, in the operand of a noexcept-expression, and we can be
7444 // unable to compute an exception specification for an enclosed class.
7445 //
7446 // We do not allow an in-class initializer to require the evaluation
7447 // of the exception specification for any in-class initializer whose
7448 // definition is not lexically complete.
7449 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007450 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007451 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007452 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7453 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7454 // If this is a deleted function, add it anyway. This might be conformant
7455 // with the standard. This might not. I'm not sure. It might not matter.
7456 // In particular, the problem is that this function never gets called. It
7457 // might just be ill-formed because this function attempts to refer to
7458 // a deleted function here.
7459 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007460 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007461 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007462 }
John McCalle23cf432010-12-14 08:05:40 +00007463
Sean Hunt001cad92011-05-10 00:49:42 +00007464 return ExceptSpec;
7465}
7466
Richard Smithafb49182012-11-29 01:34:07 +00007467namespace {
7468/// RAII object to register a special member as being currently declared.
7469struct DeclaringSpecialMember {
7470 Sema &S;
7471 Sema::SpecialMemberDecl D;
7472 bool WasAlreadyBeingDeclared;
7473
7474 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7475 : S(S), D(RD, CSM) {
7476 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7477 if (WasAlreadyBeingDeclared)
7478 // This almost never happens, but if it does, ensure that our cache
7479 // doesn't contain a stale result.
7480 S.SpecialMemberCache.clear();
7481
7482 // FIXME: Register a note to be produced if we encounter an error while
7483 // declaring the special member.
7484 }
7485 ~DeclaringSpecialMember() {
7486 if (!WasAlreadyBeingDeclared)
7487 S.SpecialMembersBeingDeclared.erase(D);
7488 }
7489
7490 /// \brief Are we already trying to declare this special member?
7491 bool isAlreadyBeingDeclared() const {
7492 return WasAlreadyBeingDeclared;
7493 }
7494};
7495}
7496
Sean Hunt001cad92011-05-10 00:49:42 +00007497CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7498 CXXRecordDecl *ClassDecl) {
7499 // C++ [class.ctor]p5:
7500 // A default constructor for a class X is a constructor of class X
7501 // that can be called without an argument. If there is no
7502 // user-declared constructor for class X, a default constructor is
7503 // implicitly declared. An implicitly-declared default constructor
7504 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007505 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007506 "Should not build implicit default constructor!");
7507
Richard Smithafb49182012-11-29 01:34:07 +00007508 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7509 if (DSM.isAlreadyBeingDeclared())
7510 return 0;
7511
Richard Smith7756afa2012-06-10 05:43:50 +00007512 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7513 CXXDefaultConstructor,
7514 false);
7515
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007516 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007517 CanQualType ClassType
7518 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007519 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007520 DeclarationName Name
7521 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007522 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007523 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007524 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007525 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007526 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007527 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007528 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007529 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007530
7531 // Build an exception specification pointing back at this constructor.
7532 FunctionProtoType::ExtProtoInfo EPI;
7533 EPI.ExceptionSpecType = EST_Unevaluated;
7534 EPI.ExceptionSpecDecl = DefaultCon;
7535 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7536
Richard Smithbc2a35d2012-12-08 08:32:28 +00007537 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7538 // constructors is easy to compute.
7539 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7540
7541 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7542 DefaultCon->setDeletedAsWritten();
7543
Douglas Gregor18274032010-07-03 00:47:00 +00007544 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007545 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007546
Douglas Gregor23c94db2010-07-02 17:43:08 +00007547 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007548 PushOnScopeChains(DefaultCon, S, false);
7549 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007550
Douglas Gregor32df23e2010-07-01 22:02:46 +00007551 return DefaultCon;
7552}
7553
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007554void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7555 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007556 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007557 !Constructor->doesThisDeclarationHaveABody() &&
7558 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007559 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007560
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007561 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007562 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007563
Eli Friedman9a14db32012-10-18 20:14:08 +00007564 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007565 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007566 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007567 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007568 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007569 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007570 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007571 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007572 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007573
7574 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007575 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007576
7577 Constructor->setUsed();
7578 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007579
7580 if (ASTMutationListener *L = getASTMutationListener()) {
7581 L->CompletedImplicitDefinition(Constructor);
7582 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007583}
7584
Richard Smith7a614d82011-06-11 17:19:42 +00007585void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007586 // Check that any explicitly-defaulted methods have exception specifications
7587 // compatible with their implicit exception specifications.
7588 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007589}
7590
Sebastian Redlf677ea32011-02-05 19:23:19 +00007591void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7592 // We start with an initial pass over the base classes to collect those that
7593 // inherit constructors from. If there are none, we can forgo all further
7594 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007595 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007596 BasesVector BasesToInheritFrom;
7597 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7598 BaseE = ClassDecl->bases_end();
7599 BaseIt != BaseE; ++BaseIt) {
7600 if (BaseIt->getInheritConstructors()) {
7601 QualType Base = BaseIt->getType();
7602 if (Base->isDependentType()) {
7603 // If we inherit constructors from anything that is dependent, just
7604 // abort processing altogether. We'll get another chance for the
7605 // instantiations.
7606 return;
7607 }
7608 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7609 }
7610 }
7611 if (BasesToInheritFrom.empty())
7612 return;
7613
7614 // Now collect the constructors that we already have in the current class.
7615 // Those take precedence over inherited constructors.
7616 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7617 // unless there is a user-declared constructor with the same signature in
7618 // the class where the using-declaration appears.
7619 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7620 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7621 CtorE = ClassDecl->ctor_end();
7622 CtorIt != CtorE; ++CtorIt) {
7623 ExistingConstructors.insert(
7624 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7625 }
7626
Sebastian Redlf677ea32011-02-05 19:23:19 +00007627 DeclarationName CreatedCtorName =
7628 Context.DeclarationNames.getCXXConstructorName(
7629 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7630
7631 // Now comes the true work.
7632 // First, we keep a map from constructor types to the base that introduced
7633 // them. Needed for finding conflicting constructors. We also keep the
7634 // actually inserted declarations in there, for pretty diagnostics.
7635 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7636 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7637 ConstructorToSourceMap InheritedConstructors;
7638 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7639 BaseE = BasesToInheritFrom.end();
7640 BaseIt != BaseE; ++BaseIt) {
7641 const RecordType *Base = *BaseIt;
7642 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7643 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7644 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7645 CtorE = BaseDecl->ctor_end();
7646 CtorIt != CtorE; ++CtorIt) {
7647 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00007648 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00007649 DeclarationName Name =
7650 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00007651 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7652 LookupQualifiedName(Result, CurContext);
7653 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007654 SourceLocation UsingLoc = UD ? UD->getLocation() :
7655 ClassDecl->getLocation();
7656
7657 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7658 // from the class X named in the using-declaration consists of actual
7659 // constructors and notional constructors that result from the
7660 // transformation of defaulted parameters as follows:
7661 // - all non-template default constructors of X, and
7662 // - for each non-template constructor of X that has at least one
7663 // parameter with a default argument, the set of constructors that
7664 // results from omitting any ellipsis parameter specification and
7665 // successively omitting parameters with a default argument from the
7666 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00007667 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007668 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7669 const FunctionProtoType *BaseCtorType =
7670 BaseCtor->getType()->getAs<FunctionProtoType>();
7671
7672 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7673 maxParams = BaseCtor->getNumParams();
7674 params <= maxParams; ++params) {
7675 // Skip default constructors. They're never inherited.
7676 if (params == 0)
7677 continue;
7678 // Skip copy and move constructors for the same reason.
7679 if (CanBeCopyOrMove && params == 1)
7680 continue;
7681
7682 // Build up a function type for this particular constructor.
7683 // FIXME: The working paper does not consider that the exception spec
7684 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007685 // source. This code doesn't yet, either. When it does, this code will
7686 // need to be delayed until after exception specifications and in-class
7687 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007688 const Type *NewCtorType;
7689 if (params == maxParams)
7690 NewCtorType = BaseCtorType;
7691 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007692 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007693 for (unsigned i = 0; i < params; ++i) {
7694 Args.push_back(BaseCtorType->getArgType(i));
7695 }
7696 FunctionProtoType::ExtProtoInfo ExtInfo =
7697 BaseCtorType->getExtProtoInfo();
7698 ExtInfo.Variadic = false;
7699 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7700 Args.data(), params, ExtInfo)
7701 .getTypePtr();
7702 }
7703 const Type *CanonicalNewCtorType =
7704 Context.getCanonicalType(NewCtorType);
7705
7706 // Now that we have the type, first check if the class already has a
7707 // constructor with this signature.
7708 if (ExistingConstructors.count(CanonicalNewCtorType))
7709 continue;
7710
7711 // Then we check if we have already declared an inherited constructor
7712 // with this signature.
7713 std::pair<ConstructorToSourceMap::iterator, bool> result =
7714 InheritedConstructors.insert(std::make_pair(
7715 CanonicalNewCtorType,
7716 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7717 if (!result.second) {
7718 // Already in the map. If it came from a different class, that's an
7719 // error. Not if it's from the same.
7720 CanQualType PreviousBase = result.first->second.first;
7721 if (CanonicalBase != PreviousBase) {
7722 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7723 const CXXConstructorDecl *PrevBaseCtor =
7724 PrevCtor->getInheritedConstructor();
7725 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7726
7727 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7728 Diag(BaseCtor->getLocation(),
7729 diag::note_using_decl_constructor_conflict_current_ctor);
7730 Diag(PrevBaseCtor->getLocation(),
7731 diag::note_using_decl_constructor_conflict_previous_ctor);
7732 Diag(PrevCtor->getLocation(),
7733 diag::note_using_decl_constructor_conflict_previous_using);
7734 }
7735 continue;
7736 }
7737
7738 // OK, we're there, now add the constructor.
7739 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007740 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007741 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7742 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007743 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7744 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007745 /*ImplicitlyDeclared=*/true,
7746 // FIXME: Due to a defect in the standard, we treat inherited
7747 // constructors as constexpr even if that makes them ill-formed.
7748 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007749 NewCtor->setAccess(BaseCtor->getAccess());
7750
7751 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007752 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007753 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007754 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7755 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007756 /*IdentifierInfo=*/0,
7757 BaseCtorType->getArgType(i),
7758 /*TInfo=*/0, SC_None,
7759 SC_None, /*DefaultArg=*/0));
7760 }
David Blaikie4278c652011-09-21 18:16:56 +00007761 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007762 NewCtor->setInheritedConstructor(BaseCtor);
7763
Sebastian Redlf677ea32011-02-05 19:23:19 +00007764 ClassDecl->addDecl(NewCtor);
7765 result.first->second.second = NewCtor;
7766 }
7767 }
7768 }
7769}
7770
Sean Huntcb45a0f2011-05-12 22:46:25 +00007771Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007772Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7773 CXXRecordDecl *ClassDecl = MD->getParent();
7774
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007775 // C++ [except.spec]p14:
7776 // An implicitly declared special member function (Clause 12) shall have
7777 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007778 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007779 if (ClassDecl->isInvalidDecl())
7780 return ExceptSpec;
7781
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007782 // Direct base-class destructors.
7783 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7784 BEnd = ClassDecl->bases_end();
7785 B != BEnd; ++B) {
7786 if (B->isVirtual()) // Handled below.
7787 continue;
7788
7789 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007790 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007791 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007792 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007793
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007794 // Virtual base-class destructors.
7795 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7796 BEnd = ClassDecl->vbases_end();
7797 B != BEnd; ++B) {
7798 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007799 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007800 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007801 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007802
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007803 // Field destructors.
7804 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7805 FEnd = ClassDecl->field_end();
7806 F != FEnd; ++F) {
7807 if (const RecordType *RecordTy
7808 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007809 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007810 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007811 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007812
Sean Huntcb45a0f2011-05-12 22:46:25 +00007813 return ExceptSpec;
7814}
7815
7816CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7817 // C++ [class.dtor]p2:
7818 // If a class has no user-declared destructor, a destructor is
7819 // declared implicitly. An implicitly-declared destructor is an
7820 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00007821 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00007822
Richard Smithafb49182012-11-29 01:34:07 +00007823 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7824 if (DSM.isAlreadyBeingDeclared())
7825 return 0;
7826
Douglas Gregor4923aa22010-07-02 20:37:36 +00007827 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007828 CanQualType ClassType
7829 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007830 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007831 DeclarationName Name
7832 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007833 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007834 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007835 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7836 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007837 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007838 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007839 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007840 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007841
7842 // Build an exception specification pointing back at this destructor.
7843 FunctionProtoType::ExtProtoInfo EPI;
7844 EPI.ExceptionSpecType = EST_Unevaluated;
7845 EPI.ExceptionSpecDecl = Destructor;
7846 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7847
Richard Smithbc2a35d2012-12-08 08:32:28 +00007848 AddOverriddenMethods(ClassDecl, Destructor);
7849
7850 // We don't need to use SpecialMemberIsTrivial here; triviality for
7851 // destructors is easy to compute.
7852 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7853
7854 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7855 Destructor->setDeletedAsWritten();
7856
Douglas Gregor4923aa22010-07-02 20:37:36 +00007857 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007858 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007859
Douglas Gregor4923aa22010-07-02 20:37:36 +00007860 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007861 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007862 PushOnScopeChains(Destructor, S, false);
7863 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007864
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007865 return Destructor;
7866}
7867
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007868void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007869 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007870 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007871 !Destructor->doesThisDeclarationHaveABody() &&
7872 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007873 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007874 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007875 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007876
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007877 if (Destructor->isInvalidDecl())
7878 return;
7879
Eli Friedman9a14db32012-10-18 20:14:08 +00007880 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007881
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007882 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007883 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7884 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007885
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007886 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007887 Diag(CurrentLocation, diag::note_member_synthesized_at)
7888 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7889
7890 Destructor->setInvalidDecl();
7891 return;
7892 }
7893
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007894 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007895 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007896 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007897 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007898 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007899
7900 if (ASTMutationListener *L = getASTMutationListener()) {
7901 L->CompletedImplicitDefinition(Destructor);
7902 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007903}
7904
Richard Smitha4156b82012-04-21 18:42:51 +00007905/// \brief Perform any semantic analysis which needs to be delayed until all
7906/// pending class member declarations have been parsed.
7907void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00007908 // If the context is an invalid C++ class, just suppress these checks.
7909 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
7910 if (Record->isInvalidDecl()) {
7911 DelayedDestructorExceptionSpecChecks.clear();
7912 return;
7913 }
7914 }
7915
Richard Smitha4156b82012-04-21 18:42:51 +00007916 // Perform any deferred checking of exception specifications for virtual
7917 // destructors.
7918 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7919 i != e; ++i) {
7920 const CXXDestructorDecl *Dtor =
7921 DelayedDestructorExceptionSpecChecks[i].first;
7922 assert(!Dtor->getParent()->isDependentType() &&
7923 "Should not ever add destructors of templates into the list.");
7924 CheckOverridingFunctionExceptionSpec(Dtor,
7925 DelayedDestructorExceptionSpecChecks[i].second);
7926 }
7927 DelayedDestructorExceptionSpecChecks.clear();
7928}
7929
Richard Smithb9d0b762012-07-27 04:22:15 +00007930void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7931 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00007932 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00007933 "adjusting dtor exception specs was introduced in c++11");
7934
Sebastian Redl0ee33912011-05-19 05:13:44 +00007935 // C++11 [class.dtor]p3:
7936 // A declaration of a destructor that does not have an exception-
7937 // specification is implicitly considered to have the same exception-
7938 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007939 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007940 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007941 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007942 return;
7943
Chandler Carruth3f224b22011-09-20 04:55:26 +00007944 // Replace the destructor's type, building off the existing one. Fortunately,
7945 // the only thing of interest in the destructor type is its extended info.
7946 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007947 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7948 EPI.ExceptionSpecType = EST_Unevaluated;
7949 EPI.ExceptionSpecDecl = Destructor;
7950 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007951
Sebastian Redl0ee33912011-05-19 05:13:44 +00007952 // FIXME: If the destructor has a body that could throw, and the newly created
7953 // spec doesn't allow exceptions, we should emit a warning, because this
7954 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007955 // However, we don't have a body or an exception specification yet, so it
7956 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007957}
7958
Richard Smith8c889532012-11-14 00:50:40 +00007959/// When generating a defaulted copy or move assignment operator, if a field
7960/// should be copied with __builtin_memcpy rather than via explicit assignments,
7961/// do so. This optimization only applies for arrays of scalars, and for arrays
7962/// of class type where the selected copy/move-assignment operator is trivial.
7963static StmtResult
7964buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
7965 Expr *To, Expr *From) {
7966 // Compute the size of the memory buffer to be copied.
7967 QualType SizeType = S.Context.getSizeType();
7968 llvm::APInt Size(S.Context.getTypeSize(SizeType),
7969 S.Context.getTypeSizeInChars(T).getQuantity());
7970
7971 // Take the address of the field references for "from" and "to". We
7972 // directly construct UnaryOperators here because semantic analysis
7973 // does not permit us to take the address of an xvalue.
7974 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
7975 S.Context.getPointerType(From->getType()),
7976 VK_RValue, OK_Ordinary, Loc);
7977 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
7978 S.Context.getPointerType(To->getType()),
7979 VK_RValue, OK_Ordinary, Loc);
7980
7981 const Type *E = T->getBaseElementTypeUnsafe();
7982 bool NeedsCollectableMemCpy =
7983 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
7984
7985 // Create a reference to the __builtin_objc_memmove_collectable function
7986 StringRef MemCpyName = NeedsCollectableMemCpy ?
7987 "__builtin_objc_memmove_collectable" :
7988 "__builtin_memcpy";
7989 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
7990 Sema::LookupOrdinaryName);
7991 S.LookupName(R, S.TUScope, true);
7992
7993 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
7994 if (!MemCpy)
7995 // Something went horribly wrong earlier, and we will have complained
7996 // about it.
7997 return StmtError();
7998
7999 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8000 VK_RValue, Loc, 0);
8001 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8002
8003 Expr *CallArgs[] = {
8004 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8005 };
8006 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8007 Loc, CallArgs, Loc);
8008
8009 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8010 return S.Owned(Call.takeAs<Stmt>());
8011}
8012
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008013/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008014/// \c To.
8015///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008016/// This routine is used to copy/move the members of a class with an
8017/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008018/// copied are arrays, this routine builds for loops to copy them.
8019///
8020/// \param S The Sema object used for type-checking.
8021///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008022/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008023///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008024/// \param T The type of the expressions being copied/moved. Both expressions
8025/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008026///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008027/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008028///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008029/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008030///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008031/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008032/// Otherwise, it's a non-static member subobject.
8033///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008034/// \param Copying Whether we're copying or moving.
8035///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008036/// \param Depth Internal parameter recording the depth of the recursion.
8037///
Richard Smith8c889532012-11-14 00:50:40 +00008038/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8039/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008040static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008041buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8042 Expr *To, Expr *From,
8043 bool CopyingBaseSubobject, bool Copying,
8044 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008045 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008046 // Each subobject is assigned in the manner appropriate to its type:
8047 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008048 // - if the subobject is of class type, as if by a call to operator= with
8049 // the subobject as the object expression and the corresponding
8050 // subobject of x as a single function argument (as if by explicit
8051 // qualification; that is, ignoring any possible virtual overriding
8052 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008053 //
8054 // C++03 [class.copy]p13:
8055 // - if the subobject is of class type, the copy assignment operator for
8056 // the class is used (as if by explicit qualification; that is,
8057 // ignoring any possible virtual overriding functions in more derived
8058 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008059 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8060 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008061
Douglas Gregor06a9f362010-05-01 20:49:11 +00008062 // Look for operator=.
8063 DeclarationName Name
8064 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8065 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8066 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008067
Richard Smith044c8aa2012-11-13 00:54:12 +00008068 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8069 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008070 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008071 LookupResult::Filter F = OpLookup.makeFilter();
8072 while (F.hasNext()) {
8073 NamedDecl *D = F.next();
8074 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8075 if (Method->isCopyAssignmentOperator() ||
8076 (!Copying && Method->isMoveAssignmentOperator()))
8077 continue;
8078
8079 F.erase();
8080 }
8081 F.done();
John McCallb0207482010-03-16 06:11:48 +00008082 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008083
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008084 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008085 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008086 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008087 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008088 // ambiguities), we need to cast "this" to that subobject type; to
8089 // ensure that we don't go through the virtual call mechanism, we need
8090 // to qualify the operator= name with the base class (see below). However,
8091 // this means that if the base class has a protected copy assignment
8092 // operator, the protected member access check will fail. So, we
8093 // rewrite "protected" access to "public" access in this case, since we
8094 // know by construction that we're calling from a derived class.
8095 if (CopyingBaseSubobject) {
8096 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8097 L != LEnd; ++L) {
8098 if (L.getAccess() == AS_protected)
8099 L.setAccess(AS_public);
8100 }
8101 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008102
Douglas Gregor06a9f362010-05-01 20:49:11 +00008103 // Create the nested-name-specifier that will be used to qualify the
8104 // reference to operator=; this is required to suppress the virtual
8105 // call mechanism.
8106 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008107 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008108 SS.MakeTrivial(S.Context,
8109 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008110 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008111 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008112
Douglas Gregor06a9f362010-05-01 20:49:11 +00008113 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008114 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008115 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008116 /*TemplateKWLoc=*/SourceLocation(),
8117 /*FirstQualifierInScope=*/0,
8118 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008119 /*TemplateArgs=*/0,
8120 /*SuppressQualifierCheck=*/true);
8121 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008122 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008123
Douglas Gregor06a9f362010-05-01 20:49:11 +00008124 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008125
Richard Smith044c8aa2012-11-13 00:54:12 +00008126 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008127 OpEqualRef.takeAs<Expr>(),
8128 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008129 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008130 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008131
Richard Smith8c889532012-11-14 00:50:40 +00008132 // If we built a call to a trivial 'operator=' while copying an array,
8133 // bail out. We'll replace the whole shebang with a memcpy.
8134 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8135 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8136 return StmtResult((Stmt*)0);
8137
Richard Smith044c8aa2012-11-13 00:54:12 +00008138 // Convert to an expression-statement, and clean up any produced
8139 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008140 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008141 }
John McCallb0207482010-03-16 06:11:48 +00008142
Richard Smith044c8aa2012-11-13 00:54:12 +00008143 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008144 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008145 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008146 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008147 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008148 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008149 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008150 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008151 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008152
8153 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008154 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008155
Douglas Gregor06a9f362010-05-01 20:49:11 +00008156 // Construct a loop over the array bounds, e.g.,
8157 //
8158 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8159 //
8160 // that will copy each of the array elements.
8161 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008162
Douglas Gregor06a9f362010-05-01 20:49:11 +00008163 // Create the iteration variable.
8164 IdentifierInfo *IterationVarName = 0;
8165 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008166 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008167 llvm::raw_svector_ostream OS(Str);
8168 OS << "__i" << Depth;
8169 IterationVarName = &S.Context.Idents.get(OS.str());
8170 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008171 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008172 IterationVarName, SizeType,
8173 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00008174 SC_None, SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008175
Douglas Gregor06a9f362010-05-01 20:49:11 +00008176 // Initialize the iteration variable to zero.
8177 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008178 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008179
8180 // Create a reference to the iteration variable; we'll use this several
8181 // times throughout.
8182 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008183 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008184 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008185 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8186 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8187
Douglas Gregor06a9f362010-05-01 20:49:11 +00008188 // Create the DeclStmt that holds the iteration variable.
8189 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008190
Douglas Gregor06a9f362010-05-01 20:49:11 +00008191 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008192 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008193 IterationVarRefRVal,
8194 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008195 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008196 IterationVarRefRVal,
8197 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008198 if (!Copying) // Cast to rvalue
8199 From = CastForMoving(S, From);
8200
8201 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008202 StmtResult Copy =
8203 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8204 To, From, CopyingBaseSubobject,
8205 Copying, Depth + 1);
8206 // Bail out if copying fails or if we determined that we should use memcpy.
8207 if (Copy.isInvalid() || !Copy.get())
8208 return Copy;
8209
8210 // Create the comparison against the array bound.
8211 llvm::APInt Upper
8212 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8213 Expr *Comparison
8214 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8215 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8216 BO_NE, S.Context.BoolTy,
8217 VK_RValue, OK_Ordinary, Loc, false);
8218
8219 // Create the pre-increment of the iteration variable.
8220 Expr *Increment
8221 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8222 VK_LValue, OK_Ordinary, Loc);
8223
Douglas Gregor06a9f362010-05-01 20:49:11 +00008224 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008225 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008226 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008227 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008228 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008229}
8230
Richard Smith8c889532012-11-14 00:50:40 +00008231static StmtResult
8232buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8233 Expr *To, Expr *From,
8234 bool CopyingBaseSubobject, bool Copying) {
8235 // Maybe we should use a memcpy?
8236 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8237 T.isTriviallyCopyableType(S.Context))
8238 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8239
8240 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8241 CopyingBaseSubobject,
8242 Copying, 0));
8243
8244 // If we ended up picking a trivial assignment operator for an array of a
8245 // non-trivially-copyable class type, just emit a memcpy.
8246 if (!Result.isInvalid() && !Result.get())
8247 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8248
8249 return Result;
8250}
8251
Richard Smithb9d0b762012-07-27 04:22:15 +00008252Sema::ImplicitExceptionSpecification
8253Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8254 CXXRecordDecl *ClassDecl = MD->getParent();
8255
8256 ImplicitExceptionSpecification ExceptSpec(*this);
8257 if (ClassDecl->isInvalidDecl())
8258 return ExceptSpec;
8259
8260 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8261 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8262 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8263
Douglas Gregorb87786f2010-07-01 17:48:08 +00008264 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008265 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008266 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008267
8268 // It is unspecified whether or not an implicit copy assignment operator
8269 // attempts to deduplicate calls to assignment operators of virtual bases are
8270 // made. As such, this exception specification is effectively unspecified.
8271 // Based on a similar decision made for constness in C++0x, we're erring on
8272 // the side of assuming such calls to be made regardless of whether they
8273 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008274 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8275 BaseEnd = ClassDecl->bases_end();
8276 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008277 if (Base->isVirtual())
8278 continue;
8279
Douglas Gregora376d102010-07-02 21:50:04 +00008280 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008281 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008282 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8283 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008284 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008285 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008286
8287 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8288 BaseEnd = ClassDecl->vbases_end();
8289 Base != BaseEnd; ++Base) {
8290 CXXRecordDecl *BaseClassDecl
8291 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8292 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8293 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008294 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008295 }
8296
Douglas Gregorb87786f2010-07-01 17:48:08 +00008297 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8298 FieldEnd = ClassDecl->field_end();
8299 Field != FieldEnd;
8300 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008301 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008302 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8303 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008304 LookupCopyingAssignment(FieldClassDecl,
8305 ArgQuals | FieldType.getCVRQualifiers(),
8306 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008307 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008308 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008309 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008310
Richard Smithb9d0b762012-07-27 04:22:15 +00008311 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008312}
8313
8314CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8315 // Note: The following rules are largely analoguous to the copy
8316 // constructor rules. Note that virtual bases are not taken into account
8317 // for determining the argument type of the operator. Note also that
8318 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008319 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008320
Richard Smithafb49182012-11-29 01:34:07 +00008321 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8322 if (DSM.isAlreadyBeingDeclared())
8323 return 0;
8324
Sean Hunt30de05c2011-05-14 05:23:20 +00008325 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8326 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008327 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008328 ArgType = ArgType.withConst();
8329 ArgType = Context.getLValueReferenceType(ArgType);
8330
Douglas Gregord3c35902010-07-01 16:36:15 +00008331 // An implicitly-declared copy assignment operator is an inline public
8332 // member of its class.
8333 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008334 SourceLocation ClassLoc = ClassDecl->getLocation();
8335 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008336 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008337 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00008338 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00008339 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008340 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008341 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008342 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008343 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008344 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008345
8346 // Build an exception specification pointing back at this member.
8347 FunctionProtoType::ExtProtoInfo EPI;
8348 EPI.ExceptionSpecType = EST_Unevaluated;
8349 EPI.ExceptionSpecDecl = CopyAssignment;
8350 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8351
Douglas Gregord3c35902010-07-01 16:36:15 +00008352 // Add the parameter to the operator.
8353 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008354 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008355 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008356 SC_None,
8357 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008358 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008359
Richard Smithbc2a35d2012-12-08 08:32:28 +00008360 AddOverriddenMethods(ClassDecl, CopyAssignment);
8361
8362 CopyAssignment->setTrivial(
8363 ClassDecl->needsOverloadResolutionForCopyAssignment()
8364 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8365 : ClassDecl->hasTrivialCopyAssignment());
8366
Nico Weberafcc96a2012-01-23 03:19:29 +00008367 // C++0x [class.copy]p19:
8368 // .... If the class definition does not explicitly declare a copy
8369 // assignment operator, there is no user-declared move constructor, and
8370 // there is no user-declared move assignment operator, a copy assignment
8371 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008372 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00008373 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008374
Richard Smithbc2a35d2012-12-08 08:32:28 +00008375 // Note that we have added this copy-assignment operator.
8376 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8377
8378 if (Scope *S = getScopeForContext(ClassDecl))
8379 PushOnScopeChains(CopyAssignment, S, false);
8380 ClassDecl->addDecl(CopyAssignment);
8381
Douglas Gregord3c35902010-07-01 16:36:15 +00008382 return CopyAssignment;
8383}
8384
Douglas Gregor06a9f362010-05-01 20:49:11 +00008385void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8386 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008387 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008388 CopyAssignOperator->isOverloadedOperator() &&
8389 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008390 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8391 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008392 "DefineImplicitCopyAssignment called for wrong function");
8393
8394 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8395
8396 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8397 CopyAssignOperator->setInvalidDecl();
8398 return;
8399 }
8400
8401 CopyAssignOperator->setUsed();
8402
Eli Friedman9a14db32012-10-18 20:14:08 +00008403 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008404 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008405
8406 // C++0x [class.copy]p30:
8407 // The implicitly-defined or explicitly-defaulted copy assignment operator
8408 // for a non-union class X performs memberwise copy assignment of its
8409 // subobjects. The direct base classes of X are assigned first, in the
8410 // order of their declaration in the base-specifier-list, and then the
8411 // immediate non-static data members of X are assigned, in the order in
8412 // which they were declared in the class definition.
8413
8414 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008415 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008416
8417 // The parameter for the "other" object, which we are copying from.
8418 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8419 Qualifiers OtherQuals = Other->getType().getQualifiers();
8420 QualType OtherRefType = Other->getType();
8421 if (const LValueReferenceType *OtherRef
8422 = OtherRefType->getAs<LValueReferenceType>()) {
8423 OtherRefType = OtherRef->getPointeeType();
8424 OtherQuals = OtherRefType.getQualifiers();
8425 }
8426
8427 // Our location for everything implicitly-generated.
8428 SourceLocation Loc = CopyAssignOperator->getLocation();
8429
8430 // Construct a reference to the "other" object. We'll be using this
8431 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008432 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008433 assert(OtherRef && "Reference to parameter cannot fail!");
8434
8435 // Construct the "this" pointer. We'll be using this throughout the generated
8436 // ASTs.
8437 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8438 assert(This && "Reference to this cannot fail!");
8439
8440 // Assign base classes.
8441 bool Invalid = false;
8442 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8443 E = ClassDecl->bases_end(); Base != E; ++Base) {
8444 // Form the assignment:
8445 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8446 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008447 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008448 Invalid = true;
8449 continue;
8450 }
8451
John McCallf871d0c2010-08-07 06:22:56 +00008452 CXXCastPath BasePath;
8453 BasePath.push_back(Base);
8454
Douglas Gregor06a9f362010-05-01 20:49:11 +00008455 // Construct the "from" expression, which is an implicit cast to the
8456 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008457 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008458 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8459 CK_UncheckedDerivedToBase,
8460 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008461
8462 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008463 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008464
8465 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008466 To = ImpCastExprToType(To.take(),
8467 Context.getCVRQualifiedType(BaseType,
8468 CopyAssignOperator->getTypeQualifiers()),
8469 CK_UncheckedDerivedToBase,
8470 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008471
8472 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008473 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008474 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008475 /*CopyingBaseSubobject=*/true,
8476 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008477 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008478 Diag(CurrentLocation, diag::note_member_synthesized_at)
8479 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8480 CopyAssignOperator->setInvalidDecl();
8481 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008482 }
8483
8484 // Success! Record the copy.
8485 Statements.push_back(Copy.takeAs<Expr>());
8486 }
8487
Douglas Gregor06a9f362010-05-01 20:49:11 +00008488 // Assign non-static members.
8489 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8490 FieldEnd = ClassDecl->field_end();
8491 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008492 if (Field->isUnnamedBitfield())
8493 continue;
8494
Douglas Gregor06a9f362010-05-01 20:49:11 +00008495 // Check for members of reference type; we can't copy those.
8496 if (Field->getType()->isReferenceType()) {
8497 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8498 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8499 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008500 Diag(CurrentLocation, diag::note_member_synthesized_at)
8501 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008502 Invalid = true;
8503 continue;
8504 }
8505
8506 // Check for members of const-qualified, non-class type.
8507 QualType BaseType = Context.getBaseElementType(Field->getType());
8508 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8509 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8510 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8511 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008512 Diag(CurrentLocation, diag::note_member_synthesized_at)
8513 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008514 Invalid = true;
8515 continue;
8516 }
John McCallb77115d2011-06-17 00:18:42 +00008517
8518 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008519 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8520 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008521
8522 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008523 if (FieldType->isIncompleteArrayType()) {
8524 assert(ClassDecl->hasFlexibleArrayMember() &&
8525 "Incomplete array type is not valid");
8526 continue;
8527 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008528
8529 // Build references to the field in the object we're copying from and to.
8530 CXXScopeSpec SS; // Intentionally empty
8531 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8532 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008533 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008534 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008535 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008536 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008537 SS, SourceLocation(), 0,
8538 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008539 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008540 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008541 SS, SourceLocation(), 0,
8542 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008543 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8544 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008545
Douglas Gregor06a9f362010-05-01 20:49:11 +00008546 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008547 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008548 To.get(), From.get(),
8549 /*CopyingBaseSubobject=*/false,
8550 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008551 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008552 Diag(CurrentLocation, diag::note_member_synthesized_at)
8553 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8554 CopyAssignOperator->setInvalidDecl();
8555 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008556 }
8557
8558 // Success! Record the copy.
8559 Statements.push_back(Copy.takeAs<Stmt>());
8560 }
8561
8562 if (!Invalid) {
8563 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008564 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008565
John McCall60d7b3a2010-08-24 06:29:42 +00008566 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008567 if (Return.isInvalid())
8568 Invalid = true;
8569 else {
8570 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008571
8572 if (Trap.hasErrorOccurred()) {
8573 Diag(CurrentLocation, diag::note_member_synthesized_at)
8574 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8575 Invalid = true;
8576 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008577 }
8578 }
8579
8580 if (Invalid) {
8581 CopyAssignOperator->setInvalidDecl();
8582 return;
8583 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008584
8585 StmtResult Body;
8586 {
8587 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008588 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008589 /*isStmtExpr=*/false);
8590 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8591 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008592 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008593
8594 if (ASTMutationListener *L = getASTMutationListener()) {
8595 L->CompletedImplicitDefinition(CopyAssignOperator);
8596 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008597}
8598
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008599Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008600Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8601 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008602
Richard Smithb9d0b762012-07-27 04:22:15 +00008603 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008604 if (ClassDecl->isInvalidDecl())
8605 return ExceptSpec;
8606
8607 // C++0x [except.spec]p14:
8608 // An implicitly declared special member function (Clause 12) shall have an
8609 // exception-specification. [...]
8610
8611 // It is unspecified whether or not an implicit move assignment operator
8612 // attempts to deduplicate calls to assignment operators of virtual bases are
8613 // made. As such, this exception specification is effectively unspecified.
8614 // Based on a similar decision made for constness in C++0x, we're erring on
8615 // the side of assuming such calls to be made regardless of whether they
8616 // actually happen.
8617 // Note that a move constructor is not implicitly declared when there are
8618 // virtual bases, but it can still be user-declared and explicitly defaulted.
8619 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8620 BaseEnd = ClassDecl->bases_end();
8621 Base != BaseEnd; ++Base) {
8622 if (Base->isVirtual())
8623 continue;
8624
8625 CXXRecordDecl *BaseClassDecl
8626 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8627 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008628 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008629 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008630 }
8631
8632 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8633 BaseEnd = ClassDecl->vbases_end();
8634 Base != BaseEnd; ++Base) {
8635 CXXRecordDecl *BaseClassDecl
8636 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8637 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008638 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008639 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008640 }
8641
8642 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8643 FieldEnd = ClassDecl->field_end();
8644 Field != FieldEnd;
8645 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008646 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008647 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008648 if (CXXMethodDecl *MoveAssign =
8649 LookupMovingAssignment(FieldClassDecl,
8650 FieldType.getCVRQualifiers(),
8651 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008652 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008653 }
8654 }
8655
8656 return ExceptSpec;
8657}
8658
Richard Smith1c931be2012-04-02 18:40:40 +00008659/// Determine whether the class type has any direct or indirect virtual base
8660/// classes which have a non-trivial move assignment operator.
8661static bool
8662hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8663 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8664 BaseEnd = ClassDecl->vbases_end();
8665 Base != BaseEnd; ++Base) {
8666 CXXRecordDecl *BaseClass =
8667 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8668
8669 // Try to declare the move assignment. If it would be deleted, then the
8670 // class does not have a non-trivial move assignment.
8671 if (BaseClass->needsImplicitMoveAssignment())
8672 S.DeclareImplicitMoveAssignment(BaseClass);
8673
Richard Smith426391c2012-11-16 00:53:38 +00008674 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008675 return true;
8676 }
8677
8678 return false;
8679}
8680
8681/// Determine whether the given type either has a move constructor or is
8682/// trivially copyable.
8683static bool
8684hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8685 Type = S.Context.getBaseElementType(Type);
8686
8687 // FIXME: Technically, non-trivially-copyable non-class types, such as
8688 // reference types, are supposed to return false here, but that appears
8689 // to be a standard defect.
8690 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008691 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008692 return true;
8693
8694 if (Type.isTriviallyCopyableType(S.Context))
8695 return true;
8696
8697 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008698 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8699 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008700 if (ClassDecl->needsImplicitMoveConstructor())
8701 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008702 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008703 }
8704
Richard Smithe5411b72012-12-01 02:35:44 +00008705 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8706 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008707 if (ClassDecl->needsImplicitMoveAssignment())
8708 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008709 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008710}
8711
8712/// Determine whether all non-static data members and direct or virtual bases
8713/// of class \p ClassDecl have either a move operation, or are trivially
8714/// copyable.
8715static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8716 bool IsConstructor) {
8717 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8718 BaseEnd = ClassDecl->bases_end();
8719 Base != BaseEnd; ++Base) {
8720 if (Base->isVirtual())
8721 continue;
8722
8723 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8724 return false;
8725 }
8726
8727 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8728 BaseEnd = ClassDecl->vbases_end();
8729 Base != BaseEnd; ++Base) {
8730 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8731 return false;
8732 }
8733
8734 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8735 FieldEnd = ClassDecl->field_end();
8736 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008737 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008738 return false;
8739 }
8740
8741 return true;
8742}
8743
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008744CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008745 // C++11 [class.copy]p20:
8746 // If the definition of a class X does not explicitly declare a move
8747 // assignment operator, one will be implicitly declared as defaulted
8748 // if and only if:
8749 //
8750 // - [first 4 bullets]
8751 assert(ClassDecl->needsImplicitMoveAssignment());
8752
Richard Smithafb49182012-11-29 01:34:07 +00008753 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8754 if (DSM.isAlreadyBeingDeclared())
8755 return 0;
8756
Richard Smith1c931be2012-04-02 18:40:40 +00008757 // [Checked after we build the declaration]
8758 // - the move assignment operator would not be implicitly defined as
8759 // deleted,
8760
8761 // [DR1402]:
8762 // - X has no direct or indirect virtual base class with a non-trivial
8763 // move assignment operator, and
8764 // - each of X's non-static data members and direct or virtual base classes
8765 // has a type that either has a move assignment operator or is trivially
8766 // copyable.
8767 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8768 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8769 ClassDecl->setFailedImplicitMoveAssignment();
8770 return 0;
8771 }
8772
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008773 // Note: The following rules are largely analoguous to the move
8774 // constructor rules.
8775
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008776 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8777 QualType RetType = Context.getLValueReferenceType(ArgType);
8778 ArgType = Context.getRValueReferenceType(ArgType);
8779
8780 // An implicitly-declared move assignment operator is an inline public
8781 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008782 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8783 SourceLocation ClassLoc = ClassDecl->getLocation();
8784 DeclarationNameInfo NameInfo(Name, ClassLoc);
8785 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008786 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008787 /*TInfo=*/0, /*isStatic=*/false,
8788 /*StorageClassAsWritten=*/SC_None,
8789 /*isInline=*/true,
8790 /*isConstexpr=*/false,
8791 SourceLocation());
8792 MoveAssignment->setAccess(AS_public);
8793 MoveAssignment->setDefaulted();
8794 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008795
Richard Smithb9d0b762012-07-27 04:22:15 +00008796 // Build an exception specification pointing back at this member.
8797 FunctionProtoType::ExtProtoInfo EPI;
8798 EPI.ExceptionSpecType = EST_Unevaluated;
8799 EPI.ExceptionSpecDecl = MoveAssignment;
8800 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8801
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008802 // Add the parameter to the operator.
8803 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8804 ClassLoc, ClassLoc, /*Id=*/0,
8805 ArgType, /*TInfo=*/0,
8806 SC_None,
8807 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008808 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008809
Richard Smithbc2a35d2012-12-08 08:32:28 +00008810 AddOverriddenMethods(ClassDecl, MoveAssignment);
8811
8812 MoveAssignment->setTrivial(
8813 ClassDecl->needsOverloadResolutionForMoveAssignment()
8814 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8815 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008816
8817 // C++0x [class.copy]p9:
8818 // If the definition of a class X does not explicitly declare a move
8819 // assignment operator, one will be implicitly declared as defaulted if and
8820 // only if:
8821 // [...]
8822 // - the move assignment operator would not be implicitly defined as
8823 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008824 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008825 // Cache this result so that we don't try to generate this over and over
8826 // on every lookup, leaking memory and wasting time.
8827 ClassDecl->setFailedImplicitMoveAssignment();
8828 return 0;
8829 }
8830
Richard Smithbc2a35d2012-12-08 08:32:28 +00008831 // Note that we have added this copy-assignment operator.
8832 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8833
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008834 if (Scope *S = getScopeForContext(ClassDecl))
8835 PushOnScopeChains(MoveAssignment, S, false);
8836 ClassDecl->addDecl(MoveAssignment);
8837
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008838 return MoveAssignment;
8839}
8840
8841void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8842 CXXMethodDecl *MoveAssignOperator) {
8843 assert((MoveAssignOperator->isDefaulted() &&
8844 MoveAssignOperator->isOverloadedOperator() &&
8845 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008846 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8847 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008848 "DefineImplicitMoveAssignment called for wrong function");
8849
8850 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8851
8852 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8853 MoveAssignOperator->setInvalidDecl();
8854 return;
8855 }
8856
8857 MoveAssignOperator->setUsed();
8858
Eli Friedman9a14db32012-10-18 20:14:08 +00008859 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008860 DiagnosticErrorTrap Trap(Diags);
8861
8862 // C++0x [class.copy]p28:
8863 // The implicitly-defined or move assignment operator for a non-union class
8864 // X performs memberwise move assignment of its subobjects. The direct base
8865 // classes of X are assigned first, in the order of their declaration in the
8866 // base-specifier-list, and then the immediate non-static data members of X
8867 // are assigned, in the order in which they were declared in the class
8868 // definition.
8869
8870 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008871 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008872
8873 // The parameter for the "other" object, which we are move from.
8874 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8875 QualType OtherRefType = Other->getType()->
8876 getAs<RValueReferenceType>()->getPointeeType();
8877 assert(OtherRefType.getQualifiers() == 0 &&
8878 "Bad argument type of defaulted move assignment");
8879
8880 // Our location for everything implicitly-generated.
8881 SourceLocation Loc = MoveAssignOperator->getLocation();
8882
8883 // Construct a reference to the "other" object. We'll be using this
8884 // throughout the generated ASTs.
8885 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8886 assert(OtherRef && "Reference to parameter cannot fail!");
8887 // Cast to rvalue.
8888 OtherRef = CastForMoving(*this, OtherRef);
8889
8890 // Construct the "this" pointer. We'll be using this throughout the generated
8891 // ASTs.
8892 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8893 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008894
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008895 // Assign base classes.
8896 bool Invalid = false;
8897 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8898 E = ClassDecl->bases_end(); Base != E; ++Base) {
8899 // Form the assignment:
8900 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8901 QualType BaseType = Base->getType().getUnqualifiedType();
8902 if (!BaseType->isRecordType()) {
8903 Invalid = true;
8904 continue;
8905 }
8906
8907 CXXCastPath BasePath;
8908 BasePath.push_back(Base);
8909
8910 // Construct the "from" expression, which is an implicit cast to the
8911 // appropriately-qualified base type.
8912 Expr *From = OtherRef;
8913 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008914 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008915
8916 // Dereference "this".
8917 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8918
8919 // Implicitly cast "this" to the appropriately-qualified base type.
8920 To = ImpCastExprToType(To.take(),
8921 Context.getCVRQualifiedType(BaseType,
8922 MoveAssignOperator->getTypeQualifiers()),
8923 CK_UncheckedDerivedToBase,
8924 VK_LValue, &BasePath);
8925
8926 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00008927 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008928 To.get(), From,
8929 /*CopyingBaseSubobject=*/true,
8930 /*Copying=*/false);
8931 if (Move.isInvalid()) {
8932 Diag(CurrentLocation, diag::note_member_synthesized_at)
8933 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8934 MoveAssignOperator->setInvalidDecl();
8935 return;
8936 }
8937
8938 // Success! Record the move.
8939 Statements.push_back(Move.takeAs<Expr>());
8940 }
8941
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008942 // Assign non-static members.
8943 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8944 FieldEnd = ClassDecl->field_end();
8945 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008946 if (Field->isUnnamedBitfield())
8947 continue;
8948
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008949 // Check for members of reference type; we can't move those.
8950 if (Field->getType()->isReferenceType()) {
8951 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8952 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8953 Diag(Field->getLocation(), diag::note_declared_at);
8954 Diag(CurrentLocation, diag::note_member_synthesized_at)
8955 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8956 Invalid = true;
8957 continue;
8958 }
8959
8960 // Check for members of const-qualified, non-class type.
8961 QualType BaseType = Context.getBaseElementType(Field->getType());
8962 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8963 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8964 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8965 Diag(Field->getLocation(), diag::note_declared_at);
8966 Diag(CurrentLocation, diag::note_member_synthesized_at)
8967 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8968 Invalid = true;
8969 continue;
8970 }
8971
8972 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008973 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8974 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008975
8976 QualType FieldType = Field->getType().getNonReferenceType();
8977 if (FieldType->isIncompleteArrayType()) {
8978 assert(ClassDecl->hasFlexibleArrayMember() &&
8979 "Incomplete array type is not valid");
8980 continue;
8981 }
8982
8983 // Build references to the field in the object we're copying from and to.
8984 CXXScopeSpec SS; // Intentionally empty
8985 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8986 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008987 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008988 MemberLookup.resolveKind();
8989 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8990 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008991 SS, SourceLocation(), 0,
8992 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008993 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8994 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008995 SS, SourceLocation(), 0,
8996 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008997 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8998 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8999
9000 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9001 "Member reference with rvalue base must be rvalue except for reference "
9002 "members, which aren't allowed for move assignment.");
9003
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009004 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009005 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009006 To.get(), From.get(),
9007 /*CopyingBaseSubobject=*/false,
9008 /*Copying=*/false);
9009 if (Move.isInvalid()) {
9010 Diag(CurrentLocation, diag::note_member_synthesized_at)
9011 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9012 MoveAssignOperator->setInvalidDecl();
9013 return;
9014 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009015
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009016 // Success! Record the copy.
9017 Statements.push_back(Move.takeAs<Stmt>());
9018 }
9019
9020 if (!Invalid) {
9021 // Add a "return *this;"
9022 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9023
9024 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9025 if (Return.isInvalid())
9026 Invalid = true;
9027 else {
9028 Statements.push_back(Return.takeAs<Stmt>());
9029
9030 if (Trap.hasErrorOccurred()) {
9031 Diag(CurrentLocation, diag::note_member_synthesized_at)
9032 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9033 Invalid = true;
9034 }
9035 }
9036 }
9037
9038 if (Invalid) {
9039 MoveAssignOperator->setInvalidDecl();
9040 return;
9041 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009042
9043 StmtResult Body;
9044 {
9045 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009046 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009047 /*isStmtExpr=*/false);
9048 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9049 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009050 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9051
9052 if (ASTMutationListener *L = getASTMutationListener()) {
9053 L->CompletedImplicitDefinition(MoveAssignOperator);
9054 }
9055}
9056
Richard Smithb9d0b762012-07-27 04:22:15 +00009057Sema::ImplicitExceptionSpecification
9058Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9059 CXXRecordDecl *ClassDecl = MD->getParent();
9060
9061 ImplicitExceptionSpecification ExceptSpec(*this);
9062 if (ClassDecl->isInvalidDecl())
9063 return ExceptSpec;
9064
9065 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9066 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9067 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9068
Douglas Gregor0d405db2010-07-01 20:59:04 +00009069 // C++ [except.spec]p14:
9070 // An implicitly declared special member function (Clause 12) shall have an
9071 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009072 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9073 BaseEnd = ClassDecl->bases_end();
9074 Base != BaseEnd;
9075 ++Base) {
9076 // Virtual bases are handled below.
9077 if (Base->isVirtual())
9078 continue;
9079
Douglas Gregor22584312010-07-02 23:41:54 +00009080 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009081 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009082 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009083 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009084 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009085 }
9086 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9087 BaseEnd = ClassDecl->vbases_end();
9088 Base != BaseEnd;
9089 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009090 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009091 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009092 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009093 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009094 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009095 }
9096 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9097 FieldEnd = ClassDecl->field_end();
9098 Field != FieldEnd;
9099 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009100 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009101 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9102 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009103 LookupCopyingConstructor(FieldClassDecl,
9104 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009105 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009106 }
9107 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009108
Richard Smithb9d0b762012-07-27 04:22:15 +00009109 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009110}
9111
9112CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9113 CXXRecordDecl *ClassDecl) {
9114 // C++ [class.copy]p4:
9115 // If the class definition does not explicitly declare a copy
9116 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009117 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009118
Richard Smithafb49182012-11-29 01:34:07 +00009119 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9120 if (DSM.isAlreadyBeingDeclared())
9121 return 0;
9122
Sean Hunt49634cf2011-05-13 06:10:58 +00009123 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9124 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009125 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009126 if (Const)
9127 ArgType = ArgType.withConst();
9128 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009129
Richard Smith7756afa2012-06-10 05:43:50 +00009130 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9131 CXXCopyConstructor,
9132 Const);
9133
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009134 DeclarationName Name
9135 = Context.DeclarationNames.getCXXConstructorName(
9136 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009137 SourceLocation ClassLoc = ClassDecl->getLocation();
9138 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009139
9140 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009141 // member of its class.
9142 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009143 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009144 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009145 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009146 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009147 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009148
Richard Smithb9d0b762012-07-27 04:22:15 +00009149 // Build an exception specification pointing back at this member.
9150 FunctionProtoType::ExtProtoInfo EPI;
9151 EPI.ExceptionSpecType = EST_Unevaluated;
9152 EPI.ExceptionSpecDecl = CopyConstructor;
9153 CopyConstructor->setType(
9154 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9155
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009156 // Add the parameter to the constructor.
9157 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009158 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009159 /*IdentifierInfo=*/0,
9160 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009161 SC_None,
9162 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009163 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009164
Richard Smithbc2a35d2012-12-08 08:32:28 +00009165 CopyConstructor->setTrivial(
9166 ClassDecl->needsOverloadResolutionForCopyConstructor()
9167 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9168 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009169
Nico Weberafcc96a2012-01-23 03:19:29 +00009170 // C++11 [class.copy]p8:
9171 // ... If the class definition does not explicitly declare a copy
9172 // constructor, there is no user-declared move constructor, and there is no
9173 // user-declared move assignment operator, a copy constructor is implicitly
9174 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009175 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00009176 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00009177
Richard Smithbc2a35d2012-12-08 08:32:28 +00009178 // Note that we have declared this constructor.
9179 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9180
9181 if (Scope *S = getScopeForContext(ClassDecl))
9182 PushOnScopeChains(CopyConstructor, S, false);
9183 ClassDecl->addDecl(CopyConstructor);
9184
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009185 return CopyConstructor;
9186}
9187
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009188void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009189 CXXConstructorDecl *CopyConstructor) {
9190 assert((CopyConstructor->isDefaulted() &&
9191 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009192 !CopyConstructor->doesThisDeclarationHaveABody() &&
9193 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009194 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009195
Anders Carlsson63010a72010-04-23 16:24:12 +00009196 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009197 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009198
Eli Friedman9a14db32012-10-18 20:14:08 +00009199 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009200 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009201
David Blaikie93c86172013-01-17 05:26:25 +00009202 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009203 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009204 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009205 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009206 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009207 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009208 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009209 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9210 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009211 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009212 /*isStmtExpr=*/false)
9213 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009214 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009215 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009216
9217 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009218 if (ASTMutationListener *L = getASTMutationListener()) {
9219 L->CompletedImplicitDefinition(CopyConstructor);
9220 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009221}
9222
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009223Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009224Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9225 CXXRecordDecl *ClassDecl = MD->getParent();
9226
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009227 // C++ [except.spec]p14:
9228 // An implicitly declared special member function (Clause 12) shall have an
9229 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009230 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009231 if (ClassDecl->isInvalidDecl())
9232 return ExceptSpec;
9233
9234 // Direct base-class constructors.
9235 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9236 BEnd = ClassDecl->bases_end();
9237 B != BEnd; ++B) {
9238 if (B->isVirtual()) // Handled below.
9239 continue;
9240
9241 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9242 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009243 CXXConstructorDecl *Constructor =
9244 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009245 // If this is a deleted function, add it anyway. This might be conformant
9246 // with the standard. This might not. I'm not sure. It might not matter.
9247 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009248 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009249 }
9250 }
9251
9252 // Virtual base-class constructors.
9253 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9254 BEnd = ClassDecl->vbases_end();
9255 B != BEnd; ++B) {
9256 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9257 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009258 CXXConstructorDecl *Constructor =
9259 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009260 // If this is a deleted function, add it anyway. This might be conformant
9261 // with the standard. This might not. I'm not sure. It might not matter.
9262 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009263 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009264 }
9265 }
9266
9267 // Field constructors.
9268 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9269 FEnd = ClassDecl->field_end();
9270 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009271 QualType FieldType = Context.getBaseElementType(F->getType());
9272 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9273 CXXConstructorDecl *Constructor =
9274 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009275 // If this is a deleted function, add it anyway. This might be conformant
9276 // with the standard. This might not. I'm not sure. It might not matter.
9277 // In particular, the problem is that this function never gets called. It
9278 // might just be ill-formed because this function attempts to refer to
9279 // a deleted function here.
9280 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009281 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009282 }
9283 }
9284
9285 return ExceptSpec;
9286}
9287
9288CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9289 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009290 // C++11 [class.copy]p9:
9291 // If the definition of a class X does not explicitly declare a move
9292 // constructor, one will be implicitly declared as defaulted if and only if:
9293 //
9294 // - [first 4 bullets]
9295 assert(ClassDecl->needsImplicitMoveConstructor());
9296
Richard Smithafb49182012-11-29 01:34:07 +00009297 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9298 if (DSM.isAlreadyBeingDeclared())
9299 return 0;
9300
Richard Smith1c931be2012-04-02 18:40:40 +00009301 // [Checked after we build the declaration]
9302 // - the move assignment operator would not be implicitly defined as
9303 // deleted,
9304
9305 // [DR1402]:
9306 // - each of X's non-static data members and direct or virtual base classes
9307 // has a type that either has a move constructor or is trivially copyable.
9308 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9309 ClassDecl->setFailedImplicitMoveConstructor();
9310 return 0;
9311 }
9312
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009313 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9314 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009315
Richard Smith7756afa2012-06-10 05:43:50 +00009316 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9317 CXXMoveConstructor,
9318 false);
9319
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009320 DeclarationName Name
9321 = Context.DeclarationNames.getCXXConstructorName(
9322 Context.getCanonicalType(ClassType));
9323 SourceLocation ClassLoc = ClassDecl->getLocation();
9324 DeclarationNameInfo NameInfo(Name, ClassLoc);
9325
9326 // C++0x [class.copy]p11:
9327 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009328 // member of its class.
9329 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009330 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009331 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009332 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009333 MoveConstructor->setAccess(AS_public);
9334 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009335
Richard Smithb9d0b762012-07-27 04:22:15 +00009336 // Build an exception specification pointing back at this member.
9337 FunctionProtoType::ExtProtoInfo EPI;
9338 EPI.ExceptionSpecType = EST_Unevaluated;
9339 EPI.ExceptionSpecDecl = MoveConstructor;
9340 MoveConstructor->setType(
9341 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9342
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009343 // Add the parameter to the constructor.
9344 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9345 ClassLoc, ClassLoc,
9346 /*IdentifierInfo=*/0,
9347 ArgType, /*TInfo=*/0,
9348 SC_None,
9349 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009350 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009351
Richard Smithbc2a35d2012-12-08 08:32:28 +00009352 MoveConstructor->setTrivial(
9353 ClassDecl->needsOverloadResolutionForMoveConstructor()
9354 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9355 : ClassDecl->hasTrivialMoveConstructor());
9356
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009357 // C++0x [class.copy]p9:
9358 // If the definition of a class X does not explicitly declare a move
9359 // constructor, one will be implicitly declared as defaulted if and only if:
9360 // [...]
9361 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009362 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009363 // Cache this result so that we don't try to generate this over and over
9364 // on every lookup, leaking memory and wasting time.
9365 ClassDecl->setFailedImplicitMoveConstructor();
9366 return 0;
9367 }
9368
9369 // Note that we have declared this constructor.
9370 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9371
9372 if (Scope *S = getScopeForContext(ClassDecl))
9373 PushOnScopeChains(MoveConstructor, S, false);
9374 ClassDecl->addDecl(MoveConstructor);
9375
9376 return MoveConstructor;
9377}
9378
9379void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9380 CXXConstructorDecl *MoveConstructor) {
9381 assert((MoveConstructor->isDefaulted() &&
9382 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009383 !MoveConstructor->doesThisDeclarationHaveABody() &&
9384 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009385 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9386
9387 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9388 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9389
Eli Friedman9a14db32012-10-18 20:14:08 +00009390 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009391 DiagnosticErrorTrap Trap(Diags);
9392
David Blaikie93c86172013-01-17 05:26:25 +00009393 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009394 Trap.hasErrorOccurred()) {
9395 Diag(CurrentLocation, diag::note_member_synthesized_at)
9396 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9397 MoveConstructor->setInvalidDecl();
9398 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009399 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009400 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9401 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009402 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009403 /*isStmtExpr=*/false)
9404 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009405 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009406 }
9407
9408 MoveConstructor->setUsed();
9409
9410 if (ASTMutationListener *L = getASTMutationListener()) {
9411 L->CompletedImplicitDefinition(MoveConstructor);
9412 }
9413}
9414
Douglas Gregore4e68d42012-02-15 19:33:52 +00009415bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9416 return FD->isDeleted() &&
9417 (FD->isDefaulted() || FD->isImplicit()) &&
9418 isa<CXXMethodDecl>(FD);
9419}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009420
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009421/// \brief Mark the call operator of the given lambda closure type as "used".
9422static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9423 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009424 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009425 Lambda->lookup(
9426 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009427 CallOperator->setReferenced();
9428 CallOperator->setUsed();
9429}
9430
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009431void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9432 SourceLocation CurrentLocation,
9433 CXXConversionDecl *Conv)
9434{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009435 CXXRecordDecl *Lambda = Conv->getParent();
9436
9437 // Make sure that the lambda call operator is marked used.
9438 markLambdaCallOperatorUsed(*this, Lambda);
9439
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009440 Conv->setUsed();
9441
Eli Friedman9a14db32012-10-18 20:14:08 +00009442 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009443 DiagnosticErrorTrap Trap(Diags);
9444
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009445 // Return the address of the __invoke function.
9446 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9447 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009448 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009449 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9450 VK_LValue, Conv->getLocation()).take();
9451 assert(FunctionRef && "Can't refer to __invoke function?");
9452 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009453 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009454 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009455 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009456
9457 // Fill in the __invoke function with a dummy implementation. IR generation
9458 // will fill in the actual details.
9459 Invoke->setUsed();
9460 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009461 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009462
9463 if (ASTMutationListener *L = getASTMutationListener()) {
9464 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009465 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009466 }
9467}
9468
9469void Sema::DefineImplicitLambdaToBlockPointerConversion(
9470 SourceLocation CurrentLocation,
9471 CXXConversionDecl *Conv)
9472{
9473 Conv->setUsed();
9474
Eli Friedman9a14db32012-10-18 20:14:08 +00009475 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009476 DiagnosticErrorTrap Trap(Diags);
9477
Douglas Gregorac1303e2012-02-22 05:02:47 +00009478 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009479 Expr *This = ActOnCXXThis(CurrentLocation).take();
9480 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009481
Eli Friedman23f02672012-03-01 04:01:32 +00009482 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9483 Conv->getLocation(),
9484 Conv, DerefThis);
9485
9486 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9487 // behavior. Note that only the general conversion function does this
9488 // (since it's unusable otherwise); in the case where we inline the
9489 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009490 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009491 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9492 CK_CopyAndAutoreleaseBlockObject,
9493 BuildBlock.get(), 0, VK_RValue);
9494
9495 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009496 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009497 Conv->setInvalidDecl();
9498 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009499 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009500
Douglas Gregorac1303e2012-02-22 05:02:47 +00009501 // Create the return statement that returns the block from the conversion
9502 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009503 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009504 if (Return.isInvalid()) {
9505 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9506 Conv->setInvalidDecl();
9507 return;
9508 }
9509
9510 // Set the body of the conversion function.
9511 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009512 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009513 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009514 Conv->getLocation()));
9515
Douglas Gregorac1303e2012-02-22 05:02:47 +00009516 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009517 if (ASTMutationListener *L = getASTMutationListener()) {
9518 L->CompletedImplicitDefinition(Conv);
9519 }
9520}
9521
Douglas Gregorf52757d2012-03-10 06:53:13 +00009522/// \brief Determine whether the given list arguments contains exactly one
9523/// "real" (non-default) argument.
9524static bool hasOneRealArgument(MultiExprArg Args) {
9525 switch (Args.size()) {
9526 case 0:
9527 return false;
9528
9529 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009530 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009531 return false;
9532
9533 // fall through
9534 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009535 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009536 }
9537
9538 return false;
9539}
9540
John McCall60d7b3a2010-08-24 06:29:42 +00009541ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009542Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009543 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009544 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009545 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009546 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009547 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009548 unsigned ConstructKind,
9549 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009550 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009551
Douglas Gregor2f599792010-04-02 18:24:57 +00009552 // C++0x [class.copy]p34:
9553 // When certain criteria are met, an implementation is allowed to
9554 // omit the copy/move construction of a class object, even if the
9555 // copy/move constructor and/or destructor for the object have
9556 // side effects. [...]
9557 // - when a temporary class object that has not been bound to a
9558 // reference (12.2) would be copied/moved to a class object
9559 // with the same cv-unqualified type, the copy/move operation
9560 // can be omitted by constructing the temporary object
9561 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009562 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009563 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009564 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009565 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009566 }
Mike Stump1eb44332009-09-09 15:08:12 +00009567
9568 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009569 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009570 IsListInitialization, RequiresZeroInit,
9571 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009572}
9573
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009574/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9575/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009576ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009577Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9578 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009579 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009580 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009581 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009582 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009583 unsigned ConstructKind,
9584 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009585 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009586 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009587 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +00009588 HadMultipleCandidates,
9589 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009590 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9591 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009592}
9593
John McCall68c6c9a2010-02-02 09:10:11 +00009594void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009595 if (VD->isInvalidDecl()) return;
9596
John McCall68c6c9a2010-02-02 09:10:11 +00009597 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009598 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009599 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009600 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009601
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009602 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009603 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009604 CheckDestructorAccess(VD->getLocation(), Destructor,
9605 PDiag(diag::err_access_dtor_var)
9606 << VD->getDeclName()
9607 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009608 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009609
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009610 if (!VD->hasGlobalStorage()) return;
9611
9612 // Emit warning for non-trivial dtor in global scope (a real global,
9613 // class-static, function-static).
9614 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9615
9616 // TODO: this should be re-enabled for static locals by !CXAAtExit
9617 if (!VD->isStaticLocal())
9618 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009619}
9620
Douglas Gregor39da0b82009-09-09 23:08:42 +00009621/// \brief Given a constructor and the set of arguments provided for the
9622/// constructor, convert the arguments and add any required default arguments
9623/// to form a proper call to this constructor.
9624///
9625/// \returns true if an error occurred, false otherwise.
9626bool
9627Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9628 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009629 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009630 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009631 bool AllowExplicit,
9632 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009633 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9634 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009635 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009636
9637 const FunctionProtoType *Proto
9638 = Constructor->getType()->getAs<FunctionProtoType>();
9639 assert(Proto && "Constructor without a prototype?");
9640 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009641
9642 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009643 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009644 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009645 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009646 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009647
9648 VariadicCallType CallType =
9649 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009650 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009651 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9652 Proto, 0, Args, NumArgs, AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009653 CallType, AllowExplicit,
9654 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009655 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009656
9657 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9658
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00009659 CheckConstructorCall(Constructor,
9660 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9661 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +00009662 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009663
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009664 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009665}
9666
Anders Carlsson20d45d22009-12-12 00:32:00 +00009667static inline bool
9668CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9669 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009670 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009671 if (isa<NamespaceDecl>(DC)) {
9672 return SemaRef.Diag(FnDecl->getLocation(),
9673 diag::err_operator_new_delete_declared_in_namespace)
9674 << FnDecl->getDeclName();
9675 }
9676
9677 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009678 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009679 return SemaRef.Diag(FnDecl->getLocation(),
9680 diag::err_operator_new_delete_declared_static)
9681 << FnDecl->getDeclName();
9682 }
9683
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009684 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009685}
9686
Anders Carlsson156c78e2009-12-13 17:53:43 +00009687static inline bool
9688CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9689 CanQualType ExpectedResultType,
9690 CanQualType ExpectedFirstParamType,
9691 unsigned DependentParamTypeDiag,
9692 unsigned InvalidParamTypeDiag) {
9693 QualType ResultType =
9694 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9695
9696 // Check that the result type is not dependent.
9697 if (ResultType->isDependentType())
9698 return SemaRef.Diag(FnDecl->getLocation(),
9699 diag::err_operator_new_delete_dependent_result_type)
9700 << FnDecl->getDeclName() << ExpectedResultType;
9701
9702 // Check that the result type is what we expect.
9703 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9704 return SemaRef.Diag(FnDecl->getLocation(),
9705 diag::err_operator_new_delete_invalid_result_type)
9706 << FnDecl->getDeclName() << ExpectedResultType;
9707
9708 // A function template must have at least 2 parameters.
9709 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9710 return SemaRef.Diag(FnDecl->getLocation(),
9711 diag::err_operator_new_delete_template_too_few_parameters)
9712 << FnDecl->getDeclName();
9713
9714 // The function decl must have at least 1 parameter.
9715 if (FnDecl->getNumParams() == 0)
9716 return SemaRef.Diag(FnDecl->getLocation(),
9717 diag::err_operator_new_delete_too_few_parameters)
9718 << FnDecl->getDeclName();
9719
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009720 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009721 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9722 if (FirstParamType->isDependentType())
9723 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9724 << FnDecl->getDeclName() << ExpectedFirstParamType;
9725
9726 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009727 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009728 ExpectedFirstParamType)
9729 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9730 << FnDecl->getDeclName() << ExpectedFirstParamType;
9731
9732 return false;
9733}
9734
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009735static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009736CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009737 // C++ [basic.stc.dynamic.allocation]p1:
9738 // A program is ill-formed if an allocation function is declared in a
9739 // namespace scope other than global scope or declared static in global
9740 // scope.
9741 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9742 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009743
9744 CanQualType SizeTy =
9745 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9746
9747 // C++ [basic.stc.dynamic.allocation]p1:
9748 // The return type shall be void*. The first parameter shall have type
9749 // std::size_t.
9750 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9751 SizeTy,
9752 diag::err_operator_new_dependent_param_type,
9753 diag::err_operator_new_param_type))
9754 return true;
9755
9756 // C++ [basic.stc.dynamic.allocation]p1:
9757 // The first parameter shall not have an associated default argument.
9758 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009759 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009760 diag::err_operator_new_default_arg)
9761 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9762
9763 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009764}
9765
9766static bool
Richard Smith444d3842012-10-20 08:26:51 +00009767CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009768 // C++ [basic.stc.dynamic.deallocation]p1:
9769 // A program is ill-formed if deallocation functions are declared in a
9770 // namespace scope other than global scope or declared static in global
9771 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009772 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9773 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009774
9775 // C++ [basic.stc.dynamic.deallocation]p2:
9776 // Each deallocation function shall return void and its first parameter
9777 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009778 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9779 SemaRef.Context.VoidPtrTy,
9780 diag::err_operator_delete_dependent_param_type,
9781 diag::err_operator_delete_param_type))
9782 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009783
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009784 return false;
9785}
9786
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009787/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9788/// of this overloaded operator is well-formed. If so, returns false;
9789/// otherwise, emits appropriate diagnostics and returns true.
9790bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009791 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009792 "Expected an overloaded operator declaration");
9793
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009794 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9795
Mike Stump1eb44332009-09-09 15:08:12 +00009796 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009797 // The allocation and deallocation functions, operator new,
9798 // operator new[], operator delete and operator delete[], are
9799 // described completely in 3.7.3. The attributes and restrictions
9800 // found in the rest of this subclause do not apply to them unless
9801 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009802 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009803 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009804
Anders Carlssona3ccda52009-12-12 00:26:23 +00009805 if (Op == OO_New || Op == OO_Array_New)
9806 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009807
9808 // C++ [over.oper]p6:
9809 // An operator function shall either be a non-static member
9810 // function or be a non-member function and have at least one
9811 // parameter whose type is a class, a reference to a class, an
9812 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009813 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9814 if (MethodDecl->isStatic())
9815 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009816 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009817 } else {
9818 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009819 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9820 ParamEnd = FnDecl->param_end();
9821 Param != ParamEnd; ++Param) {
9822 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009823 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9824 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009825 ClassOrEnumParam = true;
9826 break;
9827 }
9828 }
9829
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009830 if (!ClassOrEnumParam)
9831 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009832 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009833 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009834 }
9835
9836 // C++ [over.oper]p8:
9837 // An operator function cannot have default arguments (8.3.6),
9838 // except where explicitly stated below.
9839 //
Mike Stump1eb44332009-09-09 15:08:12 +00009840 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009841 // (C++ [over.call]p1).
9842 if (Op != OO_Call) {
9843 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9844 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009845 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009846 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009847 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009848 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009849 }
9850 }
9851
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009852 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9853 { false, false, false }
9854#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9855 , { Unary, Binary, MemberOnly }
9856#include "clang/Basic/OperatorKinds.def"
9857 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009858
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009859 bool CanBeUnaryOperator = OperatorUses[Op][0];
9860 bool CanBeBinaryOperator = OperatorUses[Op][1];
9861 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009862
9863 // C++ [over.oper]p8:
9864 // [...] Operator functions cannot have more or fewer parameters
9865 // than the number required for the corresponding operator, as
9866 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009867 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009868 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009869 if (Op != OO_Call &&
9870 ((NumParams == 1 && !CanBeUnaryOperator) ||
9871 (NumParams == 2 && !CanBeBinaryOperator) ||
9872 (NumParams < 1) || (NumParams > 2))) {
9873 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009874 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009875 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009876 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009877 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009878 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009879 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009880 assert(CanBeBinaryOperator &&
9881 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009882 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009883 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009884
Chris Lattner416e46f2008-11-21 07:57:12 +00009885 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009886 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009887 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009888
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009889 // Overloaded operators other than operator() cannot be variadic.
9890 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009891 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009892 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009893 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009894 }
9895
9896 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009897 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9898 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009899 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009900 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009901 }
9902
9903 // C++ [over.inc]p1:
9904 // The user-defined function called operator++ implements the
9905 // prefix and postfix ++ operator. If this function is a member
9906 // function with no parameters, or a non-member function with one
9907 // parameter of class or enumeration type, it defines the prefix
9908 // increment operator ++ for objects of that type. If the function
9909 // is a member function with one parameter (which shall be of type
9910 // int) or a non-member function with two parameters (the second
9911 // of which shall be of type int), it defines the postfix
9912 // increment operator ++ for objects of that type.
9913 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9914 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9915 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009916 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009917 ParamIsInt = BT->getKind() == BuiltinType::Int;
9918
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009919 if (!ParamIsInt)
9920 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009921 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009922 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009923 }
9924
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009925 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009926}
Chris Lattner5a003a42008-12-17 07:09:26 +00009927
Sean Hunta6c058d2010-01-13 09:01:02 +00009928/// CheckLiteralOperatorDeclaration - Check whether the declaration
9929/// of this literal operator function is well-formed. If so, returns
9930/// false; otherwise, emits appropriate diagnostics and returns true.
9931bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009932 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009933 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9934 << FnDecl->getDeclName();
9935 return true;
9936 }
9937
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009938 if (FnDecl->isExternC()) {
9939 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9940 return true;
9941 }
9942
Sean Hunta6c058d2010-01-13 09:01:02 +00009943 bool Valid = false;
9944
Richard Smith36f5cfe2012-03-09 08:00:36 +00009945 // This might be the definition of a literal operator template.
9946 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9947 // This might be a specialization of a literal operator template.
9948 if (!TpDecl)
9949 TpDecl = FnDecl->getPrimaryTemplate();
9950
Sean Hunt216c2782010-04-07 23:11:06 +00009951 // template <char...> type operator "" name() is the only valid template
9952 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009953 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009954 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009955 // Must have only one template parameter
9956 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9957 if (Params->size() == 1) {
9958 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009959 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009960
Sean Hunt216c2782010-04-07 23:11:06 +00009961 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009962 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9963 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9964 Valid = true;
9965 }
9966 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009967 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009968 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009969 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9970
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009971 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009972
Sean Hunt30019c02010-04-07 22:57:35 +00009973 // unsigned long long int, long double, and any character type are allowed
9974 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009975 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9976 Context.hasSameType(T, Context.LongDoubleTy) ||
9977 Context.hasSameType(T, Context.CharTy) ||
9978 Context.hasSameType(T, Context.WCharTy) ||
9979 Context.hasSameType(T, Context.Char16Ty) ||
9980 Context.hasSameType(T, Context.Char32Ty)) {
9981 if (++Param == FnDecl->param_end())
9982 Valid = true;
9983 goto FinishedParams;
9984 }
9985
Sean Hunt30019c02010-04-07 22:57:35 +00009986 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009987 const PointerType *PT = T->getAs<PointerType>();
9988 if (!PT)
9989 goto FinishedParams;
9990 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009991 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009992 goto FinishedParams;
9993 T = T.getUnqualifiedType();
9994
9995 // Move on to the second parameter;
9996 ++Param;
9997
9998 // If there is no second parameter, the first must be a const char *
9999 if (Param == FnDecl->param_end()) {
10000 if (Context.hasSameType(T, Context.CharTy))
10001 Valid = true;
10002 goto FinishedParams;
10003 }
10004
10005 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10006 // are allowed as the first parameter to a two-parameter function
10007 if (!(Context.hasSameType(T, Context.CharTy) ||
10008 Context.hasSameType(T, Context.WCharTy) ||
10009 Context.hasSameType(T, Context.Char16Ty) ||
10010 Context.hasSameType(T, Context.Char32Ty)))
10011 goto FinishedParams;
10012
10013 // The second and final parameter must be an std::size_t
10014 T = (*Param)->getType().getUnqualifiedType();
10015 if (Context.hasSameType(T, Context.getSizeType()) &&
10016 ++Param == FnDecl->param_end())
10017 Valid = true;
10018 }
10019
10020 // FIXME: This diagnostic is absolutely terrible.
10021FinishedParams:
10022 if (!Valid) {
10023 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10024 << FnDecl->getDeclName();
10025 return true;
10026 }
10027
Richard Smitha9e88b22012-03-09 08:16:22 +000010028 // A parameter-declaration-clause containing a default argument is not
10029 // equivalent to any of the permitted forms.
10030 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10031 ParamEnd = FnDecl->param_end();
10032 Param != ParamEnd; ++Param) {
10033 if ((*Param)->hasDefaultArg()) {
10034 Diag((*Param)->getDefaultArgRange().getBegin(),
10035 diag::err_literal_operator_default_argument)
10036 << (*Param)->getDefaultArgRange();
10037 break;
10038 }
10039 }
10040
Richard Smith2fb4ae32012-03-08 02:39:21 +000010041 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010042 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10043 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010044 // C++11 [usrlit.suffix]p1:
10045 // Literal suffix identifiers that do not start with an underscore
10046 // are reserved for future standardization.
10047 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010048 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010049
Sean Hunta6c058d2010-01-13 09:01:02 +000010050 return false;
10051}
10052
Douglas Gregor074149e2009-01-05 19:45:36 +000010053/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10054/// linkage specification, including the language and (if present)
10055/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10056/// the location of the language string literal, which is provided
10057/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10058/// the '{' brace. Otherwise, this linkage specification does not
10059/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010060Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10061 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010062 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010063 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010064 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010065 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010066 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010067 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010068 Language = LinkageSpecDecl::lang_cxx;
10069 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010070 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010071 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010072 }
Mike Stump1eb44332009-09-09 15:08:12 +000010073
Chris Lattnercc98eac2008-12-17 07:13:27 +000010074 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010075
Douglas Gregor074149e2009-01-05 19:45:36 +000010076 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010077 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010078 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010079 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010080 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010081}
10082
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010083/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010084/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10085/// valid, it's the position of the closing '}' brace in a linkage
10086/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010087Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010088 Decl *LinkageSpec,
10089 SourceLocation RBraceLoc) {
10090 if (LinkageSpec) {
10091 if (RBraceLoc.isValid()) {
10092 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10093 LSDecl->setRBraceLoc(RBraceLoc);
10094 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010095 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010096 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010097 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010098}
10099
Michael Han684aa732013-02-22 17:15:32 +000010100Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10101 AttributeList *AttrList,
10102 SourceLocation SemiLoc) {
10103 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10104 // Attribute declarations appertain to empty declaration so we handle
10105 // them here.
10106 if (AttrList)
10107 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010108
Michael Han684aa732013-02-22 17:15:32 +000010109 CurContext->addDecl(ED);
10110 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010111}
10112
Douglas Gregord308e622009-05-18 20:51:54 +000010113/// \brief Perform semantic analysis for the variable declaration that
10114/// occurs within a C++ catch clause, returning the newly-created
10115/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010116VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010117 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010118 SourceLocation StartLoc,
10119 SourceLocation Loc,
10120 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010121 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010122 QualType ExDeclType = TInfo->getType();
10123
Sebastian Redl4b07b292008-12-22 19:15:10 +000010124 // Arrays and functions decay.
10125 if (ExDeclType->isArrayType())
10126 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10127 else if (ExDeclType->isFunctionType())
10128 ExDeclType = Context.getPointerType(ExDeclType);
10129
10130 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10131 // The exception-declaration shall not denote a pointer or reference to an
10132 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010133 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010134 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010135 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010136 Invalid = true;
10137 }
Douglas Gregord308e622009-05-18 20:51:54 +000010138
Sebastian Redl4b07b292008-12-22 19:15:10 +000010139 QualType BaseType = ExDeclType;
10140 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010141 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010142 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010143 BaseType = Ptr->getPointeeType();
10144 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010145 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010146 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010147 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010148 BaseType = Ref->getPointeeType();
10149 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010150 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010151 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010152 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010153 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010154 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010155
Mike Stump1eb44332009-09-09 15:08:12 +000010156 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010157 RequireNonAbstractType(Loc, ExDeclType,
10158 diag::err_abstract_type_in_decl,
10159 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010160 Invalid = true;
10161
John McCall5a180392010-07-24 00:37:23 +000010162 // Only the non-fragile NeXT runtime currently supports C++ catches
10163 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010164 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010165 QualType T = ExDeclType;
10166 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10167 T = RT->getPointeeType();
10168
10169 if (T->isObjCObjectType()) {
10170 Diag(Loc, diag::err_objc_object_catch);
10171 Invalid = true;
10172 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010173 // FIXME: should this be a test for macosx-fragile specifically?
10174 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010175 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010176 }
10177 }
10178
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010179 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10180 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010181 ExDecl->setExceptionVariable(true);
10182
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010183 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010184 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010185 Invalid = true;
10186
Douglas Gregorc41b8782011-07-06 18:14:43 +000010187 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010188 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +000010189 // C++ [except.handle]p16:
10190 // The object declared in an exception-declaration or, if the
10191 // exception-declaration does not specify a name, a temporary (12.2) is
10192 // copy-initialized (8.5) from the exception object. [...]
10193 // The object is destroyed when the handler exits, after the destruction
10194 // of any automatic objects initialized within the handler.
10195 //
10196 // We just pretend to initialize the object with itself, then make sure
10197 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010198 QualType initType = ExDeclType;
10199
10200 InitializedEntity entity =
10201 InitializedEntity::InitializeVariable(ExDecl);
10202 InitializationKind initKind =
10203 InitializationKind::CreateCopy(Loc, SourceLocation());
10204
10205 Expr *opaqueValue =
10206 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10207 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10208 ExprResult result = sequence.Perform(*this, entity, initKind,
10209 MultiExprArg(&opaqueValue, 1));
10210 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010211 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010212 else {
10213 // If the constructor used was non-trivial, set this as the
10214 // "initializer".
10215 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10216 if (!construct->getConstructor()->isTrivial()) {
10217 Expr *init = MaybeCreateExprWithCleanups(construct);
10218 ExDecl->setInit(init);
10219 }
10220
10221 // And make sure it's destructable.
10222 FinalizeVarWithDestructor(ExDecl, recordType);
10223 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010224 }
10225 }
10226
Douglas Gregord308e622009-05-18 20:51:54 +000010227 if (Invalid)
10228 ExDecl->setInvalidDecl();
10229
10230 return ExDecl;
10231}
10232
10233/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10234/// handler.
John McCalld226f652010-08-21 09:40:31 +000010235Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010236 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010237 bool Invalid = D.isInvalidType();
10238
10239 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010240 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10241 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010242 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10243 D.getIdentifierLoc());
10244 Invalid = true;
10245 }
10246
Sebastian Redl4b07b292008-12-22 19:15:10 +000010247 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010248 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010249 LookupOrdinaryName,
10250 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010251 // The scope should be freshly made just for us. There is just no way
10252 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010253 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010254 if (PrevDecl->isTemplateParameter()) {
10255 // Maybe we will complain about the shadowed template parameter.
10256 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010257 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010258 }
10259 }
10260
Chris Lattnereaaebc72009-04-25 08:06:05 +000010261 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010262 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10263 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010264 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010265 }
10266
Douglas Gregor83cb9422010-09-09 17:09:21 +000010267 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010268 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010269 D.getIdentifierLoc(),
10270 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010271 if (Invalid)
10272 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010273
Sebastian Redl4b07b292008-12-22 19:15:10 +000010274 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010275 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010276 PushOnScopeChains(ExDecl, S);
10277 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010278 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010279
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010280 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010281 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010282}
Anders Carlssonfb311762009-03-14 00:25:26 +000010283
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010284Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010285 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010286 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010287 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010288 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010289
Richard Smithe3f470a2012-07-11 22:37:56 +000010290 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10291 return 0;
10292
10293 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10294 AssertMessage, RParenLoc, false);
10295}
10296
10297Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10298 Expr *AssertExpr,
10299 StringLiteral *AssertMessage,
10300 SourceLocation RParenLoc,
10301 bool Failed) {
10302 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10303 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010304 // In a static_assert-declaration, the constant-expression shall be a
10305 // constant expression that can be contextually converted to bool.
10306 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10307 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010308 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010309
Richard Smithdaaefc52011-12-14 23:32:26 +000010310 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010311 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010312 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010313 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010314 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010315
Richard Smithe3f470a2012-07-11 22:37:56 +000010316 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010317 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010318 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010319 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010320 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010321 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010322 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010323 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010324 }
Mike Stump1eb44332009-09-09 15:08:12 +000010325
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010326 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010327 AssertExpr, AssertMessage, RParenLoc,
10328 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010329
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010330 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010331 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010332}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010333
Douglas Gregor1d869352010-04-07 16:53:43 +000010334/// \brief Perform semantic analysis of the given friend type declaration.
10335///
10336/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010337FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010338 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010339 TypeSourceInfo *TSInfo) {
10340 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10341
10342 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010343 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010344
Richard Smith6b130222011-10-18 21:39:00 +000010345 // C++03 [class.friend]p2:
10346 // An elaborated-type-specifier shall be used in a friend declaration
10347 // for a class.*
10348 //
10349 // * The class-key of the elaborated-type-specifier is required.
10350 if (!ActiveTemplateInstantiations.empty()) {
10351 // Do not complain about the form of friend template types during
10352 // template instantiation; we will already have complained when the
10353 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010354 } else {
10355 if (!T->isElaboratedTypeSpecifier()) {
10356 // If we evaluated the type to a record type, suggest putting
10357 // a tag in front.
10358 if (const RecordType *RT = T->getAs<RecordType>()) {
10359 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010360
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010361 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010362
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010363 Diag(TypeRange.getBegin(),
10364 getLangOpts().CPlusPlus11 ?
10365 diag::warn_cxx98_compat_unelaborated_friend_type :
10366 diag::ext_unelaborated_friend_type)
10367 << (unsigned) RD->getTagKind()
10368 << T
10369 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10370 InsertionText);
10371 } else {
10372 Diag(FriendLoc,
10373 getLangOpts().CPlusPlus11 ?
10374 diag::warn_cxx98_compat_nonclass_type_friend :
10375 diag::ext_nonclass_type_friend)
10376 << T
10377 << TypeRange;
10378 }
10379 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010380 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010381 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010382 diag::warn_cxx98_compat_enum_friend :
10383 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010384 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010385 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010386 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010387
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010388 // C++11 [class.friend]p3:
10389 // A friend declaration that does not declare a function shall have one
10390 // of the following forms:
10391 // friend elaborated-type-specifier ;
10392 // friend simple-type-specifier ;
10393 // friend typename-specifier ;
10394 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10395 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10396 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010397
Douglas Gregor06245bf2010-04-07 17:57:12 +000010398 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010399 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010400 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010401 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010402}
10403
John McCall9a34edb2010-10-19 01:40:49 +000010404/// Handle a friend tag declaration where the scope specifier was
10405/// templated.
10406Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10407 unsigned TagSpec, SourceLocation TagLoc,
10408 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010409 IdentifierInfo *Name,
10410 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010411 AttributeList *Attr,
10412 MultiTemplateParamsArg TempParamLists) {
10413 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10414
10415 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010416 bool Invalid = false;
10417
10418 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010419 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010420 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010421 TempParamLists.size(),
10422 /*friend*/ true,
10423 isExplicitSpecialization,
10424 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010425 if (TemplateParams->size() > 0) {
10426 // This is a declaration of a class template.
10427 if (Invalid)
10428 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010429
Eric Christopher4110e132011-07-21 05:34:24 +000010430 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10431 SS, Name, NameLoc, Attr,
10432 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010433 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010434 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010435 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010436 } else {
10437 // The "template<>" header is extraneous.
10438 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10439 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10440 isExplicitSpecialization = true;
10441 }
10442 }
10443
10444 if (Invalid) return 0;
10445
John McCall9a34edb2010-10-19 01:40:49 +000010446 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010447 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010448 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010449 isAllExplicitSpecializations = false;
10450 break;
10451 }
10452 }
10453
10454 // FIXME: don't ignore attributes.
10455
10456 // If it's explicit specializations all the way down, just forget
10457 // about the template header and build an appropriate non-templated
10458 // friend. TODO: for source fidelity, remember the headers.
10459 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010460 if (SS.isEmpty()) {
10461 bool Owned = false;
10462 bool IsDependent = false;
10463 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10464 Attr, AS_public,
10465 /*ModulePrivateLoc=*/SourceLocation(),
10466 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010467 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010468 /*ScopedEnumUsesClassTag=*/false,
10469 /*UnderlyingType=*/TypeResult());
10470 }
10471
Douglas Gregor2494dd02011-03-01 01:34:45 +000010472 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010473 ElaboratedTypeKeyword Keyword
10474 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010475 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010476 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010477 if (T.isNull())
10478 return 0;
10479
10480 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10481 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010482 DependentNameTypeLoc TL =
10483 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010484 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010485 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010486 TL.setNameLoc(NameLoc);
10487 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010488 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010489 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010490 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010491 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010492 }
10493
10494 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010495 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010496 Friend->setAccess(AS_public);
10497 CurContext->addDecl(Friend);
10498 return Friend;
10499 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010500
10501 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10502
10503
John McCall9a34edb2010-10-19 01:40:49 +000010504
10505 // Handle the case of a templated-scope friend class. e.g.
10506 // template <class T> class A<T>::B;
10507 // FIXME: we don't support these right now.
10508 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10509 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10510 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000010511 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010512 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010513 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010514 TL.setNameLoc(NameLoc);
10515
10516 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010517 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010518 Friend->setAccess(AS_public);
10519 Friend->setUnsupportedFriend(true);
10520 CurContext->addDecl(Friend);
10521 return Friend;
10522}
10523
10524
John McCalldd4a3b02009-09-16 22:47:08 +000010525/// Handle a friend type declaration. This works in tandem with
10526/// ActOnTag.
10527///
10528/// Notes on friend class templates:
10529///
10530/// We generally treat friend class declarations as if they were
10531/// declaring a class. So, for example, the elaborated type specifier
10532/// in a friend declaration is required to obey the restrictions of a
10533/// class-head (i.e. no typedefs in the scope chain), template
10534/// parameters are required to match up with simple template-ids, &c.
10535/// However, unlike when declaring a template specialization, it's
10536/// okay to refer to a template specialization without an empty
10537/// template parameter declaration, e.g.
10538/// friend class A<T>::B<unsigned>;
10539/// We permit this as a special case; if there are any template
10540/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010541/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010542Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010543 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010544 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010545
10546 assert(DS.isFriendSpecified());
10547 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10548
John McCalldd4a3b02009-09-16 22:47:08 +000010549 // Try to convert the decl specifier to a type. This works for
10550 // friend templates because ActOnTag never produces a ClassTemplateDecl
10551 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010552 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010553 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10554 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010555 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010556 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010557
Douglas Gregor6ccab972010-12-16 01:14:37 +000010558 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10559 return 0;
10560
John McCalldd4a3b02009-09-16 22:47:08 +000010561 // This is definitely an error in C++98. It's probably meant to
10562 // be forbidden in C++0x, too, but the specification is just
10563 // poorly written.
10564 //
10565 // The problem is with declarations like the following:
10566 // template <T> friend A<T>::foo;
10567 // where deciding whether a class C is a friend or not now hinges
10568 // on whether there exists an instantiation of A that causes
10569 // 'foo' to equal C. There are restrictions on class-heads
10570 // (which we declare (by fiat) elaborated friend declarations to
10571 // be) that makes this tractable.
10572 //
10573 // FIXME: handle "template <> friend class A<T>;", which
10574 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010575 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010576 Diag(Loc, diag::err_tagless_friend_type_template)
10577 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010578 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010579 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010580
John McCall02cace72009-08-28 07:59:38 +000010581 // C++98 [class.friend]p1: A friend of a class is a function
10582 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010583 // This is fixed in DR77, which just barely didn't make the C++03
10584 // deadline. It's also a very silly restriction that seriously
10585 // affects inner classes and which nobody else seems to implement;
10586 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010587 //
10588 // But note that we could warn about it: it's always useless to
10589 // friend one of your own members (it's not, however, worthless to
10590 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010591
John McCalldd4a3b02009-09-16 22:47:08 +000010592 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010593 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010594 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010595 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010596 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010597 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010598 DS.getFriendSpecLoc());
10599 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010600 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010601
10602 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010603 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010604
John McCalldd4a3b02009-09-16 22:47:08 +000010605 D->setAccess(AS_public);
10606 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010607
John McCalld226f652010-08-21 09:40:31 +000010608 return D;
John McCall02cace72009-08-28 07:59:38 +000010609}
10610
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000010611NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10612 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010613 const DeclSpec &DS = D.getDeclSpec();
10614
10615 assert(DS.isFriendSpecified());
10616 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10617
10618 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010619 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010620
10621 // C++ [class.friend]p1
10622 // A friend of a class is a function or class....
10623 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010624 // It *doesn't* see through dependent types, which is correct
10625 // according to [temp.arg.type]p3:
10626 // If a declaration acquires a function type through a
10627 // type dependent on a template-parameter and this causes
10628 // a declaration that does not use the syntactic form of a
10629 // function declarator to have a function type, the program
10630 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010631 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010632 Diag(Loc, diag::err_unexpected_friend);
10633
10634 // It might be worthwhile to try to recover by creating an
10635 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010636 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010637 }
10638
10639 // C++ [namespace.memdef]p3
10640 // - If a friend declaration in a non-local class first declares a
10641 // class or function, the friend class or function is a member
10642 // of the innermost enclosing namespace.
10643 // - The name of the friend is not found by simple name lookup
10644 // until a matching declaration is provided in that namespace
10645 // scope (either before or after the class declaration granting
10646 // friendship).
10647 // - If a friend function is called, its name may be found by the
10648 // name lookup that considers functions from namespaces and
10649 // classes associated with the types of the function arguments.
10650 // - When looking for a prior declaration of a class or a function
10651 // declared as a friend, scopes outside the innermost enclosing
10652 // namespace scope are not considered.
10653
John McCall337ec3d2010-10-12 23:13:28 +000010654 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010655 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10656 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010657 assert(Name);
10658
Douglas Gregor6ccab972010-12-16 01:14:37 +000010659 // Check for unexpanded parameter packs.
10660 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10661 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10662 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10663 return 0;
10664
John McCall67d1a672009-08-06 02:15:43 +000010665 // The context we found the declaration in, or in which we should
10666 // create the declaration.
10667 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010668 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010669 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010670 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010671
John McCall337ec3d2010-10-12 23:13:28 +000010672 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010673
John McCall337ec3d2010-10-12 23:13:28 +000010674 // There are four cases here.
10675 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010676 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010677 // there as appropriate.
10678 // Recover from invalid scope qualifiers as if they just weren't there.
10679 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010680 // C++0x [namespace.memdef]p3:
10681 // If the name in a friend declaration is neither qualified nor
10682 // a template-id and the declaration is a function or an
10683 // elaborated-type-specifier, the lookup to determine whether
10684 // the entity has been previously declared shall not consider
10685 // any scopes outside the innermost enclosing namespace.
10686 // C++0x [class.friend]p11:
10687 // If a friend declaration appears in a local class and the name
10688 // specified is an unqualified name, a prior declaration is
10689 // looked up without considering scopes that are outside the
10690 // innermost enclosing non-class scope. For a friend function
10691 // declaration, if there is no prior declaration, the program is
10692 // ill-formed.
10693 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010694 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010695
John McCall29ae6e52010-10-13 05:45:15 +000010696 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010697 DC = CurContext;
10698 while (true) {
10699 // Skip class contexts. If someone can cite chapter and verse
10700 // for this behavior, that would be nice --- it's what GCC and
10701 // EDG do, and it seems like a reasonable intent, but the spec
10702 // really only says that checks for unqualified existing
10703 // declarations should stop at the nearest enclosing namespace,
10704 // not that they should only consider the nearest enclosing
10705 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010706 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010707 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010708
John McCall68263142009-11-18 22:49:29 +000010709 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010710
10711 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010712 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010713 break;
John McCall29ae6e52010-10-13 05:45:15 +000010714
John McCall8a407372010-10-14 22:22:28 +000010715 if (isTemplateId) {
10716 if (isa<TranslationUnitDecl>(DC)) break;
10717 } else {
10718 if (DC->isFileContext()) break;
10719 }
John McCall67d1a672009-08-06 02:15:43 +000010720 DC = DC->getParent();
10721 }
10722
10723 // C++ [class.friend]p1: A friend of a class is a function or
10724 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010725 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010726 // Most C++ 98 compilers do seem to give an error here, so
10727 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010728 if (!Previous.empty() && DC->Equals(CurContext))
10729 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010730 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010731 diag::warn_cxx98_compat_friend_is_member :
10732 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010733
John McCall380aaa42010-10-13 06:22:15 +000010734 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010735
Douglas Gregor883af832011-10-10 01:11:59 +000010736 // C++ [class.friend]p6:
10737 // A function can be defined in a friend declaration of a class if and
10738 // only if the class is a non-local class (9.8), the function name is
10739 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010740 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010741 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10742 }
10743
John McCall337ec3d2010-10-12 23:13:28 +000010744 // - There's a non-dependent scope specifier, in which case we
10745 // compute it and do a previous lookup there for a function
10746 // or function template.
10747 } else if (!SS.getScopeRep()->isDependent()) {
10748 DC = computeDeclContext(SS);
10749 if (!DC) return 0;
10750
10751 if (RequireCompleteDeclContext(SS, DC)) return 0;
10752
10753 LookupQualifiedName(Previous, DC);
10754
10755 // Ignore things found implicitly in the wrong scope.
10756 // TODO: better diagnostics for this case. Suggesting the right
10757 // qualified scope would be nice...
10758 LookupResult::Filter F = Previous.makeFilter();
10759 while (F.hasNext()) {
10760 NamedDecl *D = F.next();
10761 if (!DC->InEnclosingNamespaceSetOf(
10762 D->getDeclContext()->getRedeclContext()))
10763 F.erase();
10764 }
10765 F.done();
10766
10767 if (Previous.empty()) {
10768 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010769 Diag(Loc, diag::err_qualified_friend_not_found)
10770 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010771 return 0;
10772 }
10773
10774 // C++ [class.friend]p1: A friend of a class is a function or
10775 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010776 if (DC->Equals(CurContext))
10777 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010778 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010779 diag::warn_cxx98_compat_friend_is_member :
10780 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010781
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010782 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010783 // C++ [class.friend]p6:
10784 // A function can be defined in a friend declaration of a class if and
10785 // only if the class is a non-local class (9.8), the function name is
10786 // unqualified, and the function has namespace scope.
10787 SemaDiagnosticBuilder DB
10788 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10789
10790 DB << SS.getScopeRep();
10791 if (DC->isFileContext())
10792 DB << FixItHint::CreateRemoval(SS.getRange());
10793 SS.clear();
10794 }
John McCall337ec3d2010-10-12 23:13:28 +000010795
10796 // - There's a scope specifier that does not match any template
10797 // parameter lists, in which case we use some arbitrary context,
10798 // create a method or method template, and wait for instantiation.
10799 // - There's a scope specifier that does match some template
10800 // parameter lists, which we don't handle right now.
10801 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010802 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010803 // C++ [class.friend]p6:
10804 // A function can be defined in a friend declaration of a class if and
10805 // only if the class is a non-local class (9.8), the function name is
10806 // unqualified, and the function has namespace scope.
10807 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10808 << SS.getScopeRep();
10809 }
10810
John McCall337ec3d2010-10-12 23:13:28 +000010811 DC = CurContext;
10812 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010813 }
Douglas Gregor883af832011-10-10 01:11:59 +000010814
John McCall29ae6e52010-10-13 05:45:15 +000010815 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010816 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010817 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10818 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10819 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010820 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010821 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10822 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010823 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010824 }
John McCall67d1a672009-08-06 02:15:43 +000010825 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010826
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010827 // FIXME: This is an egregious hack to cope with cases where the scope stack
10828 // does not contain the declaration context, i.e., in an out-of-line
10829 // definition of a class.
10830 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10831 if (!DCScope) {
10832 FakeDCScope.setEntity(DC);
10833 DCScope = &FakeDCScope;
10834 }
10835
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010836 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010837 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010838 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010839 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010840
Douglas Gregor182ddf02009-09-28 00:08:27 +000010841 assert(ND->getDeclContext() == DC);
10842 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010843
John McCallab88d972009-08-31 22:39:49 +000010844 // Add the function declaration to the appropriate lookup tables,
10845 // adjusting the redeclarations list as necessary. We don't
10846 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010847 //
John McCallab88d972009-08-31 22:39:49 +000010848 // Also update the scope-based lookup if the target context's
10849 // lookup context is in lexical scope.
10850 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010851 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010852 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010853 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010854 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010855 }
John McCall02cace72009-08-28 07:59:38 +000010856
10857 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010858 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010859 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010860 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010861 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010862
John McCall1f2e1a92012-08-10 03:15:35 +000010863 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010864 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010865 } else {
10866 if (DC->isRecord()) CheckFriendAccess(ND);
10867
John McCall6102ca12010-10-16 06:59:13 +000010868 FunctionDecl *FD;
10869 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10870 FD = FTD->getTemplatedDecl();
10871 else
10872 FD = cast<FunctionDecl>(ND);
10873
10874 // Mark templated-scope function declarations as unsupported.
10875 if (FD->getNumTemplateParameterLists())
10876 FrD->setUnsupportedFriend(true);
10877 }
John McCall337ec3d2010-10-12 23:13:28 +000010878
John McCalld226f652010-08-21 09:40:31 +000010879 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010880}
10881
John McCalld226f652010-08-21 09:40:31 +000010882void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10883 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010884
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000010885 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000010886 if (!Fn) {
10887 Diag(DelLoc, diag::err_deleted_non_function);
10888 return;
10889 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010890 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010891 // Don't consider the implicit declaration we generate for explicit
10892 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010893 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10894 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010895 Diag(DelLoc, diag::err_deleted_decl_not_first);
10896 Diag(Prev->getLocation(), diag::note_previous_declaration);
10897 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010898 // If the declaration wasn't the first, we delete the function anyway for
10899 // recovery.
10900 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010901 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010902}
Sebastian Redl13e88542009-04-27 21:33:24 +000010903
Sean Hunte4246a62011-05-12 06:15:49 +000010904void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000010905 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000010906
10907 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010908 if (MD->getParent()->isDependentType()) {
10909 MD->setDefaulted();
10910 MD->setExplicitlyDefaulted();
10911 return;
10912 }
10913
Sean Hunte4246a62011-05-12 06:15:49 +000010914 CXXSpecialMember Member = getSpecialMember(MD);
10915 if (Member == CXXInvalid) {
10916 Diag(DefaultLoc, diag::err_default_special_members);
10917 return;
10918 }
10919
10920 MD->setDefaulted();
10921 MD->setExplicitlyDefaulted();
10922
Sean Huntcd10dec2011-05-23 23:14:04 +000010923 // If this definition appears within the record, do the checking when
10924 // the record is complete.
10925 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000010926 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000010927 // Find the uninstantiated declaration that actually had the '= default'
10928 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000010929 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000010930
10931 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010932 return;
10933
Richard Smithb9d0b762012-07-27 04:22:15 +000010934 CheckExplicitlyDefaultedSpecialMember(MD);
10935
Richard Smith1d28caf2012-12-11 01:14:52 +000010936 // The exception specification is needed because we are defining the
10937 // function.
10938 ResolveExceptionSpec(DefaultLoc,
10939 MD->getType()->castAs<FunctionProtoType>());
10940
Sean Hunte4246a62011-05-12 06:15:49 +000010941 switch (Member) {
10942 case CXXDefaultConstructor: {
10943 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010944 if (!CD->isInvalidDecl())
10945 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10946 break;
10947 }
10948
10949 case CXXCopyConstructor: {
10950 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010951 if (!CD->isInvalidDecl())
10952 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010953 break;
10954 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010955
Sean Hunt2b188082011-05-14 05:23:28 +000010956 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010957 if (!MD->isInvalidDecl())
10958 DefineImplicitCopyAssignment(DefaultLoc, MD);
10959 break;
10960 }
10961
Sean Huntcb45a0f2011-05-12 22:46:25 +000010962 case CXXDestructor: {
10963 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010964 if (!DD->isInvalidDecl())
10965 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010966 break;
10967 }
10968
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010969 case CXXMoveConstructor: {
10970 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010971 if (!CD->isInvalidDecl())
10972 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010973 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010974 }
Sean Hunt82713172011-05-25 23:16:36 +000010975
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010976 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010977 if (!MD->isInvalidDecl())
10978 DefineImplicitMoveAssignment(DefaultLoc, MD);
10979 break;
10980 }
10981
10982 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010983 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010984 }
10985 } else {
10986 Diag(DefaultLoc, diag::err_default_special_members);
10987 }
10988}
10989
Sebastian Redl13e88542009-04-27 21:33:24 +000010990static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010991 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010992 Stmt *SubStmt = *CI;
10993 if (!SubStmt)
10994 continue;
10995 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010996 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010997 diag::err_return_in_constructor_handler);
10998 if (!isa<Expr>(SubStmt))
10999 SearchForReturnInStmt(Self, SubStmt);
11000 }
11001}
11002
11003void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11004 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11005 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11006 SearchForReturnInStmt(*this, Handler);
11007 }
11008}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011009
David Blaikie299adab2013-01-18 23:03:15 +000011010bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011011 const CXXMethodDecl *Old) {
11012 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11013 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11014
11015 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11016
11017 // If the calling conventions match, everything is fine
11018 if (NewCC == OldCC)
11019 return false;
11020
11021 // If either of the calling conventions are set to "default", we need to pick
11022 // something more sensible based on the target. This supports code where the
11023 // one method explicitly sets thiscall, and another has no explicit calling
11024 // convention.
11025 CallingConv Default =
11026 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11027 if (NewCC == CC_Default)
11028 NewCC = Default;
11029 if (OldCC == CC_Default)
11030 OldCC = Default;
11031
11032 // If the calling conventions still don't match, then report the error
11033 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011034 Diag(New->getLocation(),
11035 diag::err_conflicting_overriding_cc_attributes)
11036 << New->getDeclName() << New->getType() << Old->getType();
11037 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11038 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011039 }
11040
11041 return false;
11042}
11043
Mike Stump1eb44332009-09-09 15:08:12 +000011044bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011045 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011046 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11047 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011048
Chandler Carruth73857792010-02-15 11:53:20 +000011049 if (Context.hasSameType(NewTy, OldTy) ||
11050 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011051 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011052
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011053 // Check if the return types are covariant
11054 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011055
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011056 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011057 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11058 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011059 NewClassTy = NewPT->getPointeeType();
11060 OldClassTy = OldPT->getPointeeType();
11061 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011062 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11063 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11064 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11065 NewClassTy = NewRT->getPointeeType();
11066 OldClassTy = OldRT->getPointeeType();
11067 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011068 }
11069 }
Mike Stump1eb44332009-09-09 15:08:12 +000011070
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011071 // The return types aren't either both pointers or references to a class type.
11072 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011073 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011074 diag::err_different_return_type_for_overriding_virtual_function)
11075 << New->getDeclName() << NewTy << OldTy;
11076 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011077
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011078 return true;
11079 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011080
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011081 // C++ [class.virtual]p6:
11082 // If the return type of D::f differs from the return type of B::f, the
11083 // class type in the return type of D::f shall be complete at the point of
11084 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011085 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11086 if (!RT->isBeingDefined() &&
11087 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011088 diag::err_covariant_return_incomplete,
11089 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011090 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011091 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011092
Douglas Gregora4923eb2009-11-16 21:35:15 +000011093 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011094 // Check if the new class derives from the old class.
11095 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11096 Diag(New->getLocation(),
11097 diag::err_covariant_return_not_derived)
11098 << New->getDeclName() << NewTy << OldTy;
11099 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11100 return true;
11101 }
Mike Stump1eb44332009-09-09 15:08:12 +000011102
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011103 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011104 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011105 diag::err_covariant_return_inaccessible_base,
11106 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11107 // FIXME: Should this point to the return type?
11108 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011109 // FIXME: this note won't trigger for delayed access control
11110 // diagnostics, and it's impossible to get an undelayed error
11111 // here from access control during the original parse because
11112 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011113 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11114 return true;
11115 }
11116 }
Mike Stump1eb44332009-09-09 15:08:12 +000011117
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011118 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011119 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011120 Diag(New->getLocation(),
11121 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011122 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011123 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11124 return true;
11125 };
Mike Stump1eb44332009-09-09 15:08:12 +000011126
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011127
11128 // The new class type must have the same or less qualifiers as the old type.
11129 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11130 Diag(New->getLocation(),
11131 diag::err_covariant_return_type_class_type_more_qualified)
11132 << New->getDeclName() << NewTy << OldTy;
11133 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11134 return true;
11135 };
Mike Stump1eb44332009-09-09 15:08:12 +000011136
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011137 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011138}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011139
Douglas Gregor4ba31362009-12-01 17:24:26 +000011140/// \brief Mark the given method pure.
11141///
11142/// \param Method the method to be marked pure.
11143///
11144/// \param InitRange the source range that covers the "0" initializer.
11145bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011146 SourceLocation EndLoc = InitRange.getEnd();
11147 if (EndLoc.isValid())
11148 Method->setRangeEnd(EndLoc);
11149
Douglas Gregor4ba31362009-12-01 17:24:26 +000011150 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11151 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011152 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011153 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011154
11155 if (!Method->isInvalidDecl())
11156 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11157 << Method->getDeclName() << InitRange;
11158 return true;
11159}
11160
Douglas Gregor552e2992012-02-21 02:22:07 +000011161/// \brief Determine whether the given declaration is a static data member.
11162static bool isStaticDataMember(Decl *D) {
11163 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11164 if (!Var)
11165 return false;
11166
11167 return Var->isStaticDataMember();
11168}
John McCall731ad842009-12-19 09:28:58 +000011169/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11170/// an initializer for the out-of-line declaration 'Dcl'. The scope
11171/// is a fresh scope pushed for just this purpose.
11172///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011173/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11174/// static data member of class X, names should be looked up in the scope of
11175/// class X.
John McCalld226f652010-08-21 09:40:31 +000011176void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011177 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011178 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011179
John McCall731ad842009-12-19 09:28:58 +000011180 // We should only get called for declarations with scope specifiers, like:
11181 // int foo::bar;
11182 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011183 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011184
11185 // If we are parsing the initializer for a static data member, push a
11186 // new expression evaluation context that is associated with this static
11187 // data member.
11188 if (isStaticDataMember(D))
11189 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011190}
11191
11192/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011193/// initializer for the out-of-line declaration 'D'.
11194void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011195 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011196 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011197
Douglas Gregor552e2992012-02-21 02:22:07 +000011198 if (isStaticDataMember(D))
11199 PopExpressionEvaluationContext();
11200
John McCall731ad842009-12-19 09:28:58 +000011201 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011202 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011203}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011204
11205/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11206/// C++ if/switch/while/for statement.
11207/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011208DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011209 // C++ 6.4p2:
11210 // The declarator shall not specify a function or an array.
11211 // The type-specifier-seq shall not contain typedef and shall not declare a
11212 // new class or enumeration.
11213 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11214 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011215
11216 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011217 if (!Dcl)
11218 return true;
11219
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011220 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11221 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011222 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011223 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011224 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011225
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011226 return Dcl;
11227}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011228
Douglas Gregordfe65432011-07-28 19:11:31 +000011229void Sema::LoadExternalVTableUses() {
11230 if (!ExternalSource)
11231 return;
11232
11233 SmallVector<ExternalVTableUse, 4> VTables;
11234 ExternalSource->ReadUsedVTables(VTables);
11235 SmallVector<VTableUse, 4> NewUses;
11236 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11237 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11238 = VTablesUsed.find(VTables[I].Record);
11239 // Even if a definition wasn't required before, it may be required now.
11240 if (Pos != VTablesUsed.end()) {
11241 if (!Pos->second && VTables[I].DefinitionRequired)
11242 Pos->second = true;
11243 continue;
11244 }
11245
11246 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11247 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11248 }
11249
11250 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11251}
11252
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011253void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11254 bool DefinitionRequired) {
11255 // Ignore any vtable uses in unevaluated operands or for classes that do
11256 // not have a vtable.
11257 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11258 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011259 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011260 return;
11261
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011262 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011263 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011264 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11265 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11266 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11267 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011268 // If we already had an entry, check to see if we are promoting this vtable
11269 // to required a definition. If so, we need to reappend to the VTableUses
11270 // list, since we may have already processed the first entry.
11271 if (DefinitionRequired && !Pos.first->second) {
11272 Pos.first->second = true;
11273 } else {
11274 // Otherwise, we can early exit.
11275 return;
11276 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011277 }
11278
11279 // Local classes need to have their virtual members marked
11280 // immediately. For all other classes, we mark their virtual members
11281 // at the end of the translation unit.
11282 if (Class->isLocalClass())
11283 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011284 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011285 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011286}
11287
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011288bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011289 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011290 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011291 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011292
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011293 // Note: The VTableUses vector could grow as a result of marking
11294 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011295 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011296 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011297 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011298 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011299 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011300 if (!Class)
11301 continue;
11302
11303 SourceLocation Loc = VTableUses[I].second;
11304
Richard Smithb9d0b762012-07-27 04:22:15 +000011305 bool DefineVTable = true;
11306
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011307 // If this class has a key function, but that key function is
11308 // defined in another translation unit, we don't need to emit the
11309 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011310 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011311 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011312 switch (KeyFunction->getTemplateSpecializationKind()) {
11313 case TSK_Undeclared:
11314 case TSK_ExplicitSpecialization:
11315 case TSK_ExplicitInstantiationDeclaration:
11316 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011317 DefineVTable = false;
11318 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011319
11320 case TSK_ExplicitInstantiationDefinition:
11321 case TSK_ImplicitInstantiation:
11322 // We will be instantiating the key function.
11323 break;
11324 }
11325 } else if (!KeyFunction) {
11326 // If we have a class with no key function that is the subject
11327 // of an explicit instantiation declaration, suppress the
11328 // vtable; it will live with the explicit instantiation
11329 // definition.
11330 bool IsExplicitInstantiationDeclaration
11331 = Class->getTemplateSpecializationKind()
11332 == TSK_ExplicitInstantiationDeclaration;
11333 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11334 REnd = Class->redecls_end();
11335 R != REnd; ++R) {
11336 TemplateSpecializationKind TSK
11337 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11338 if (TSK == TSK_ExplicitInstantiationDeclaration)
11339 IsExplicitInstantiationDeclaration = true;
11340 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11341 IsExplicitInstantiationDeclaration = false;
11342 break;
11343 }
11344 }
11345
11346 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011347 DefineVTable = false;
11348 }
11349
11350 // The exception specifications for all virtual members may be needed even
11351 // if we are not providing an authoritative form of the vtable in this TU.
11352 // We may choose to emit it available_externally anyway.
11353 if (!DefineVTable) {
11354 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11355 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011356 }
11357
11358 // Mark all of the virtual members of this class as referenced, so
11359 // that we can build a vtable. Then, tell the AST consumer that a
11360 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011361 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011362 MarkVirtualMembersReferenced(Loc, Class);
11363 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11364 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11365
11366 // Optionally warn if we're emitting a weak vtable.
11367 if (Class->getLinkage() == ExternalLinkage &&
11368 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011369 const FunctionDecl *KeyFunctionDef = 0;
11370 if (!KeyFunction ||
11371 (KeyFunction->hasBody(KeyFunctionDef) &&
11372 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011373 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11374 TSK_ExplicitInstantiationDefinition
11375 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11376 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011377 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011378 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011379 VTableUses.clear();
11380
Douglas Gregor78844032011-04-22 22:25:37 +000011381 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011382}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011383
Richard Smithb9d0b762012-07-27 04:22:15 +000011384void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11385 const CXXRecordDecl *RD) {
11386 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11387 E = RD->method_end(); I != E; ++I)
11388 if ((*I)->isVirtual() && !(*I)->isPure())
11389 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11390}
11391
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011392void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11393 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011394 // Mark all functions which will appear in RD's vtable as used.
11395 CXXFinalOverriderMap FinalOverriders;
11396 RD->getFinalOverriders(FinalOverriders);
11397 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11398 E = FinalOverriders.end();
11399 I != E; ++I) {
11400 for (OverridingMethods::const_iterator OI = I->second.begin(),
11401 OE = I->second.end();
11402 OI != OE; ++OI) {
11403 assert(OI->second.size() > 0 && "no final overrider");
11404 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011405
Richard Smithff817f72012-07-07 06:59:51 +000011406 // C++ [basic.def.odr]p2:
11407 // [...] A virtual member function is used if it is not pure. [...]
11408 if (!Overrider->isPure())
11409 MarkFunctionReferenced(Loc, Overrider);
11410 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011411 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011412
11413 // Only classes that have virtual bases need a VTT.
11414 if (RD->getNumVBases() == 0)
11415 return;
11416
11417 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11418 e = RD->bases_end(); i != e; ++i) {
11419 const CXXRecordDecl *Base =
11420 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011421 if (Base->getNumVBases() == 0)
11422 continue;
11423 MarkVirtualMembersReferenced(Loc, Base);
11424 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011425}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011426
11427/// SetIvarInitializers - This routine builds initialization ASTs for the
11428/// Objective-C implementation whose ivars need be initialized.
11429void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011430 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011431 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011432 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011433 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011434 CollectIvarsToConstructOrDestruct(OID, ivars);
11435 if (ivars.empty())
11436 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011437 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011438 for (unsigned i = 0; i < ivars.size(); i++) {
11439 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011440 if (Field->isInvalidDecl())
11441 continue;
11442
Sean Huntcbb67482011-01-08 20:30:50 +000011443 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011444 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11445 InitializationKind InitKind =
11446 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11447
11448 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011449 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011450 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011451 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011452 // Note, MemberInit could actually come back empty if no initialization
11453 // is required (e.g., because it would call a trivial default constructor)
11454 if (!MemberInit.get() || MemberInit.isInvalid())
11455 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011456
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011457 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011458 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11459 SourceLocation(),
11460 MemberInit.takeAs<Expr>(),
11461 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011462 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011463
11464 // Be sure that the destructor is accessible and is marked as referenced.
11465 if (const RecordType *RecordTy
11466 = Context.getBaseElementType(Field->getType())
11467 ->getAs<RecordType>()) {
11468 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011469 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011470 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011471 CheckDestructorAccess(Field->getLocation(), Destructor,
11472 PDiag(diag::err_access_dtor_ivar)
11473 << Context.getBaseElementType(Field->getType()));
11474 }
11475 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011476 }
11477 ObjCImplementation->setIvarInitializers(Context,
11478 AllToInit.data(), AllToInit.size());
11479 }
11480}
Sean Huntfe57eef2011-05-04 05:57:24 +000011481
Sean Huntebcbe1d2011-05-04 23:29:54 +000011482static
11483void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11484 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11485 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11486 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11487 Sema &S) {
11488 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11489 CE = Current.end();
11490 if (Ctor->isInvalidDecl())
11491 return;
11492
Richard Smitha8eaf002012-08-23 06:16:52 +000011493 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11494
11495 // Target may not be determinable yet, for instance if this is a dependent
11496 // call in an uninstantiated template.
11497 if (Target) {
11498 const FunctionDecl *FNTarget = 0;
11499 (void)Target->hasBody(FNTarget);
11500 Target = const_cast<CXXConstructorDecl*>(
11501 cast_or_null<CXXConstructorDecl>(FNTarget));
11502 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011503
11504 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11505 // Avoid dereferencing a null pointer here.
11506 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11507
11508 if (!Current.insert(Canonical))
11509 return;
11510
11511 // We know that beyond here, we aren't chaining into a cycle.
11512 if (!Target || !Target->isDelegatingConstructor() ||
11513 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11514 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11515 Valid.insert(*CI);
11516 Current.clear();
11517 // We've hit a cycle.
11518 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11519 Current.count(TCanonical)) {
11520 // If we haven't diagnosed this cycle yet, do so now.
11521 if (!Invalid.count(TCanonical)) {
11522 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011523 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011524 << Ctor;
11525
Richard Smitha8eaf002012-08-23 06:16:52 +000011526 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011527 if (TCanonical != Canonical)
11528 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11529
11530 CXXConstructorDecl *C = Target;
11531 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011532 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011533 (void)C->getTargetConstructor()->hasBody(FNTarget);
11534 assert(FNTarget && "Ctor cycle through bodiless function");
11535
Richard Smitha8eaf002012-08-23 06:16:52 +000011536 C = const_cast<CXXConstructorDecl*>(
11537 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011538 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11539 }
11540 }
11541
11542 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11543 Invalid.insert(*CI);
11544 Current.clear();
11545 } else {
11546 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11547 }
11548}
11549
11550
Sean Huntfe57eef2011-05-04 05:57:24 +000011551void Sema::CheckDelegatingCtorCycles() {
11552 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11553
Sean Huntebcbe1d2011-05-04 23:29:54 +000011554 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11555 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011556
Douglas Gregor0129b562011-07-27 21:57:17 +000011557 for (DelegatingCtorDeclsType::iterator
11558 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011559 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011560 I != E; ++I)
11561 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011562
11563 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11564 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011565}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011566
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011567namespace {
11568 /// \brief AST visitor that finds references to the 'this' expression.
11569 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11570 Sema &S;
11571
11572 public:
11573 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11574
11575 bool VisitCXXThisExpr(CXXThisExpr *E) {
11576 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11577 << E->isImplicit();
11578 return false;
11579 }
11580 };
11581}
11582
11583bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11584 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11585 if (!TSInfo)
11586 return false;
11587
11588 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011589 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011590 if (!ProtoTL)
11591 return false;
11592
11593 // C++11 [expr.prim.general]p3:
11594 // [The expression this] shall not appear before the optional
11595 // cv-qualifier-seq and it shall not appear within the declaration of a
11596 // static member function (although its type and value category are defined
11597 // within a static member function as they are within a non-static member
11598 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011599 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000011600 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011601 FindCXXThisExpr Finder(*this);
11602
11603 // If the return type came after the cv-qualifier-seq, check it now.
11604 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000011605 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011606 return true;
11607
11608 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011609 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11610 return true;
11611
11612 return checkThisInStaticMemberFunctionAttributes(Method);
11613}
11614
11615bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11616 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11617 if (!TSInfo)
11618 return false;
11619
11620 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011621 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011622 if (!ProtoTL)
11623 return false;
11624
David Blaikie39e6ab42013-02-18 22:06:02 +000011625 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011626 FindCXXThisExpr Finder(*this);
11627
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011628 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011629 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011630 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011631 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011632 case EST_DynamicNone:
11633 case EST_MSAny:
11634 case EST_None:
11635 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011636
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011637 case EST_ComputedNoexcept:
11638 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11639 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011640
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011641 case EST_Dynamic:
11642 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011643 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011644 E != EEnd; ++E) {
11645 if (!Finder.TraverseType(*E))
11646 return true;
11647 }
11648 break;
11649 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011650
11651 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011652}
11653
11654bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11655 FindCXXThisExpr Finder(*this);
11656
11657 // Check attributes.
11658 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11659 A != AEnd; ++A) {
11660 // FIXME: This should be emitted by tblgen.
11661 Expr *Arg = 0;
11662 ArrayRef<Expr *> Args;
11663 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11664 Arg = G->getArg();
11665 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11666 Arg = G->getArg();
11667 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11668 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11669 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11670 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11671 else if (ExclusiveLockFunctionAttr *ELF
11672 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11673 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11674 else if (SharedLockFunctionAttr *SLF
11675 = dyn_cast<SharedLockFunctionAttr>(*A))
11676 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11677 else if (ExclusiveTrylockFunctionAttr *ETLF
11678 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11679 Arg = ETLF->getSuccessValue();
11680 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11681 } else if (SharedTrylockFunctionAttr *STLF
11682 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11683 Arg = STLF->getSuccessValue();
11684 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11685 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11686 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11687 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11688 Arg = LR->getArg();
11689 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11690 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11691 else if (ExclusiveLocksRequiredAttr *ELR
11692 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11693 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11694 else if (SharedLocksRequiredAttr *SLR
11695 = dyn_cast<SharedLocksRequiredAttr>(*A))
11696 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11697
11698 if (Arg && !Finder.TraverseStmt(Arg))
11699 return true;
11700
11701 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11702 if (!Finder.TraverseStmt(Args[I]))
11703 return true;
11704 }
11705 }
11706
11707 return false;
11708}
11709
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011710void
11711Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11712 ArrayRef<ParsedType> DynamicExceptions,
11713 ArrayRef<SourceRange> DynamicExceptionRanges,
11714 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011715 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011716 FunctionProtoType::ExtProtoInfo &EPI) {
11717 Exceptions.clear();
11718 EPI.ExceptionSpecType = EST;
11719 if (EST == EST_Dynamic) {
11720 Exceptions.reserve(DynamicExceptions.size());
11721 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11722 // FIXME: Preserve type source info.
11723 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11724
11725 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11726 collectUnexpandedParameterPacks(ET, Unexpanded);
11727 if (!Unexpanded.empty()) {
11728 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11729 UPPC_ExceptionType,
11730 Unexpanded);
11731 continue;
11732 }
11733
11734 // Check that the type is valid for an exception spec, and
11735 // drop it if not.
11736 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11737 Exceptions.push_back(ET);
11738 }
11739 EPI.NumExceptions = Exceptions.size();
11740 EPI.Exceptions = Exceptions.data();
11741 return;
11742 }
11743
11744 if (EST == EST_ComputedNoexcept) {
11745 // If an error occurred, there's no expression here.
11746 if (NoexceptExpr) {
11747 assert((NoexceptExpr->isTypeDependent() ||
11748 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11749 Context.BoolTy) &&
11750 "Parser should have made sure that the expression is boolean");
11751 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11752 EPI.ExceptionSpecType = EST_BasicNoexcept;
11753 return;
11754 }
11755
11756 if (!NoexceptExpr->isValueDependent())
11757 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011758 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011759 /*AllowFold*/ false).take();
11760 EPI.NoexceptExpr = NoexceptExpr;
11761 }
11762 return;
11763 }
11764}
11765
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011766/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11767Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11768 // Implicitly declared functions (e.g. copy constructors) are
11769 // __host__ __device__
11770 if (D->isImplicit())
11771 return CFT_HostDevice;
11772
11773 if (D->hasAttr<CUDAGlobalAttr>())
11774 return CFT_Global;
11775
11776 if (D->hasAttr<CUDADeviceAttr>()) {
11777 if (D->hasAttr<CUDAHostAttr>())
11778 return CFT_HostDevice;
11779 else
11780 return CFT_Device;
11781 }
11782
11783 return CFT_Host;
11784}
11785
11786bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11787 CUDAFunctionTarget CalleeTarget) {
11788 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11789 // Callable from the device only."
11790 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11791 return true;
11792
11793 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11794 // Callable from the host only."
11795 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11796 // Callable from the host only."
11797 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11798 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11799 return true;
11800
11801 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11802 return true;
11803
11804 return false;
11805}