blob: 8f8e22a68a277905bec3702eb8cbdf7559574051 [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
Douglas Gregora8f32e02009-10-06 17:59:45 +00001314/// \brief Determine whether the type \p Derived is a C++ class that is
1315/// derived from the type \p Base.
1316bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001317 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001318 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001319
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001320 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001321 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001322 return false;
1323
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001324 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001325 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001326 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001327
1328 // If either the base or the derived type is invalid, don't try to
1329 // check whether one is derived from the other.
1330 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1331 return false;
1332
John McCall86ff3082010-02-04 22:26:26 +00001333 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1334 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001335}
1336
1337/// \brief Determine whether the type \p Derived is a C++ class that is
1338/// derived from the type \p Base.
1339bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001340 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001341 return false;
1342
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001343 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001344 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001345 return false;
1346
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001347 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001348 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001349 return false;
1350
Douglas Gregora8f32e02009-10-06 17:59:45 +00001351 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1352}
1353
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001354void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001355 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001356 assert(BasePathArray.empty() && "Base path array must be empty!");
1357 assert(Paths.isRecordingPaths() && "Must record paths!");
1358
1359 const CXXBasePath &Path = Paths.front();
1360
1361 // We first go backward and check if we have a virtual base.
1362 // FIXME: It would be better if CXXBasePath had the base specifier for
1363 // the nearest virtual base.
1364 unsigned Start = 0;
1365 for (unsigned I = Path.size(); I != 0; --I) {
1366 if (Path[I - 1].Base->isVirtual()) {
1367 Start = I - 1;
1368 break;
1369 }
1370 }
1371
1372 // Now add all bases.
1373 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001374 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001375}
1376
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001377/// \brief Determine whether the given base path includes a virtual
1378/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001379bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1380 for (CXXCastPath::const_iterator B = BasePath.begin(),
1381 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001382 B != BEnd; ++B)
1383 if ((*B)->isVirtual())
1384 return true;
1385
1386 return false;
1387}
1388
Douglas Gregora8f32e02009-10-06 17:59:45 +00001389/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1390/// conversion (where Derived and Base are class types) is
1391/// well-formed, meaning that the conversion is unambiguous (and
1392/// that all of the base classes are accessible). Returns true
1393/// and emits a diagnostic if the code is ill-formed, returns false
1394/// otherwise. Loc is the location where this routine should point to
1395/// if there is an error, and Range is the source range to highlight
1396/// if there is an error.
1397bool
1398Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001399 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001400 unsigned AmbigiousBaseConvID,
1401 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001402 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001403 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001404 // First, determine whether the path from Derived to Base is
1405 // ambiguous. This is slightly more expensive than checking whether
1406 // the Derived to Base conversion exists, because here we need to
1407 // explore multiple paths to determine if there is an ambiguity.
1408 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1409 /*DetectVirtual=*/false);
1410 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1411 assert(DerivationOkay &&
1412 "Can only be used with a derived-to-base conversion");
1413 (void)DerivationOkay;
1414
1415 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001416 if (InaccessibleBaseID) {
1417 // Check that the base class can be accessed.
1418 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1419 InaccessibleBaseID)) {
1420 case AR_inaccessible:
1421 return true;
1422 case AR_accessible:
1423 case AR_dependent:
1424 case AR_delayed:
1425 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001426 }
John McCall6b2accb2010-02-10 09:31:12 +00001427 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001428
1429 // Build a base path if necessary.
1430 if (BasePath)
1431 BuildBasePathArray(Paths, *BasePath);
1432 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001433 }
1434
1435 // We know that the derived-to-base conversion is ambiguous, and
1436 // we're going to produce a diagnostic. Perform the derived-to-base
1437 // search just one more time to compute all of the possible paths so
1438 // that we can print them out. This is more expensive than any of
1439 // the previous derived-to-base checks we've done, but at this point
1440 // performance isn't as much of an issue.
1441 Paths.clear();
1442 Paths.setRecordingPaths(true);
1443 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1444 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1445 (void)StillOkay;
1446
1447 // Build up a textual representation of the ambiguous paths, e.g.,
1448 // D -> B -> A, that will be used to illustrate the ambiguous
1449 // conversions in the diagnostic. We only print one of the paths
1450 // to each base class subobject.
1451 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1452
1453 Diag(Loc, AmbigiousBaseConvID)
1454 << Derived << Base << PathDisplayStr << Range << Name;
1455 return true;
1456}
1457
1458bool
1459Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001460 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001461 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001462 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001463 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001464 IgnoreAccess ? 0
1465 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001466 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001467 Loc, Range, DeclarationName(),
1468 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001469}
1470
1471
1472/// @brief Builds a string representing ambiguous paths from a
1473/// specific derived class to different subobjects of the same base
1474/// class.
1475///
1476/// This function builds a string that can be used in error messages
1477/// to show the different paths that one can take through the
1478/// inheritance hierarchy to go from the derived class to different
1479/// subobjects of a base class. The result looks something like this:
1480/// @code
1481/// struct D -> struct B -> struct A
1482/// struct D -> struct C -> struct A
1483/// @endcode
1484std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1485 std::string PathDisplayStr;
1486 std::set<unsigned> DisplayedPaths;
1487 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1488 Path != Paths.end(); ++Path) {
1489 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1490 // We haven't displayed a path to this particular base
1491 // class subobject yet.
1492 PathDisplayStr += "\n ";
1493 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1494 for (CXXBasePath::const_iterator Element = Path->begin();
1495 Element != Path->end(); ++Element)
1496 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1497 }
1498 }
1499
1500 return PathDisplayStr;
1501}
1502
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001503//===----------------------------------------------------------------------===//
1504// C++ class member Handling
1505//===----------------------------------------------------------------------===//
1506
Abramo Bagnara6206d532010-06-05 05:09:32 +00001507/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001508bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1509 SourceLocation ASLoc,
1510 SourceLocation ColonLoc,
1511 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001512 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001513 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001514 ASLoc, ColonLoc);
1515 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001516 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001517}
1518
Richard Smitha4b39652012-08-06 03:25:17 +00001519/// CheckOverrideControl - Check C++11 override control semantics.
1520void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001521 if (D->isInvalidDecl())
1522 return;
1523
Chris Lattner5f9e2722011-07-23 10:55:15 +00001524 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001525
Richard Smitha4b39652012-08-06 03:25:17 +00001526 // Do we know which functions this declaration might be overriding?
1527 bool OverridesAreKnown = !MD ||
1528 (!MD->getParent()->hasAnyDependentBases() &&
1529 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001530
Richard Smitha4b39652012-08-06 03:25:17 +00001531 if (!MD || !MD->isVirtual()) {
1532 if (OverridesAreKnown) {
1533 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1534 Diag(OA->getLocation(),
1535 diag::override_keyword_only_allowed_on_virtual_member_functions)
1536 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1537 D->dropAttr<OverrideAttr>();
1538 }
1539 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1540 Diag(FA->getLocation(),
1541 diag::override_keyword_only_allowed_on_virtual_member_functions)
1542 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1543 D->dropAttr<FinalAttr>();
1544 }
1545 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001546 return;
1547 }
Richard Smitha4b39652012-08-06 03:25:17 +00001548
1549 if (!OverridesAreKnown)
1550 return;
1551
1552 // C++11 [class.virtual]p5:
1553 // If a virtual function is marked with the virt-specifier override and
1554 // does not override a member function of a base class, the program is
1555 // ill-formed.
1556 bool HasOverriddenMethods =
1557 MD->begin_overridden_methods() != MD->end_overridden_methods();
1558 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1559 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1560 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001561}
1562
Richard Smitha4b39652012-08-06 03:25:17 +00001563/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001564/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001565/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001566bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1567 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001568 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001569 return false;
1570
1571 Diag(New->getLocation(), diag::err_final_function_overridden)
1572 << New->getDeclName();
1573 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1574 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001575}
1576
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001577static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001578 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1579 // FIXME: Destruction of ObjC lifetime types has side-effects.
1580 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1581 return !RD->isCompleteDefinition() ||
1582 !RD->hasTrivialDefaultConstructor() ||
1583 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001584 return false;
1585}
1586
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001587/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1588/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001589/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001590/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1591/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001592NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001593Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001594 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001595 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001596 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001597 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001598 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1599 DeclarationName Name = NameInfo.getName();
1600 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001601
1602 // For anonymous bitfields, the location should point to the type.
1603 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001604 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001605
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001606 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001607
John McCall4bde1e12010-06-04 08:34:12 +00001608 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001609 assert(!DS.isFriendSpecified());
1610
Richard Smith1ab0d902011-06-25 02:28:38 +00001611 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001612
John McCalle402e722012-09-25 07:32:39 +00001613 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1614 // The Microsoft extension __interface only permits public member functions
1615 // and prohibits constructors, destructors, operators, non-public member
1616 // functions, static methods and data members.
1617 unsigned InvalidDecl;
1618 bool ShowDeclName = true;
1619 if (!isFunc)
1620 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1621 else if (AS != AS_public)
1622 InvalidDecl = 2;
1623 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1624 InvalidDecl = 3;
1625 else switch (Name.getNameKind()) {
1626 case DeclarationName::CXXConstructorName:
1627 InvalidDecl = 4;
1628 ShowDeclName = false;
1629 break;
1630
1631 case DeclarationName::CXXDestructorName:
1632 InvalidDecl = 5;
1633 ShowDeclName = false;
1634 break;
1635
1636 case DeclarationName::CXXOperatorName:
1637 case DeclarationName::CXXConversionFunctionName:
1638 InvalidDecl = 6;
1639 break;
1640
1641 default:
1642 InvalidDecl = 0;
1643 break;
1644 }
1645
1646 if (InvalidDecl) {
1647 if (ShowDeclName)
1648 Diag(Loc, diag::err_invalid_member_in_interface)
1649 << (InvalidDecl-1) << Name;
1650 else
1651 Diag(Loc, diag::err_invalid_member_in_interface)
1652 << (InvalidDecl-1) << "";
1653 return 0;
1654 }
1655 }
1656
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001657 // C++ 9.2p6: A member shall not be declared to have automatic storage
1658 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001659 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1660 // data members and cannot be applied to names declared const or static,
1661 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001662 switch (DS.getStorageClassSpec()) {
1663 case DeclSpec::SCS_unspecified:
1664 case DeclSpec::SCS_typedef:
1665 case DeclSpec::SCS_static:
1666 // FALL THROUGH.
1667 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001668 case DeclSpec::SCS_mutable:
1669 if (isFunc) {
1670 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001671 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001672 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001673 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Sebastian Redla11f42f2008-11-17 23:24:37 +00001675 // FIXME: It would be nicer if the keyword was ignored only for this
1676 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001677 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001678 }
1679 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001680 default:
1681 if (DS.getStorageClassSpecLoc().isValid())
1682 Diag(DS.getStorageClassSpecLoc(),
1683 diag::err_storageclass_invalid_for_member);
1684 else
1685 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1686 D.getMutableDeclSpec().ClearStorageClassSpecs();
1687 }
1688
Sebastian Redl669d5d72008-11-14 23:42:31 +00001689 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1690 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001691 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001692
David Blaikie1d87fba2013-01-30 01:22:18 +00001693 if (DS.isConstexprSpecified() && isInstField) {
1694 SemaDiagnosticBuilder B =
1695 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1696 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1697 if (InitStyle == ICIS_NoInit) {
1698 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1699 D.getMutableDeclSpec().ClearConstexprSpec();
1700 const char *PrevSpec;
1701 unsigned DiagID;
1702 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1703 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001704 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001705 assert(!Failed && "Making a constexpr member const shouldn't fail");
1706 } else {
1707 B << 1;
1708 const char *PrevSpec;
1709 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001710 if (D.getMutableDeclSpec().SetStorageClassSpec(
1711 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001712 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001713 "This is the only DeclSpec that should fail to be applied");
1714 B << 1;
1715 } else {
1716 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1717 isInstField = false;
1718 }
1719 }
1720 }
1721
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001722 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001723 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001724 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001725
1726 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001727 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001728 Diag(Loc, diag::err_bad_variable_name)
1729 << Name;
1730 return 0;
1731 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001732
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001733 IdentifierInfo *II = Name.getAsIdentifierInfo();
1734
Douglas Gregorf2503652011-09-21 14:40:46 +00001735 // Member field could not be with "template" keyword.
1736 // So TemplateParameterLists should be empty in this case.
1737 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001738 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001739 if (TemplateParams->size()) {
1740 // There is no such thing as a member field template.
1741 Diag(D.getIdentifierLoc(), diag::err_template_member)
1742 << II
1743 << SourceRange(TemplateParams->getTemplateLoc(),
1744 TemplateParams->getRAngleLoc());
1745 } else {
1746 // There is an extraneous 'template<>' for this member.
1747 Diag(TemplateParams->getTemplateLoc(),
1748 diag::err_template_member_noparams)
1749 << II
1750 << SourceRange(TemplateParams->getTemplateLoc(),
1751 TemplateParams->getRAngleLoc());
1752 }
1753 return 0;
1754 }
1755
Douglas Gregor922fff22010-10-13 22:19:53 +00001756 if (SS.isSet() && !SS.isInvalid()) {
1757 // The user provided a superfluous scope specifier inside a class
1758 // definition:
1759 //
1760 // class X {
1761 // int X::member;
1762 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001763 if (DeclContext *DC = computeDeclContext(SS, false))
1764 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001765 else
1766 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1767 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001768
Douglas Gregor922fff22010-10-13 22:19:53 +00001769 SS.clear();
1770 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001771
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001772 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001773 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001774 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001775 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001776 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001777
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001778 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001779 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001780 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001781 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001782
1783 // Non-instance-fields can't have a bitfield.
1784 if (BitWidth) {
1785 if (Member->isInvalidDecl()) {
1786 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001787 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001788 // C++ 9.6p3: A bit-field shall not be a static member.
1789 // "static member 'A' cannot be a bit-field"
1790 Diag(Loc, diag::err_static_not_bitfield)
1791 << Name << BitWidth->getSourceRange();
1792 } else if (isa<TypedefDecl>(Member)) {
1793 // "typedef member 'x' cannot be a bit-field"
1794 Diag(Loc, diag::err_typedef_not_bitfield)
1795 << Name << BitWidth->getSourceRange();
1796 } else {
1797 // A function typedef ("typedef int f(); f a;").
1798 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1799 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001800 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001801 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001802 }
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Chris Lattner8b963ef2009-03-05 23:01:03 +00001804 BitWidth = 0;
1805 Member->setInvalidDecl();
1806 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001807
1808 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001809
Douglas Gregor37b372b2009-08-20 22:52:58 +00001810 // If we have declared a member function template, set the access of the
1811 // templated declaration as well.
1812 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1813 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001814 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001815
Richard Smitha4b39652012-08-06 03:25:17 +00001816 if (VS.isOverrideSpecified())
1817 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1818 if (VS.isFinalSpecified())
1819 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001820
Douglas Gregorf5251602011-03-08 17:10:18 +00001821 if (VS.getLastLocation().isValid()) {
1822 // Update the end location of a method that has a virt-specifiers.
1823 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1824 MD->setRangeEnd(VS.getLastLocation());
1825 }
Richard Smitha4b39652012-08-06 03:25:17 +00001826
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001827 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001828
Douglas Gregor10bd3682008-11-17 22:58:34 +00001829 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001830
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001831 if (isInstField) {
1832 FieldDecl *FD = cast<FieldDecl>(Member);
1833 FieldCollector->Add(FD);
1834
1835 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1836 FD->getLocation())
1837 != DiagnosticsEngine::Ignored) {
1838 // Remember all explicit private FieldDecls that have a name, no side
1839 // effects and are not part of a dependent type declaration.
1840 if (!FD->isImplicit() && FD->getDeclName() &&
1841 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001842 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001843 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001844 !InitializationHasSideEffects(*FD))
1845 UnusedPrivateFields.insert(FD);
1846 }
1847 }
1848
John McCalld226f652010-08-21 09:40:31 +00001849 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001850}
1851
Hans Wennborg471f9852012-09-18 15:58:06 +00001852namespace {
1853 class UninitializedFieldVisitor
1854 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1855 Sema &S;
1856 ValueDecl *VD;
1857 public:
1858 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1859 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001860 S(S) {
1861 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1862 this->VD = IFD->getAnonField();
1863 else
1864 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001865 }
1866
1867 void HandleExpr(Expr *E) {
1868 if (!E) return;
1869
1870 // Expressions like x(x) sometimes lack the surrounding expressions
1871 // but need to be checked anyways.
1872 HandleValue(E);
1873 Visit(E);
1874 }
1875
1876 void HandleValue(Expr *E) {
1877 E = E->IgnoreParens();
1878
1879 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1880 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001881 return;
1882
1883 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1884 // or union.
1885 MemberExpr *FieldME = ME;
1886
Hans Wennborg471f9852012-09-18 15:58:06 +00001887 Expr *Base = E;
1888 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001889 ME = cast<MemberExpr>(Base);
1890
1891 if (isa<VarDecl>(ME->getMemberDecl()))
1892 return;
1893
1894 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1895 if (!FD->isAnonymousStructOrUnion())
1896 FieldME = ME;
1897
Hans Wennborg471f9852012-09-18 15:58:06 +00001898 Base = ME->getBase();
1899 }
1900
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001901 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00001902 unsigned diag = VD->getType()->isReferenceType()
1903 ? diag::warn_reference_field_is_uninit
1904 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001905 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001906 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001907 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00001908 }
1909
1910 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1911 HandleValue(CO->getTrueExpr());
1912 HandleValue(CO->getFalseExpr());
1913 return;
1914 }
1915
1916 if (BinaryConditionalOperator *BCO =
1917 dyn_cast<BinaryConditionalOperator>(E)) {
1918 HandleValue(BCO->getCommon());
1919 HandleValue(BCO->getFalseExpr());
1920 return;
1921 }
1922
1923 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1924 switch (BO->getOpcode()) {
1925 default:
1926 return;
1927 case(BO_PtrMemD):
1928 case(BO_PtrMemI):
1929 HandleValue(BO->getLHS());
1930 return;
1931 case(BO_Comma):
1932 HandleValue(BO->getRHS());
1933 return;
1934 }
1935 }
1936 }
1937
1938 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1939 if (E->getCastKind() == CK_LValueToRValue)
1940 HandleValue(E->getSubExpr());
1941
1942 Inherited::VisitImplicitCastExpr(E);
1943 }
1944
1945 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1946 Expr *Callee = E->getCallee();
1947 if (isa<MemberExpr>(Callee))
1948 HandleValue(Callee);
1949
1950 Inherited::VisitCXXMemberCallExpr(E);
1951 }
1952 };
1953 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1954 ValueDecl *VD) {
1955 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1956 }
1957} // namespace
1958
Richard Smith7a614d82011-06-11 17:19:42 +00001959/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001960/// in-class initializer for a non-static C++ class member, and after
1961/// instantiating an in-class initializer in a class template. Such actions
1962/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001963void
Richard Smithca523302012-06-10 03:12:00 +00001964Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001965 Expr *InitExpr) {
1966 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001967 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1968 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001969
1970 if (!InitExpr) {
1971 FD->setInvalidDecl();
1972 FD->removeInClassInitializer();
1973 return;
1974 }
1975
Peter Collingbournefef21892011-10-23 18:59:44 +00001976 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1977 FD->setInvalidDecl();
1978 FD->removeInClassInitializer();
1979 return;
1980 }
1981
Hans Wennborg471f9852012-09-18 15:58:06 +00001982 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1983 != DiagnosticsEngine::Ignored) {
1984 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1985 }
1986
Richard Smith7a614d82011-06-11 17:19:42 +00001987 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00001988 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001989 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001990 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001991 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1992 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001993 Expr **Inits = &InitExpr;
1994 unsigned NumInits = 1;
1995 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00001996 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00001997 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00001998 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00001999 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
2000 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00002001 if (Init.isInvalid()) {
2002 FD->setInvalidDecl();
2003 return;
2004 }
Richard Smith7a614d82011-06-11 17:19:42 +00002005 }
2006
Richard Smith41956372013-01-14 22:39:08 +00002007 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002008 // The initialization of each base and member constitutes a
2009 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002010 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002011 if (Init.isInvalid()) {
2012 FD->setInvalidDecl();
2013 return;
2014 }
2015
2016 InitExpr = Init.release();
2017
2018 FD->setInClassInitializer(InitExpr);
2019}
2020
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002021/// \brief Find the direct and/or virtual base specifiers that
2022/// correspond to the given base type, for use in base initialization
2023/// within a constructor.
2024static bool FindBaseInitializer(Sema &SemaRef,
2025 CXXRecordDecl *ClassDecl,
2026 QualType BaseType,
2027 const CXXBaseSpecifier *&DirectBaseSpec,
2028 const CXXBaseSpecifier *&VirtualBaseSpec) {
2029 // First, check for a direct base class.
2030 DirectBaseSpec = 0;
2031 for (CXXRecordDecl::base_class_const_iterator Base
2032 = ClassDecl->bases_begin();
2033 Base != ClassDecl->bases_end(); ++Base) {
2034 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2035 // We found a direct base of this type. That's what we're
2036 // initializing.
2037 DirectBaseSpec = &*Base;
2038 break;
2039 }
2040 }
2041
2042 // Check for a virtual base class.
2043 // FIXME: We might be able to short-circuit this if we know in advance that
2044 // there are no virtual bases.
2045 VirtualBaseSpec = 0;
2046 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2047 // We haven't found a base yet; search the class hierarchy for a
2048 // virtual base class.
2049 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2050 /*DetectVirtual=*/false);
2051 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2052 BaseType, Paths)) {
2053 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2054 Path != Paths.end(); ++Path) {
2055 if (Path->back().Base->isVirtual()) {
2056 VirtualBaseSpec = Path->back().Base;
2057 break;
2058 }
2059 }
2060 }
2061 }
2062
2063 return DirectBaseSpec || VirtualBaseSpec;
2064}
2065
Sebastian Redl6df65482011-09-24 17:48:25 +00002066/// \brief Handle a C++ member initializer using braced-init-list syntax.
2067MemInitResult
2068Sema::ActOnMemInitializer(Decl *ConstructorD,
2069 Scope *S,
2070 CXXScopeSpec &SS,
2071 IdentifierInfo *MemberOrBase,
2072 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002073 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002074 SourceLocation IdLoc,
2075 Expr *InitList,
2076 SourceLocation EllipsisLoc) {
2077 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002078 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002079 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002080}
2081
2082/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002083MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002084Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002085 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002086 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002087 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002088 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002089 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002090 SourceLocation IdLoc,
2091 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002092 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002093 SourceLocation RParenLoc,
2094 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002095 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2096 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002097 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002098 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002099 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002100}
2101
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002102namespace {
2103
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002104// Callback to only accept typo corrections that can be a valid C++ member
2105// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002106class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2107 public:
2108 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2109 : ClassDecl(ClassDecl) {}
2110
2111 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2112 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2113 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2114 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2115 else
2116 return isa<TypeDecl>(ND);
2117 }
2118 return false;
2119 }
2120
2121 private:
2122 CXXRecordDecl *ClassDecl;
2123};
2124
2125}
2126
Sebastian Redl6df65482011-09-24 17:48:25 +00002127/// \brief Handle a C++ member initializer.
2128MemInitResult
2129Sema::BuildMemInitializer(Decl *ConstructorD,
2130 Scope *S,
2131 CXXScopeSpec &SS,
2132 IdentifierInfo *MemberOrBase,
2133 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002134 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002135 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002136 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002137 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002138 if (!ConstructorD)
2139 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002140
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002141 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002142
2143 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002144 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002145 if (!Constructor) {
2146 // The user wrote a constructor initializer on a function that is
2147 // not a C++ constructor. Ignore the error for now, because we may
2148 // have more member initializers coming; we'll diagnose it just
2149 // once in ActOnMemInitializers.
2150 return true;
2151 }
2152
2153 CXXRecordDecl *ClassDecl = Constructor->getParent();
2154
2155 // C++ [class.base.init]p2:
2156 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002157 // constructor's class and, if not found in that scope, are looked
2158 // up in the scope containing the constructor's definition.
2159 // [Note: if the constructor's class contains a member with the
2160 // same name as a direct or virtual base class of the class, a
2161 // mem-initializer-id naming the member or base class and composed
2162 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002163 // mem-initializer-id for the hidden base class may be specified
2164 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002165 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002166 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002167 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002168 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002169 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002170 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002171 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2172 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002173 if (EllipsisLoc.isValid())
2174 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002175 << MemberOrBase
2176 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002177
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002178 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002179 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002180 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002181 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002182 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002183 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002184 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002185
2186 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002187 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002188 } else if (DS.getTypeSpecType() == TST_decltype) {
2189 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002190 } else {
2191 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2192 LookupParsedName(R, S, &SS);
2193
2194 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2195 if (!TyD) {
2196 if (R.isAmbiguous()) return true;
2197
John McCallfd225442010-04-09 19:01:14 +00002198 // We don't want access-control diagnostics here.
2199 R.suppressDiagnostics();
2200
Douglas Gregor7a886e12010-01-19 06:46:48 +00002201 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2202 bool NotUnknownSpecialization = false;
2203 DeclContext *DC = computeDeclContext(SS, false);
2204 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2205 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2206
2207 if (!NotUnknownSpecialization) {
2208 // When the scope specifier can refer to a member of an unknown
2209 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002210 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2211 SS.getWithLocInContext(Context),
2212 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002213 if (BaseType.isNull())
2214 return true;
2215
Douglas Gregor7a886e12010-01-19 06:46:48 +00002216 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002217 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002218 }
2219 }
2220
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002221 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002222 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002223 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002224 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002225 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002226 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002227 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2228 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002229 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002230 // We have found a non-static data member with a similar
2231 // name to what was typed; complain and initialize that
2232 // member.
2233 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2234 << MemberOrBase << true << CorrectedQuotedStr
2235 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2236 Diag(Member->getLocation(), diag::note_previous_decl)
2237 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002238
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002239 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002240 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002241 const CXXBaseSpecifier *DirectBaseSpec;
2242 const CXXBaseSpecifier *VirtualBaseSpec;
2243 if (FindBaseInitializer(*this, ClassDecl,
2244 Context.getTypeDeclType(Type),
2245 DirectBaseSpec, VirtualBaseSpec)) {
2246 // We have found a direct or virtual base class with a
2247 // similar name to what was typed; complain and initialize
2248 // that base class.
2249 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002250 << MemberOrBase << false << CorrectedQuotedStr
2251 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002252
2253 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2254 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002255 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002256 diag::note_base_class_specified_here)
2257 << BaseSpec->getType()
2258 << BaseSpec->getSourceRange();
2259
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002260 TyD = Type;
2261 }
2262 }
2263 }
2264
Douglas Gregor7a886e12010-01-19 06:46:48 +00002265 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002266 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002267 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002268 return true;
2269 }
John McCall2b194412009-12-21 10:41:20 +00002270 }
2271
Douglas Gregor7a886e12010-01-19 06:46:48 +00002272 if (BaseType.isNull()) {
2273 BaseType = Context.getTypeDeclType(TyD);
2274 if (SS.isSet()) {
2275 NestedNameSpecifier *Qualifier =
2276 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002277
Douglas Gregor7a886e12010-01-19 06:46:48 +00002278 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002279 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002280 }
John McCall2b194412009-12-21 10:41:20 +00002281 }
2282 }
Mike Stump1eb44332009-09-09 15:08:12 +00002283
John McCalla93c9342009-12-07 02:54:59 +00002284 if (!TInfo)
2285 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002286
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002287 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002288}
2289
Chandler Carruth81c64772011-09-03 01:14:15 +00002290/// Checks a member initializer expression for cases where reference (or
2291/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002292static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2293 Expr *Init,
2294 SourceLocation IdLoc) {
2295 QualType MemberTy = Member->getType();
2296
2297 // We only handle pointers and references currently.
2298 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2299 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2300 return;
2301
2302 const bool IsPointer = MemberTy->isPointerType();
2303 if (IsPointer) {
2304 if (const UnaryOperator *Op
2305 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2306 // The only case we're worried about with pointers requires taking the
2307 // address.
2308 if (Op->getOpcode() != UO_AddrOf)
2309 return;
2310
2311 Init = Op->getSubExpr();
2312 } else {
2313 // We only handle address-of expression initializers for pointers.
2314 return;
2315 }
2316 }
2317
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002318 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2319 // Taking the address of a temporary will be diagnosed as a hard error.
2320 if (IsPointer)
2321 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002322
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002323 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2324 << Member << Init->getSourceRange();
2325 } else if (const DeclRefExpr *DRE
2326 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2327 // We only warn when referring to a non-reference parameter declaration.
2328 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2329 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002330 return;
2331
2332 S.Diag(Init->getExprLoc(),
2333 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2334 : diag::warn_bind_ref_member_to_parameter)
2335 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002336 } else {
2337 // Other initializers are fine.
2338 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002339 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002340
2341 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2342 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002343}
2344
John McCallf312b1e2010-08-26 23:41:50 +00002345MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002346Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002347 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002348 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2349 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2350 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002351 "Member must be a FieldDecl or IndirectFieldDecl");
2352
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002353 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002354 return true;
2355
Douglas Gregor464b2f02010-11-05 22:21:31 +00002356 if (Member->isInvalidDecl())
2357 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002358
John McCallb4190042009-11-04 23:02:40 +00002359 // Diagnose value-uses of fields to initialize themselves, e.g.
2360 // foo(foo)
2361 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002362 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002363 Expr **Args;
2364 unsigned NumArgs;
2365 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2366 Args = ParenList->getExprs();
2367 NumArgs = ParenList->getNumExprs();
Richard Smithc83c2302012-12-19 01:39:02 +00002368 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002369 Args = InitList->getInits();
2370 NumArgs = InitList->getNumInits();
Richard Smithc83c2302012-12-19 01:39:02 +00002371 } else {
2372 // Template instantiation doesn't reconstruct ParenListExprs for us.
2373 Args = &Init;
2374 NumArgs = 1;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002375 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002376
Richard Trieude5e75c2012-06-14 23:11:34 +00002377 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2378 != DiagnosticsEngine::Ignored)
2379 for (unsigned i = 0; i < NumArgs; ++i)
2380 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002381 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002382 // initializing the i'th field, throw a warning if any of the >= i'th
2383 // fields are used, as they are not yet initialized.
2384 // Right now we are only handling the case where the i'th field uses
2385 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002386 // Also need to take into account that some fields may be initialized by
2387 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002388 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002389
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002390 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002391
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002392 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002393 // Can't check initialization for a member of dependent type or when
2394 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002395 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002396 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002397 bool InitList = false;
2398 if (isa<InitListExpr>(Init)) {
2399 InitList = true;
2400 Args = &Init;
2401 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002402
2403 if (isStdInitializerList(Member->getType(), 0)) {
2404 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2405 << /*at end of ctor*/1 << InitRange;
2406 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002407 }
2408
Chandler Carruth894aed92010-12-06 09:23:57 +00002409 // Initialize the member.
2410 InitializedEntity MemberEntity =
2411 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2412 : InitializedEntity::InitializeMember(IndirectMember, 0);
2413 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002414 InitList ? InitializationKind::CreateDirectList(IdLoc)
2415 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2416 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002417
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002418 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2419 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002420 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002421 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002422 if (MemberInit.isInvalid())
2423 return true;
2424
Richard Smith41956372013-01-14 22:39:08 +00002425 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002426 // The initialization of each base and member constitutes a
2427 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002428 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002429 if (MemberInit.isInvalid())
2430 return true;
2431
Richard Smithc83c2302012-12-19 01:39:02 +00002432 Init = MemberInit.get();
2433 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002434 }
2435
Chandler Carruth894aed92010-12-06 09:23:57 +00002436 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002437 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2438 InitRange.getBegin(), Init,
2439 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002440 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002441 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2442 InitRange.getBegin(), Init,
2443 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002444 }
Eli Friedman59c04372009-07-29 19:44:27 +00002445}
2446
John McCallf312b1e2010-08-26 23:41:50 +00002447MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002448Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002449 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002450 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002451 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002452 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002453 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002454 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002455
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002456 bool InitList = true;
2457 Expr **Args = &Init;
2458 unsigned NumArgs = 1;
2459 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2460 InitList = false;
2461 Args = ParenList->getExprs();
2462 NumArgs = ParenList->getNumExprs();
2463 }
2464
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002465 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002466 // Initialize the object.
2467 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2468 QualType(ClassDecl->getTypeForDecl(), 0));
2469 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002470 InitList ? InitializationKind::CreateDirectList(NameLoc)
2471 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2472 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002473 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2474 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002475 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002476 0);
Sean Hunt41717662011-02-26 19:13:13 +00002477 if (DelegationInit.isInvalid())
2478 return true;
2479
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002480 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2481 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002482
Richard Smith41956372013-01-14 22:39:08 +00002483 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002484 // The initialization of each base and member constitutes a
2485 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002486 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2487 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002488 if (DelegationInit.isInvalid())
2489 return true;
2490
Eli Friedmand21016f2012-05-19 23:35:23 +00002491 // If we are in a dependent context, template instantiation will
2492 // perform this type-checking again. Just save the arguments that we
2493 // received in a ParenListExpr.
2494 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2495 // of the information that we have about the base
2496 // initializer. However, deconstructing the ASTs is a dicey process,
2497 // and this approach is far more likely to get the corner cases right.
2498 if (CurContext->isDependentContext())
2499 DelegationInit = Owned(Init);
2500
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002501 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002502 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002503 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002504}
2505
2506MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002507Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002508 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002509 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002510 SourceLocation BaseLoc
2511 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002512
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002513 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2514 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2515 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2516
2517 // C++ [class.base.init]p2:
2518 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002519 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002520 // of that class, the mem-initializer is ill-formed. A
2521 // mem-initializer-list can initialize a base class using any
2522 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002523 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002524
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002525 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002526 if (EllipsisLoc.isValid()) {
2527 // This is a pack expansion.
2528 if (!BaseType->containsUnexpandedParameterPack()) {
2529 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002530 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002531
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002532 EllipsisLoc = SourceLocation();
2533 }
2534 } else {
2535 // Check for any unexpanded parameter packs.
2536 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2537 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002538
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002539 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002540 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002541 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002542
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002543 // Check for direct and virtual base classes.
2544 const CXXBaseSpecifier *DirectBaseSpec = 0;
2545 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2546 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002547 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2548 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002549 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002550
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002551 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2552 VirtualBaseSpec);
2553
2554 // C++ [base.class.init]p2:
2555 // Unless the mem-initializer-id names a nonstatic data member of the
2556 // constructor's class or a direct or virtual base of that class, the
2557 // mem-initializer is ill-formed.
2558 if (!DirectBaseSpec && !VirtualBaseSpec) {
2559 // If the class has any dependent bases, then it's possible that
2560 // one of those types will resolve to the same type as
2561 // BaseType. Therefore, just treat this as a dependent base
2562 // class initialization. FIXME: Should we try to check the
2563 // initialization anyway? It seems odd.
2564 if (ClassDecl->hasAnyDependentBases())
2565 Dependent = true;
2566 else
2567 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2568 << BaseType << Context.getTypeDeclType(ClassDecl)
2569 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2570 }
2571 }
2572
2573 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002574 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002575
Sebastian Redl6df65482011-09-24 17:48:25 +00002576 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2577 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002578 InitRange.getBegin(), Init,
2579 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002580 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002581
2582 // C++ [base.class.init]p2:
2583 // If a mem-initializer-id is ambiguous because it designates both
2584 // a direct non-virtual base class and an inherited virtual base
2585 // class, the mem-initializer is ill-formed.
2586 if (DirectBaseSpec && VirtualBaseSpec)
2587 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002588 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002589
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002590 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002591 if (!BaseSpec)
2592 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2593
2594 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002595 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002596 Expr **Args = &Init;
2597 unsigned NumArgs = 1;
2598 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002599 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002600 Args = ParenList->getExprs();
2601 NumArgs = ParenList->getNumExprs();
2602 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002603
2604 InitializedEntity BaseEntity =
2605 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2606 InitializationKind Kind =
2607 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2608 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2609 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002610 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2611 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002612 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002613 if (BaseInit.isInvalid())
2614 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002615
Richard Smith41956372013-01-14 22:39:08 +00002616 // C++11 [class.base.init]p7:
2617 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002618 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002619 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002620 if (BaseInit.isInvalid())
2621 return true;
2622
2623 // If we are in a dependent context, template instantiation will
2624 // perform this type-checking again. Just save the arguments that we
2625 // received in a ParenListExpr.
2626 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2627 // of the information that we have about the base
2628 // initializer. However, deconstructing the ASTs is a dicey process,
2629 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002630 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002631 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002632
Sean Huntcbb67482011-01-08 20:30:50 +00002633 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002634 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002635 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002636 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002637 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002638}
2639
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002640// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002641static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2642 if (T.isNull()) T = E->getType();
2643 QualType TargetType = SemaRef.BuildReferenceType(
2644 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002645 SourceLocation ExprLoc = E->getLocStart();
2646 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2647 TargetType, ExprLoc);
2648
2649 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2650 SourceRange(ExprLoc, ExprLoc),
2651 E->getSourceRange()).take();
2652}
2653
Anders Carlssone5ef7402010-04-23 03:10:23 +00002654/// ImplicitInitializerKind - How an implicit base or member initializer should
2655/// initialize its base or member.
2656enum ImplicitInitializerKind {
2657 IIK_Default,
2658 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002659 IIK_Move,
2660 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002661};
2662
Anders Carlssondefefd22010-04-23 02:00:02 +00002663static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002664BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002665 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002666 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002667 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002668 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002669 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002670 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2671 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002672
John McCall60d7b3a2010-08-24 06:29:42 +00002673 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002674
2675 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002676 case IIK_Inherit: {
2677 const CXXRecordDecl *Inherited =
2678 Constructor->getInheritedConstructor()->getParent();
2679 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2680 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2681 // C++11 [class.inhctor]p8:
2682 // Each expression in the expression-list is of the form
2683 // static_cast<T&&>(p), where p is the name of the corresponding
2684 // constructor parameter and T is the declared type of p.
2685 SmallVector<Expr*, 16> Args;
2686 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2687 ParmVarDecl *PD = Constructor->getParamDecl(I);
2688 ExprResult ArgExpr =
2689 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2690 VK_LValue, SourceLocation());
2691 if (ArgExpr.isInvalid())
2692 return true;
2693 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2694 }
2695
2696 InitializationKind InitKind = InitializationKind::CreateDirect(
2697 Constructor->getLocation(), SourceLocation(), SourceLocation());
2698 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2699 Args.data(), Args.size());
2700 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2701 break;
2702 }
2703 }
2704 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002705 case IIK_Default: {
2706 InitializationKind InitKind
2707 = InitializationKind::CreateDefault(Constructor->getLocation());
2708 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002709 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002710 break;
2711 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002712
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002713 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002714 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002715 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002716 ParmVarDecl *Param = Constructor->getParamDecl(0);
2717 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002718
Anders Carlssone5ef7402010-04-23 03:10:23 +00002719 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002720 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002721 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002722 Constructor->getLocation(), ParamType,
2723 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002724
Eli Friedman5f2987c2012-02-02 03:46:19 +00002725 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2726
Anders Carlssonc7957502010-04-24 22:02:54 +00002727 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002728 QualType ArgTy =
2729 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2730 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002731
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002732 if (Moving) {
2733 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2734 }
2735
John McCallf871d0c2010-08-07 06:22:56 +00002736 CXXCastPath BasePath;
2737 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002738 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2739 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002740 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002741 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002742
Anders Carlssone5ef7402010-04-23 03:10:23 +00002743 InitializationKind InitKind
2744 = InitializationKind::CreateDirect(Constructor->getLocation(),
2745 SourceLocation(), SourceLocation());
2746 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2747 &CopyCtorArg, 1);
2748 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002749 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002750 break;
2751 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002752 }
John McCall9ae2f072010-08-23 23:25:46 +00002753
Douglas Gregor53c374f2010-12-07 00:41:46 +00002754 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002755 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002756 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002757
Anders Carlssondefefd22010-04-23 02:00:02 +00002758 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002759 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002760 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2761 SourceLocation()),
2762 BaseSpec->isVirtual(),
2763 SourceLocation(),
2764 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002765 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002766 SourceLocation());
2767
Anders Carlssondefefd22010-04-23 02:00:02 +00002768 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002769}
2770
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002771static bool RefersToRValueRef(Expr *MemRef) {
2772 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2773 return Referenced->getType()->isRValueReferenceType();
2774}
2775
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002776static bool
2777BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002778 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002779 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002780 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002781 if (Field->isInvalidDecl())
2782 return true;
2783
Chandler Carruthf186b542010-06-29 23:50:44 +00002784 SourceLocation Loc = Constructor->getLocation();
2785
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002786 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2787 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002788 ParmVarDecl *Param = Constructor->getParamDecl(0);
2789 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002790
2791 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002792 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2793 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002794
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002795 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002796 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002797 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002798 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002799
Eli Friedman5f2987c2012-02-02 03:46:19 +00002800 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2801
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002802 if (Moving) {
2803 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2804 }
2805
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002806 // Build a reference to this field within the parameter.
2807 CXXScopeSpec SS;
2808 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2809 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002810 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2811 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002812 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002813 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002814 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002815 ParamType, Loc,
2816 /*IsArrow=*/false,
2817 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002818 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002819 /*FirstQualifierInScope=*/0,
2820 MemberLookup,
2821 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002822 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002823 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002824
2825 // C++11 [class.copy]p15:
2826 // - if a member m has rvalue reference type T&&, it is direct-initialized
2827 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002828 if (RefersToRValueRef(CtorArg.get())) {
2829 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002830 }
2831
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002832 // When the field we are copying is an array, create index variables for
2833 // each dimension of the array. We use these index variables to subscript
2834 // the source array, and other clients (e.g., CodeGen) will perform the
2835 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002836 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002837 QualType BaseType = Field->getType();
2838 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002839 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002840 while (const ConstantArrayType *Array
2841 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002842 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002843 // Create the iteration variable for this array index.
2844 IdentifierInfo *IterationVarName = 0;
2845 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002846 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002847 llvm::raw_svector_ostream OS(Str);
2848 OS << "__i" << IndexVariables.size();
2849 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2850 }
2851 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002852 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002853 IterationVarName, SizeType,
2854 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002855 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002856 IndexVariables.push_back(IterationVar);
2857
2858 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002859 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002860 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002861 assert(!IterationVarRef.isInvalid() &&
2862 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002863 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2864 assert(!IterationVarRef.isInvalid() &&
2865 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002866
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002867 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002868 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002869 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002870 Loc);
2871 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002872 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002873
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002874 BaseType = Array->getElementType();
2875 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002876
2877 // The array subscript expression is an lvalue, which is wrong for moving.
2878 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002879 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002880
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002881 // Construct the entity that we will be initializing. For an array, this
2882 // will be first element in the array, which may require several levels
2883 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002884 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002885 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002886 if (Indirect)
2887 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2888 else
2889 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002890 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2891 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2892 0,
2893 Entities.back()));
2894
2895 // Direct-initialize to use the copy constructor.
2896 InitializationKind InitKind =
2897 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2898
Sebastian Redl74e611a2011-09-04 18:14:28 +00002899 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002900 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002901 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002902
John McCall60d7b3a2010-08-24 06:29:42 +00002903 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002904 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002905 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002906 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002907 if (MemberInit.isInvalid())
2908 return true;
2909
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002910 if (Indirect) {
2911 assert(IndexVariables.size() == 0 &&
2912 "Indirect field improperly initialized");
2913 CXXMemberInit
2914 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2915 Loc, Loc,
2916 MemberInit.takeAs<Expr>(),
2917 Loc);
2918 } else
2919 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2920 Loc, MemberInit.takeAs<Expr>(),
2921 Loc,
2922 IndexVariables.data(),
2923 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002924 return false;
2925 }
2926
Richard Smith07b0fdc2013-03-18 21:12:30 +00002927 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
2928 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002929
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002930 QualType FieldBaseElementType =
2931 SemaRef.Context.getBaseElementType(Field->getType());
2932
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002933 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002934 InitializedEntity InitEntity
2935 = Indirect? InitializedEntity::InitializeMember(Indirect)
2936 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002937 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002938 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002939
2940 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002941 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002942 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002943
Douglas Gregor53c374f2010-12-07 00:41:46 +00002944 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002945 if (MemberInit.isInvalid())
2946 return true;
2947
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002948 if (Indirect)
2949 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2950 Indirect, Loc,
2951 Loc,
2952 MemberInit.get(),
2953 Loc);
2954 else
2955 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2956 Field, Loc, Loc,
2957 MemberInit.get(),
2958 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002959 return false;
2960 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002961
Sean Hunt1f2f3842011-05-17 00:19:05 +00002962 if (!Field->getParent()->isUnion()) {
2963 if (FieldBaseElementType->isReferenceType()) {
2964 SemaRef.Diag(Constructor->getLocation(),
2965 diag::err_uninitialized_member_in_ctor)
2966 << (int)Constructor->isImplicit()
2967 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2968 << 0 << Field->getDeclName();
2969 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2970 return true;
2971 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002972
Sean Hunt1f2f3842011-05-17 00:19:05 +00002973 if (FieldBaseElementType.isConstQualified()) {
2974 SemaRef.Diag(Constructor->getLocation(),
2975 diag::err_uninitialized_member_in_ctor)
2976 << (int)Constructor->isImplicit()
2977 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2978 << 1 << Field->getDeclName();
2979 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2980 return true;
2981 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002982 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002983
David Blaikie4e4d0842012-03-11 07:00:24 +00002984 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002985 FieldBaseElementType->isObjCRetainableType() &&
2986 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2987 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002988 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002989 // Default-initialize Objective-C pointers to NULL.
2990 CXXMemberInit
2991 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2992 Loc, Loc,
2993 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2994 Loc);
2995 return false;
2996 }
2997
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002998 // Nothing to initialize.
2999 CXXMemberInit = 0;
3000 return false;
3001}
John McCallf1860e52010-05-20 23:23:51 +00003002
3003namespace {
3004struct BaseAndFieldInfo {
3005 Sema &S;
3006 CXXConstructorDecl *Ctor;
3007 bool AnyErrorsInInits;
3008 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003009 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003010 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003011
3012 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3013 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003014 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3015 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003016 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003017 else if (Generated && Ctor->isMoveConstructor())
3018 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003019 else if (Ctor->getInheritedConstructor())
3020 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003021 else
3022 IIK = IIK_Default;
3023 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003024
3025 bool isImplicitCopyOrMove() const {
3026 switch (IIK) {
3027 case IIK_Copy:
3028 case IIK_Move:
3029 return true;
3030
3031 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003032 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003033 return false;
3034 }
David Blaikie30263482012-01-20 21:50:17 +00003035
3036 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003037 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003038
3039 bool addFieldInitializer(CXXCtorInitializer *Init) {
3040 AllToInit.push_back(Init);
3041
3042 // Check whether this initializer makes the field "used".
3043 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
3044 S.UnusedPrivateFields.remove(Init->getAnyMember());
3045
3046 return false;
3047 }
John McCallf1860e52010-05-20 23:23:51 +00003048};
3049}
3050
Richard Smitha4950662011-09-19 13:34:43 +00003051/// \brief Determine whether the given indirect field declaration is somewhere
3052/// within an anonymous union.
3053static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3054 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3055 CEnd = F->chain_end();
3056 C != CEnd; ++C)
3057 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3058 if (Record->isUnion())
3059 return true;
3060
3061 return false;
3062}
3063
Douglas Gregorddb21472011-11-02 23:04:16 +00003064/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3065/// array type.
3066static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3067 if (T->isIncompleteArrayType())
3068 return true;
3069
3070 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3071 if (!ArrayT->getSize())
3072 return true;
3073
3074 T = ArrayT->getElementType();
3075 }
3076
3077 return false;
3078}
3079
Richard Smith7a614d82011-06-11 17:19:42 +00003080static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003081 FieldDecl *Field,
3082 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003083
Chandler Carruthe861c602010-06-30 02:59:29 +00003084 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003085 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3086 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003087
Richard Smith0b8220a2012-08-07 21:30:42 +00003088 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003089 // has a brace-or-equal-initializer, the entity is initialized as specified
3090 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003091 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003092 CXXCtorInitializer *Init;
3093 if (Indirect)
3094 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3095 SourceLocation(),
3096 SourceLocation(), 0,
3097 SourceLocation());
3098 else
3099 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3100 SourceLocation(),
3101 SourceLocation(), 0,
3102 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003103 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003104 }
3105
Richard Smithc115f632011-09-18 11:14:50 +00003106 // Don't build an implicit initializer for union members if none was
3107 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003108 if (Field->getParent()->isUnion() ||
3109 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003110 return false;
3111
Douglas Gregorddb21472011-11-02 23:04:16 +00003112 // Don't initialize incomplete or zero-length arrays.
3113 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3114 return false;
3115
John McCallf1860e52010-05-20 23:23:51 +00003116 // Don't try to build an implicit initializer if there were semantic
3117 // errors in any of the initializers (and therefore we might be
3118 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003119 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003120 return false;
3121
Sean Huntcbb67482011-01-08 20:30:50 +00003122 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003123 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3124 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003125 return true;
John McCallf1860e52010-05-20 23:23:51 +00003126
Richard Smith0b8220a2012-08-07 21:30:42 +00003127 if (!Init)
3128 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003129
Richard Smith0b8220a2012-08-07 21:30:42 +00003130 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003131}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003132
3133bool
3134Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3135 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003136 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003137 Constructor->setNumCtorInitializers(1);
3138 CXXCtorInitializer **initializer =
3139 new (Context) CXXCtorInitializer*[1];
3140 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3141 Constructor->setCtorInitializers(initializer);
3142
Sean Huntb76af9c2011-05-03 23:05:34 +00003143 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003144 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003145 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3146 }
3147
Sean Huntc1598702011-05-05 00:05:47 +00003148 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003149
Sean Hunt059ce0d2011-05-01 07:04:31 +00003150 return false;
3151}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003152
David Blaikie93c86172013-01-17 05:26:25 +00003153bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3154 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003155 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003156 // Just store the initializers as written, they will be checked during
3157 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003158 if (!Initializers.empty()) {
3159 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003160 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003161 new (Context) CXXCtorInitializer*[Initializers.size()];
3162 memcpy(baseOrMemberInitializers, Initializers.data(),
3163 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003164 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003165 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003166
3167 // Let template instantiation know whether we had errors.
3168 if (AnyErrors)
3169 Constructor->setInvalidDecl();
3170
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003171 return false;
3172 }
3173
John McCallf1860e52010-05-20 23:23:51 +00003174 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003175
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003176 // We need to build the initializer AST according to order of construction
3177 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003178 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003179 if (!ClassDecl)
3180 return true;
3181
Eli Friedman80c30da2009-11-09 19:20:36 +00003182 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003183
David Blaikie93c86172013-01-17 05:26:25 +00003184 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003185 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003186
3187 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003188 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003189 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003190 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003191 }
3192
Anders Carlsson711f34a2010-04-21 19:52:01 +00003193 // Keep track of the direct virtual bases.
3194 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3195 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3196 E = ClassDecl->bases_end(); I != E; ++I) {
3197 if (I->isVirtual())
3198 DirectVBases.insert(I);
3199 }
3200
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003201 // Push virtual bases before others.
3202 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3203 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3204
Sean Huntcbb67482011-01-08 20:30:50 +00003205 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003206 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3207 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003208 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003209 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003210 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003211 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003212 VBase, IsInheritedVirtualBase,
3213 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003214 HadError = true;
3215 continue;
3216 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003217
John McCallf1860e52010-05-20 23:23:51 +00003218 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003219 }
3220 }
Mike Stump1eb44332009-09-09 15:08:12 +00003221
John McCallf1860e52010-05-20 23:23:51 +00003222 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003223 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3224 E = ClassDecl->bases_end(); Base != E; ++Base) {
3225 // Virtuals are in the virtual base list and already constructed.
3226 if (Base->isVirtual())
3227 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003228
Sean Huntcbb67482011-01-08 20:30:50 +00003229 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003230 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3231 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003232 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003233 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003234 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003235 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003236 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003237 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003238 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003239 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003240
John McCallf1860e52010-05-20 23:23:51 +00003241 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003242 }
3243 }
Mike Stump1eb44332009-09-09 15:08:12 +00003244
John McCallf1860e52010-05-20 23:23:51 +00003245 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003246 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3247 MemEnd = ClassDecl->decls_end();
3248 Mem != MemEnd; ++Mem) {
3249 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003250 // C++ [class.bit]p2:
3251 // A declaration for a bit-field that omits the identifier declares an
3252 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3253 // initialized.
3254 if (F->isUnnamedBitfield())
3255 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003256
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003257 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003258 // handle anonymous struct/union fields based on their individual
3259 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003260 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003261 continue;
3262
3263 if (CollectFieldInitializer(*this, Info, F))
3264 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003265 continue;
3266 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003267
3268 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003269 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003270 continue;
3271
3272 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3273 if (F->getType()->isIncompleteArrayType()) {
3274 assert(ClassDecl->hasFlexibleArrayMember() &&
3275 "Incomplete array type is not valid");
3276 continue;
3277 }
3278
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003279 // Initialize each field of an anonymous struct individually.
3280 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3281 HadError = true;
3282
3283 continue;
3284 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003285 }
Mike Stump1eb44332009-09-09 15:08:12 +00003286
David Blaikie93c86172013-01-17 05:26:25 +00003287 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003288 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003289 Constructor->setNumCtorInitializers(NumInitializers);
3290 CXXCtorInitializer **baseOrMemberInitializers =
3291 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003292 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003293 NumInitializers * sizeof(CXXCtorInitializer*));
3294 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003295
John McCallef027fe2010-03-16 21:39:52 +00003296 // Constructors implicitly reference the base and member
3297 // destructors.
3298 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3299 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003300 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003301
3302 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003303}
3304
David Blaikieee000bb2013-01-17 08:49:22 +00003305static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003306 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003307 const RecordDecl *RD = RT->getDecl();
3308 if (RD->isAnonymousStructOrUnion()) {
3309 for (RecordDecl::field_iterator Field = RD->field_begin(),
3310 E = RD->field_end(); Field != E; ++Field)
3311 PopulateKeysForFields(*Field, IdealInits);
3312 return;
3313 }
Eli Friedman6347f422009-07-21 19:28:10 +00003314 }
David Blaikieee000bb2013-01-17 08:49:22 +00003315 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003316}
3317
Anders Carlssonea356fb2010-04-02 05:42:15 +00003318static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003319 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003320}
3321
Anders Carlssonea356fb2010-04-02 05:42:15 +00003322static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003323 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003324 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003325 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003326
David Blaikieee000bb2013-01-17 08:49:22 +00003327 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003328}
3329
David Blaikie93c86172013-01-17 05:26:25 +00003330static void DiagnoseBaseOrMemInitializerOrder(
3331 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3332 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003333 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003334 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003335
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003336 // Don't check initializers order unless the warning is enabled at the
3337 // location of at least one initializer.
3338 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003339 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003340 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003341 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3342 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003343 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003344 ShouldCheckOrder = true;
3345 break;
3346 }
3347 }
3348 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003349 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003350
John McCalld6ca8da2010-04-10 07:37:23 +00003351 // Build the list of bases and members in the order that they'll
3352 // actually be initialized. The explicit initializers should be in
3353 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003354 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003355
Anders Carlsson071d6102010-04-02 03:38:04 +00003356 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3357
John McCalld6ca8da2010-04-10 07:37:23 +00003358 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003359 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003360 ClassDecl->vbases_begin(),
3361 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003362 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003363
John McCalld6ca8da2010-04-10 07:37:23 +00003364 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003365 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003366 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003367 if (Base->isVirtual())
3368 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003369 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003370 }
Mike Stump1eb44332009-09-09 15:08:12 +00003371
John McCalld6ca8da2010-04-10 07:37:23 +00003372 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003373 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003374 E = ClassDecl->field_end(); Field != E; ++Field) {
3375 if (Field->isUnnamedBitfield())
3376 continue;
3377
David Blaikieee000bb2013-01-17 08:49:22 +00003378 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003379 }
3380
John McCalld6ca8da2010-04-10 07:37:23 +00003381 unsigned NumIdealInits = IdealInitKeys.size();
3382 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003383
Sean Huntcbb67482011-01-08 20:30:50 +00003384 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003385 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003386 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003387 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003388
3389 // Scan forward to try to find this initializer in the idealized
3390 // initializers list.
3391 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3392 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003393 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003394
3395 // If we didn't find this initializer, it must be because we
3396 // scanned past it on a previous iteration. That can only
3397 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003398 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003399 Sema::SemaDiagnosticBuilder D =
3400 SemaRef.Diag(PrevInit->getSourceLocation(),
3401 diag::warn_initializer_out_of_order);
3402
Francois Pichet00eb3f92010-12-04 09:14:42 +00003403 if (PrevInit->isAnyMemberInitializer())
3404 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003405 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003406 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003407
Francois Pichet00eb3f92010-12-04 09:14:42 +00003408 if (Init->isAnyMemberInitializer())
3409 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003410 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003411 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003412
3413 // Move back to the initializer's location in the ideal list.
3414 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3415 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003416 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003417
3418 assert(IdealIndex != NumIdealInits &&
3419 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003420 }
John McCalld6ca8da2010-04-10 07:37:23 +00003421
3422 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003423 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003424}
3425
John McCall3c3ccdb2010-04-10 09:28:51 +00003426namespace {
3427bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003428 CXXCtorInitializer *Init,
3429 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003430 if (!PrevInit) {
3431 PrevInit = Init;
3432 return false;
3433 }
3434
Douglas Gregordc392c12013-03-25 23:28:23 +00003435 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003436 S.Diag(Init->getSourceLocation(),
3437 diag::err_multiple_mem_initialization)
3438 << Field->getDeclName()
3439 << Init->getSourceRange();
3440 else {
John McCallf4c73712011-01-19 06:33:43 +00003441 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003442 assert(BaseClass && "neither field nor base");
3443 S.Diag(Init->getSourceLocation(),
3444 diag::err_multiple_base_initialization)
3445 << QualType(BaseClass, 0)
3446 << Init->getSourceRange();
3447 }
3448 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3449 << 0 << PrevInit->getSourceRange();
3450
3451 return true;
3452}
3453
Sean Huntcbb67482011-01-08 20:30:50 +00003454typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003455typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3456
3457bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003458 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003459 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003460 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003461 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003462 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003463
3464 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003465 if (Parent->isUnion()) {
3466 UnionEntry &En = Unions[Parent];
3467 if (En.first && En.first != Child) {
3468 S.Diag(Init->getSourceLocation(),
3469 diag::err_multiple_mem_union_initialization)
3470 << Field->getDeclName()
3471 << Init->getSourceRange();
3472 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3473 << 0 << En.second->getSourceRange();
3474 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003475 }
3476 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003477 En.first = Child;
3478 En.second = Init;
3479 }
David Blaikie6fe29652011-11-17 06:01:57 +00003480 if (!Parent->isAnonymousStructOrUnion())
3481 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003482 }
3483
3484 Child = Parent;
3485 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003486 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003487
3488 return false;
3489}
3490}
3491
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003492/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003493void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003494 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003495 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003496 bool AnyErrors) {
3497 if (!ConstructorDecl)
3498 return;
3499
3500 AdjustDeclIfTemplate(ConstructorDecl);
3501
3502 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003503 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003504
3505 if (!Constructor) {
3506 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3507 return;
3508 }
3509
John McCall3c3ccdb2010-04-10 09:28:51 +00003510 // Mapping for the duplicate initializers check.
3511 // For member initializers, this is keyed with a FieldDecl*.
3512 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003513 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003514
3515 // Mapping for the inconsistent anonymous-union initializers check.
3516 RedundantUnionMap MemberUnions;
3517
Anders Carlssonea356fb2010-04-02 05:42:15 +00003518 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003519 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003520 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003521
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003522 // Set the source order index.
3523 Init->setSourceOrder(i);
3524
Francois Pichet00eb3f92010-12-04 09:14:42 +00003525 if (Init->isAnyMemberInitializer()) {
3526 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003527 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3528 CheckRedundantUnionInit(*this, Init, MemberUnions))
3529 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003530 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003531 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3532 if (CheckRedundantInit(*this, Init, Members[Key]))
3533 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003534 } else {
3535 assert(Init->isDelegatingInitializer());
3536 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003537 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003538 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003539 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003540 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003541 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003542 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003543 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003544 // Return immediately as the initializer is set.
3545 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003546 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003547 }
3548
Anders Carlssonea356fb2010-04-02 05:42:15 +00003549 if (HadError)
3550 return;
3551
David Blaikie93c86172013-01-17 05:26:25 +00003552 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003553
David Blaikie93c86172013-01-17 05:26:25 +00003554 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003555}
3556
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003557void
John McCallef027fe2010-03-16 21:39:52 +00003558Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3559 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003560 // Ignore dependent contexts. Also ignore unions, since their members never
3561 // have destructors implicitly called.
3562 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003563 return;
John McCall58e6f342010-03-16 05:22:47 +00003564
3565 // FIXME: all the access-control diagnostics are positioned on the
3566 // field/base declaration. That's probably good; that said, the
3567 // user might reasonably want to know why the destructor is being
3568 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003569
Anders Carlsson9f853df2009-11-17 04:44:12 +00003570 // Non-static data members.
3571 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3572 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003573 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003574 if (Field->isInvalidDecl())
3575 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003576
3577 // Don't destroy incomplete or zero-length arrays.
3578 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3579 continue;
3580
Anders Carlsson9f853df2009-11-17 04:44:12 +00003581 QualType FieldType = Context.getBaseElementType(Field->getType());
3582
3583 const RecordType* RT = FieldType->getAs<RecordType>();
3584 if (!RT)
3585 continue;
3586
3587 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003588 if (FieldClassDecl->isInvalidDecl())
3589 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003590 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003591 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003592 // The destructor for an implicit anonymous union member is never invoked.
3593 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3594 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003595
Douglas Gregordb89f282010-07-01 22:47:18 +00003596 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003597 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003598 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003599 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003600 << Field->getDeclName()
3601 << FieldType);
3602
Eli Friedman5f2987c2012-02-02 03:46:19 +00003603 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003604 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003605 }
3606
John McCall58e6f342010-03-16 05:22:47 +00003607 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3608
Anders Carlsson9f853df2009-11-17 04:44:12 +00003609 // Bases.
3610 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3611 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003612 // Bases are always records in a well-formed non-dependent class.
3613 const RecordType *RT = Base->getType()->getAs<RecordType>();
3614
3615 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003616 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003617 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003618
John McCall58e6f342010-03-16 05:22:47 +00003619 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003620 // If our base class is invalid, we probably can't get its dtor anyway.
3621 if (BaseClassDecl->isInvalidDecl())
3622 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003623 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003624 continue;
John McCall58e6f342010-03-16 05:22:47 +00003625
Douglas Gregordb89f282010-07-01 22:47:18 +00003626 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003627 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003628
3629 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003630 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003631 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003632 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003633 << Base->getSourceRange(),
3634 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003635
Eli Friedman5f2987c2012-02-02 03:46:19 +00003636 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003637 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003638 }
3639
3640 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003641 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3642 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003643
3644 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003645 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003646
3647 // Ignore direct virtual bases.
3648 if (DirectVirtualBases.count(RT))
3649 continue;
3650
John McCall58e6f342010-03-16 05:22:47 +00003651 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003652 // If our base class is invalid, we probably can't get its dtor anyway.
3653 if (BaseClassDecl->isInvalidDecl())
3654 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003655 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003656 continue;
John McCall58e6f342010-03-16 05:22:47 +00003657
Douglas Gregordb89f282010-07-01 22:47:18 +00003658 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003659 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003660 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003661 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003662 << VBase->getType(),
3663 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003664
Eli Friedman5f2987c2012-02-02 03:46:19 +00003665 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003666 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003667 }
3668}
3669
John McCalld226f652010-08-21 09:40:31 +00003670void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003671 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003672 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003673
Mike Stump1eb44332009-09-09 15:08:12 +00003674 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003675 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003676 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003677}
3678
Mike Stump1eb44332009-09-09 15:08:12 +00003679bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003680 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003681 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3682 unsigned DiagID;
3683 AbstractDiagSelID SelID;
3684
3685 public:
3686 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3687 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3688
3689 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003690 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003691 if (SelID == -1)
3692 S.Diag(Loc, DiagID) << T;
3693 else
3694 S.Diag(Loc, DiagID) << SelID << T;
3695 }
3696 } Diagnoser(DiagID, SelID);
3697
3698 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003699}
3700
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003701bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003702 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003703 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003704 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003705
Anders Carlsson11f21a02009-03-23 19:10:31 +00003706 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003707 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003708
Ted Kremenek6217b802009-07-29 21:53:49 +00003709 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003710 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003711 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003712 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003713
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003714 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003715 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003716 }
Mike Stump1eb44332009-09-09 15:08:12 +00003717
Ted Kremenek6217b802009-07-29 21:53:49 +00003718 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003719 if (!RT)
3720 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003721
John McCall86ff3082010-02-04 22:26:26 +00003722 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003723
John McCall94c3b562010-08-18 09:41:07 +00003724 // We can't answer whether something is abstract until it has a
3725 // definition. If it's currently being defined, we'll walk back
3726 // over all the declarations when we have a full definition.
3727 const CXXRecordDecl *Def = RD->getDefinition();
3728 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003729 return false;
3730
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003731 if (!RD->isAbstract())
3732 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003733
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003734 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003735 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003736
John McCall94c3b562010-08-18 09:41:07 +00003737 return true;
3738}
3739
3740void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3741 // Check if we've already emitted the list of pure virtual functions
3742 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003743 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003744 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003745
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003746 CXXFinalOverriderMap FinalOverriders;
3747 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003748
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003749 // Keep a set of seen pure methods so we won't diagnose the same method
3750 // more than once.
3751 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3752
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003753 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3754 MEnd = FinalOverriders.end();
3755 M != MEnd;
3756 ++M) {
3757 for (OverridingMethods::iterator SO = M->second.begin(),
3758 SOEnd = M->second.end();
3759 SO != SOEnd; ++SO) {
3760 // C++ [class.abstract]p4:
3761 // A class is abstract if it contains or inherits at least one
3762 // pure virtual function for which the final overrider is pure
3763 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003764
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003765 //
3766 if (SO->second.size() != 1)
3767 continue;
3768
3769 if (!SO->second.front().Method->isPure())
3770 continue;
3771
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003772 if (!SeenPureMethods.insert(SO->second.front().Method))
3773 continue;
3774
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003775 Diag(SO->second.front().Method->getLocation(),
3776 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003777 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003778 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003779 }
3780
3781 if (!PureVirtualClassDiagSet)
3782 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3783 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003784}
3785
Anders Carlsson8211eff2009-03-24 01:19:16 +00003786namespace {
John McCall94c3b562010-08-18 09:41:07 +00003787struct AbstractUsageInfo {
3788 Sema &S;
3789 CXXRecordDecl *Record;
3790 CanQualType AbstractType;
3791 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003792
John McCall94c3b562010-08-18 09:41:07 +00003793 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3794 : S(S), Record(Record),
3795 AbstractType(S.Context.getCanonicalType(
3796 S.Context.getTypeDeclType(Record))),
3797 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003798
John McCall94c3b562010-08-18 09:41:07 +00003799 void DiagnoseAbstractType() {
3800 if (Invalid) return;
3801 S.DiagnoseAbstractType(Record);
3802 Invalid = true;
3803 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003804
John McCall94c3b562010-08-18 09:41:07 +00003805 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3806};
3807
3808struct CheckAbstractUsage {
3809 AbstractUsageInfo &Info;
3810 const NamedDecl *Ctx;
3811
3812 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3813 : Info(Info), Ctx(Ctx) {}
3814
3815 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3816 switch (TL.getTypeLocClass()) {
3817#define ABSTRACT_TYPELOC(CLASS, PARENT)
3818#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003819 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003820#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003821 }
John McCall94c3b562010-08-18 09:41:07 +00003822 }
Mike Stump1eb44332009-09-09 15:08:12 +00003823
John McCall94c3b562010-08-18 09:41:07 +00003824 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3825 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3826 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003827 if (!TL.getArg(I))
3828 continue;
3829
John McCall94c3b562010-08-18 09:41:07 +00003830 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3831 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003832 }
John McCall94c3b562010-08-18 09:41:07 +00003833 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003834
John McCall94c3b562010-08-18 09:41:07 +00003835 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3836 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3837 }
Mike Stump1eb44332009-09-09 15:08:12 +00003838
John McCall94c3b562010-08-18 09:41:07 +00003839 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3840 // Visit the type parameters from a permissive context.
3841 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3842 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3843 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3844 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3845 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3846 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003847 }
John McCall94c3b562010-08-18 09:41:07 +00003848 }
Mike Stump1eb44332009-09-09 15:08:12 +00003849
John McCall94c3b562010-08-18 09:41:07 +00003850 // Visit pointee types from a permissive context.
3851#define CheckPolymorphic(Type) \
3852 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3853 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3854 }
3855 CheckPolymorphic(PointerTypeLoc)
3856 CheckPolymorphic(ReferenceTypeLoc)
3857 CheckPolymorphic(MemberPointerTypeLoc)
3858 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003859 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003860
John McCall94c3b562010-08-18 09:41:07 +00003861 /// Handle all the types we haven't given a more specific
3862 /// implementation for above.
3863 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3864 // Every other kind of type that we haven't called out already
3865 // that has an inner type is either (1) sugar or (2) contains that
3866 // inner type in some way as a subobject.
3867 if (TypeLoc Next = TL.getNextTypeLoc())
3868 return Visit(Next, Sel);
3869
3870 // If there's no inner type and we're in a permissive context,
3871 // don't diagnose.
3872 if (Sel == Sema::AbstractNone) return;
3873
3874 // Check whether the type matches the abstract type.
3875 QualType T = TL.getType();
3876 if (T->isArrayType()) {
3877 Sel = Sema::AbstractArrayType;
3878 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003879 }
John McCall94c3b562010-08-18 09:41:07 +00003880 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3881 if (CT != Info.AbstractType) return;
3882
3883 // It matched; do some magic.
3884 if (Sel == Sema::AbstractArrayType) {
3885 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3886 << T << TL.getSourceRange();
3887 } else {
3888 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3889 << Sel << T << TL.getSourceRange();
3890 }
3891 Info.DiagnoseAbstractType();
3892 }
3893};
3894
3895void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3896 Sema::AbstractDiagSelID Sel) {
3897 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3898}
3899
3900}
3901
3902/// Check for invalid uses of an abstract type in a method declaration.
3903static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3904 CXXMethodDecl *MD) {
3905 // No need to do the check on definitions, which require that
3906 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003907 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003908 return;
3909
3910 // For safety's sake, just ignore it if we don't have type source
3911 // information. This should never happen for non-implicit methods,
3912 // but...
3913 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3914 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3915}
3916
3917/// Check for invalid uses of an abstract type within a class definition.
3918static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3919 CXXRecordDecl *RD) {
3920 for (CXXRecordDecl::decl_iterator
3921 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3922 Decl *D = *I;
3923 if (D->isImplicit()) continue;
3924
3925 // Methods and method templates.
3926 if (isa<CXXMethodDecl>(D)) {
3927 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3928 } else if (isa<FunctionTemplateDecl>(D)) {
3929 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3930 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3931
3932 // Fields and static variables.
3933 } else if (isa<FieldDecl>(D)) {
3934 FieldDecl *FD = cast<FieldDecl>(D);
3935 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3936 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3937 } else if (isa<VarDecl>(D)) {
3938 VarDecl *VD = cast<VarDecl>(D);
3939 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3940 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3941
3942 // Nested classes and class templates.
3943 } else if (isa<CXXRecordDecl>(D)) {
3944 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3945 } else if (isa<ClassTemplateDecl>(D)) {
3946 CheckAbstractClassUsage(Info,
3947 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3948 }
3949 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003950}
3951
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003952/// \brief Perform semantic checks on a class definition that has been
3953/// completing, introducing implicitly-declared members, checking for
3954/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003955void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003956 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003957 return;
3958
John McCall94c3b562010-08-18 09:41:07 +00003959 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3960 AbstractUsageInfo Info(*this, Record);
3961 CheckAbstractClassUsage(Info, Record);
3962 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003963
3964 // If this is not an aggregate type and has no user-declared constructor,
3965 // complain about any non-static data members of reference or const scalar
3966 // type, since they will never get initializers.
3967 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003968 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3969 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003970 bool Complained = false;
3971 for (RecordDecl::field_iterator F = Record->field_begin(),
3972 FEnd = Record->field_end();
3973 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003974 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003975 continue;
3976
Douglas Gregor325e5932010-04-15 00:00:53 +00003977 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003978 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003979 if (!Complained) {
3980 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3981 << Record->getTagKind() << Record;
3982 Complained = true;
3983 }
3984
3985 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3986 << F->getType()->isReferenceType()
3987 << F->getDeclName();
3988 }
3989 }
3990 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003991
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003992 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003993 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003994
3995 if (Record->getIdentifier()) {
3996 // C++ [class.mem]p13:
3997 // If T is the name of a class, then each of the following shall have a
3998 // name different from T:
3999 // - every member of every anonymous union that is a member of class T.
4000 //
4001 // C++ [class.mem]p14:
4002 // In addition, if class T has a user-declared constructor (12.1), every
4003 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004004 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4005 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4006 ++I) {
4007 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004008 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4009 isa<IndirectFieldDecl>(D)) {
4010 Diag(D->getLocation(), diag::err_member_name_of_class)
4011 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004012 break;
4013 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004014 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004015 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004016
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004017 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004018 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004019 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004020 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004021 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4022 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4023 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004024
David Blaikieb6b5b972012-09-21 03:21:07 +00004025 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4026 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4027 DiagnoseAbstractType(Record);
4028 }
4029
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004030 if (!Record->isDependentType()) {
4031 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4032 MEnd = Record->method_end();
4033 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004034 // See if a method overloads virtual methods in a base
4035 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004036 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004037 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004038
4039 // Check whether the explicitly-defaulted special members are valid.
4040 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4041 CheckExplicitlyDefaultedSpecialMember(*M);
4042
4043 // For an explicitly defaulted or deleted special member, we defer
4044 // determining triviality until the class is complete. That time is now!
4045 if (!M->isImplicit() && !M->isUserProvided()) {
4046 CXXSpecialMember CSM = getSpecialMember(*M);
4047 if (CSM != CXXInvalid) {
4048 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4049
4050 // Inform the class that we've finished declaring this member.
4051 Record->finishedDefaultedOrDeletedMember(*M);
4052 }
4053 }
4054 }
4055 }
4056
4057 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4058 // function that is not a constructor declares that member function to be
4059 // const. [...] The class of which that function is a member shall be
4060 // a literal type.
4061 //
4062 // If the class has virtual bases, any constexpr members will already have
4063 // been diagnosed by the checks performed on the member declaration, so
4064 // suppress this (less useful) diagnostic.
4065 //
4066 // We delay this until we know whether an explicitly-defaulted (or deleted)
4067 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004068 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004069 !Record->isLiteral() && !Record->getNumVBases()) {
4070 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4071 MEnd = Record->method_end();
4072 M != MEnd; ++M) {
4073 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4074 switch (Record->getTemplateSpecializationKind()) {
4075 case TSK_ImplicitInstantiation:
4076 case TSK_ExplicitInstantiationDeclaration:
4077 case TSK_ExplicitInstantiationDefinition:
4078 // If a template instantiates to a non-literal type, but its members
4079 // instantiate to constexpr functions, the template is technically
4080 // ill-formed, but we allow it for sanity.
4081 continue;
4082
4083 case TSK_Undeclared:
4084 case TSK_ExplicitSpecialization:
4085 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4086 diag::err_constexpr_method_non_literal);
4087 break;
4088 }
4089
4090 // Only produce one error per class.
4091 break;
4092 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004093 }
4094 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004095
Richard Smith07b0fdc2013-03-18 21:12:30 +00004096 // Declare inheriting constructors. We do this eagerly here because:
4097 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004098 // constructors from different classes.
4099 // - The lazy declaration of the other implicit constructors is so as to not
4100 // waste space and performance on classes that are not meant to be
4101 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004102 // have inheriting constructors.
4103 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004104}
4105
Richard Smith7756afa2012-06-10 05:43:50 +00004106/// Is the special member function which would be selected to perform the
4107/// specified operation on the specified class type a constexpr constructor?
4108static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4109 Sema::CXXSpecialMember CSM,
4110 bool ConstArg) {
4111 Sema::SpecialMemberOverloadResult *SMOR =
4112 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4113 false, false, false, false);
4114 if (!SMOR || !SMOR->getMethod())
4115 // A constructor we wouldn't select can't be "involved in initializing"
4116 // anything.
4117 return true;
4118 return SMOR->getMethod()->isConstexpr();
4119}
4120
4121/// Determine whether the specified special member function would be constexpr
4122/// if it were implicitly defined.
4123static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4124 Sema::CXXSpecialMember CSM,
4125 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004126 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004127 return false;
4128
4129 // C++11 [dcl.constexpr]p4:
4130 // In the definition of a constexpr constructor [...]
4131 switch (CSM) {
4132 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004133 // Since default constructor lookup is essentially trivial (and cannot
4134 // involve, for instance, template instantiation), we compute whether a
4135 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4136 //
4137 // This is important for performance; we need to know whether the default
4138 // constructor is constexpr to determine whether the type is a literal type.
4139 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4140
Richard Smith7756afa2012-06-10 05:43:50 +00004141 case Sema::CXXCopyConstructor:
4142 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004143 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004144 break;
4145
4146 case Sema::CXXCopyAssignment:
4147 case Sema::CXXMoveAssignment:
4148 case Sema::CXXDestructor:
4149 case Sema::CXXInvalid:
4150 return false;
4151 }
4152
4153 // -- if the class is a non-empty union, or for each non-empty anonymous
4154 // union member of a non-union class, exactly one non-static data member
4155 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004156 //
4157 // If we squint, this is guaranteed, since exactly one non-static data member
4158 // will be initialized (if the constructor isn't deleted), we just don't know
4159 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004160 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004161 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004162
4163 // -- the class shall not have any virtual base classes;
4164 if (ClassDecl->getNumVBases())
4165 return false;
4166
4167 // -- every constructor involved in initializing [...] base class
4168 // sub-objects shall be a constexpr constructor;
4169 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4170 BEnd = ClassDecl->bases_end();
4171 B != BEnd; ++B) {
4172 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4173 if (!BaseType) continue;
4174
4175 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4176 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4177 return false;
4178 }
4179
4180 // -- every constructor involved in initializing non-static data members
4181 // [...] shall be a constexpr constructor;
4182 // -- every non-static data member and base class sub-object shall be
4183 // initialized
4184 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4185 FEnd = ClassDecl->field_end();
4186 F != FEnd; ++F) {
4187 if (F->isInvalidDecl())
4188 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004189 if (const RecordType *RecordTy =
4190 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004191 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4192 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4193 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004194 }
4195 }
4196
4197 // All OK, it's constexpr!
4198 return true;
4199}
4200
Richard Smithb9d0b762012-07-27 04:22:15 +00004201static Sema::ImplicitExceptionSpecification
4202computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4203 switch (S.getSpecialMember(MD)) {
4204 case Sema::CXXDefaultConstructor:
4205 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4206 case Sema::CXXCopyConstructor:
4207 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4208 case Sema::CXXCopyAssignment:
4209 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4210 case Sema::CXXMoveConstructor:
4211 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4212 case Sema::CXXMoveAssignment:
4213 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4214 case Sema::CXXDestructor:
4215 return S.ComputeDefaultedDtorExceptionSpec(MD);
4216 case Sema::CXXInvalid:
4217 break;
4218 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004219 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4220 "only special members have implicit exception specs");
4221 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004222}
4223
Richard Smithdd25e802012-07-30 23:48:14 +00004224static void
4225updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4226 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4227 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4228 ExceptSpec.getEPI(EPI);
4229 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
Richard Smith07b0fdc2013-03-18 21:12:30 +00004230 S.Context.getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004231 FD->setType(QualType(NewFPT, 0));
4232}
4233
Richard Smithb9d0b762012-07-27 04:22:15 +00004234void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4235 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4236 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4237 return;
4238
Richard Smithdd25e802012-07-30 23:48:14 +00004239 // Evaluate the exception specification.
4240 ImplicitExceptionSpecification ExceptSpec =
4241 computeImplicitExceptionSpec(*this, Loc, MD);
4242
4243 // Update the type of the special member to use it.
4244 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4245
4246 // A user-provided destructor can be defined outside the class. When that
4247 // happens, be sure to update the exception specification on both
4248 // declarations.
4249 const FunctionProtoType *CanonicalFPT =
4250 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4251 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4252 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4253 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004254}
4255
Richard Smith3003e1d2012-05-15 04:39:51 +00004256void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4257 CXXRecordDecl *RD = MD->getParent();
4258 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004259
Richard Smith3003e1d2012-05-15 04:39:51 +00004260 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4261 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004262
4263 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004264 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004265 bool First = MD == MD->getCanonicalDecl();
4266
4267 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004268
4269 // C++11 [dcl.fct.def.default]p1:
4270 // A function that is explicitly defaulted shall
4271 // -- be a special member function (checked elsewhere),
4272 // -- have the same type (except for ref-qualifiers, and except that a
4273 // copy operation can take a non-const reference) as an implicit
4274 // declaration, and
4275 // -- not have default arguments.
4276 unsigned ExpectedParams = 1;
4277 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4278 ExpectedParams = 0;
4279 if (MD->getNumParams() != ExpectedParams) {
4280 // This also checks for default arguments: a copy or move constructor with a
4281 // default argument is classified as a default constructor, and assignment
4282 // operations and destructors can't have default arguments.
4283 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4284 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004285 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004286 } else if (MD->isVariadic()) {
4287 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4288 << CSM << MD->getSourceRange();
4289 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004290 }
4291
Richard Smith3003e1d2012-05-15 04:39:51 +00004292 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004293
Richard Smith7756afa2012-06-10 05:43:50 +00004294 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004295 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004296 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004297 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004298 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004299
Richard Smith3003e1d2012-05-15 04:39:51 +00004300 QualType ReturnType = Context.VoidTy;
4301 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4302 // Check for return type matching.
4303 ReturnType = Type->getResultType();
4304 QualType ExpectedReturnType =
4305 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4306 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4307 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4308 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4309 HadError = true;
4310 }
4311
4312 // A defaulted special member cannot have cv-qualifiers.
4313 if (Type->getTypeQuals()) {
4314 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4315 << (CSM == CXXMoveAssignment);
4316 HadError = true;
4317 }
4318 }
4319
4320 // Check for parameter type matching.
4321 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004322 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004323 if (ExpectedParams && ArgType->isReferenceType()) {
4324 // Argument must be reference to possibly-const T.
4325 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004326 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004327
4328 if (ReferentType.isVolatileQualified()) {
4329 Diag(MD->getLocation(),
4330 diag::err_defaulted_special_member_volatile_param) << CSM;
4331 HadError = true;
4332 }
4333
Richard Smith7756afa2012-06-10 05:43:50 +00004334 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004335 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4336 Diag(MD->getLocation(),
4337 diag::err_defaulted_special_member_copy_const_param)
4338 << (CSM == CXXCopyAssignment);
4339 // FIXME: Explain why this special member can't be const.
4340 } else {
4341 Diag(MD->getLocation(),
4342 diag::err_defaulted_special_member_move_const_param)
4343 << (CSM == CXXMoveAssignment);
4344 }
4345 HadError = true;
4346 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004347 } else if (ExpectedParams) {
4348 // A copy assignment operator can take its argument by value, but a
4349 // defaulted one cannot.
4350 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004351 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004352 HadError = true;
4353 }
Sean Huntbe631222011-05-17 20:44:43 +00004354
Richard Smith61802452011-12-22 02:22:31 +00004355 // C++11 [dcl.fct.def.default]p2:
4356 // An explicitly-defaulted function may be declared constexpr only if it
4357 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004358 // Do not apply this rule to members of class templates, since core issue 1358
4359 // makes such functions always instantiate to constexpr functions. For
4360 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004361 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4362 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004363 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4364 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4365 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004366 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004367 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004368 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004369
Richard Smith61802452011-12-22 02:22:31 +00004370 // and may have an explicit exception-specification only if it is compatible
4371 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004372 if (Type->hasExceptionSpec()) {
4373 // Delay the check if this is the first declaration of the special member,
4374 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004375 if (First) {
4376 // If the exception specification needs to be instantiated, do so now,
4377 // before we clobber it with an EST_Unevaluated specification below.
4378 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4379 InstantiateExceptionSpec(MD->getLocStart(), MD);
4380 Type = MD->getType()->getAs<FunctionProtoType>();
4381 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004382 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004383 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004384 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4385 }
Richard Smith61802452011-12-22 02:22:31 +00004386
4387 // If a function is explicitly defaulted on its first declaration,
4388 if (First) {
4389 // -- it is implicitly considered to be constexpr if the implicit
4390 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004391 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004392
Richard Smith3003e1d2012-05-15 04:39:51 +00004393 // -- it is implicitly considered to have the same exception-specification
4394 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004395 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4396 EPI.ExceptionSpecType = EST_Unevaluated;
4397 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004398 MD->setType(Context.getFunctionType(ReturnType,
4399 ArrayRef<QualType>(&ArgType,
4400 ExpectedParams),
4401 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004402 }
4403
Richard Smith3003e1d2012-05-15 04:39:51 +00004404 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004405 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004406 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004407 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004408 // C++11 [dcl.fct.def.default]p4:
4409 // [For a] user-provided explicitly-defaulted function [...] if such a
4410 // function is implicitly defined as deleted, the program is ill-formed.
4411 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4412 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004413 }
4414 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004415
Richard Smith3003e1d2012-05-15 04:39:51 +00004416 if (HadError)
4417 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004418}
4419
Richard Smith1d28caf2012-12-11 01:14:52 +00004420/// Check whether the exception specification provided for an
4421/// explicitly-defaulted special member matches the exception specification
4422/// that would have been generated for an implicit special member, per
4423/// C++11 [dcl.fct.def.default]p2.
4424void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4425 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4426 // Compute the implicit exception specification.
4427 FunctionProtoType::ExtProtoInfo EPI;
4428 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4429 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Jordan Rosebea522f2013-03-08 21:51:21 +00004430 Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004431
4432 // Ensure that it matches.
4433 CheckEquivalentExceptionSpec(
4434 PDiag(diag::err_incorrect_defaulted_exception_spec)
4435 << getSpecialMember(MD), PDiag(),
4436 ImplicitType, SourceLocation(),
4437 SpecifiedType, MD->getLocation());
4438}
4439
4440void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4441 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4442 I != N; ++I)
4443 CheckExplicitlyDefaultedMemberExceptionSpec(
4444 DelayedDefaultedMemberExceptionSpecs[I].first,
4445 DelayedDefaultedMemberExceptionSpecs[I].second);
4446
4447 DelayedDefaultedMemberExceptionSpecs.clear();
4448}
4449
Richard Smith7d5088a2012-02-18 02:02:13 +00004450namespace {
4451struct SpecialMemberDeletionInfo {
4452 Sema &S;
4453 CXXMethodDecl *MD;
4454 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004455 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004456
4457 // Properties of the special member, computed for convenience.
4458 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4459 SourceLocation Loc;
4460
4461 bool AllFieldsAreConst;
4462
4463 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004464 Sema::CXXSpecialMember CSM, bool Diagnose)
4465 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004466 IsConstructor(false), IsAssignment(false), IsMove(false),
4467 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4468 AllFieldsAreConst(true) {
4469 switch (CSM) {
4470 case Sema::CXXDefaultConstructor:
4471 case Sema::CXXCopyConstructor:
4472 IsConstructor = true;
4473 break;
4474 case Sema::CXXMoveConstructor:
4475 IsConstructor = true;
4476 IsMove = true;
4477 break;
4478 case Sema::CXXCopyAssignment:
4479 IsAssignment = true;
4480 break;
4481 case Sema::CXXMoveAssignment:
4482 IsAssignment = true;
4483 IsMove = true;
4484 break;
4485 case Sema::CXXDestructor:
4486 break;
4487 case Sema::CXXInvalid:
4488 llvm_unreachable("invalid special member kind");
4489 }
4490
4491 if (MD->getNumParams()) {
4492 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4493 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4494 }
4495 }
4496
4497 bool inUnion() const { return MD->getParent()->isUnion(); }
4498
4499 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004500 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4501 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004502 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004503 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4504 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4505 Quals = 0;
4506 return S.LookupSpecialMember(Class, CSM,
4507 ConstArg || (Quals & Qualifiers::Const),
4508 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004509 MD->getRefQualifier() == RQ_RValue,
4510 TQ & Qualifiers::Const,
4511 TQ & Qualifiers::Volatile);
4512 }
4513
Richard Smith6c4c36c2012-03-30 20:53:28 +00004514 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004515
Richard Smith6c4c36c2012-03-30 20:53:28 +00004516 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004517 bool shouldDeleteForField(FieldDecl *FD);
4518 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004519
Richard Smith517bb842012-07-18 03:51:16 +00004520 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4521 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004522 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4523 Sema::SpecialMemberOverloadResult *SMOR,
4524 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004525
4526 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004527};
4528}
4529
John McCall12d8d802012-04-09 20:53:23 +00004530/// Is the given special member inaccessible when used on the given
4531/// sub-object.
4532bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4533 CXXMethodDecl *target) {
4534 /// If we're operating on a base class, the object type is the
4535 /// type of this special member.
4536 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004537 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004538 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4539 objectTy = S.Context.getTypeDeclType(MD->getParent());
4540 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4541
4542 // If we're operating on a field, the object type is the type of the field.
4543 } else {
4544 objectTy = S.Context.getTypeDeclType(target->getParent());
4545 }
4546
4547 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4548}
4549
Richard Smith6c4c36c2012-03-30 20:53:28 +00004550/// Check whether we should delete a special member due to the implicit
4551/// definition containing a call to a special member of a subobject.
4552bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4553 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4554 bool IsDtorCallInCtor) {
4555 CXXMethodDecl *Decl = SMOR->getMethod();
4556 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4557
4558 int DiagKind = -1;
4559
4560 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4561 DiagKind = !Decl ? 0 : 1;
4562 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4563 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004564 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004565 DiagKind = 3;
4566 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4567 !Decl->isTrivial()) {
4568 // A member of a union must have a trivial corresponding special member.
4569 // As a weird special case, a destructor call from a union's constructor
4570 // must be accessible and non-deleted, but need not be trivial. Such a
4571 // destructor is never actually called, but is semantically checked as
4572 // if it were.
4573 DiagKind = 4;
4574 }
4575
4576 if (DiagKind == -1)
4577 return false;
4578
4579 if (Diagnose) {
4580 if (Field) {
4581 S.Diag(Field->getLocation(),
4582 diag::note_deleted_special_member_class_subobject)
4583 << CSM << MD->getParent() << /*IsField*/true
4584 << Field << DiagKind << IsDtorCallInCtor;
4585 } else {
4586 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4587 S.Diag(Base->getLocStart(),
4588 diag::note_deleted_special_member_class_subobject)
4589 << CSM << MD->getParent() << /*IsField*/false
4590 << Base->getType() << DiagKind << IsDtorCallInCtor;
4591 }
4592
4593 if (DiagKind == 1)
4594 S.NoteDeletedFunction(Decl);
4595 // FIXME: Explain inaccessibility if DiagKind == 3.
4596 }
4597
4598 return true;
4599}
4600
Richard Smith9a561d52012-02-26 09:11:52 +00004601/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004602/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004603bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004604 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004605 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004606
4607 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004608 // -- any direct or virtual base class, or non-static data member with no
4609 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004610 // either M has no default constructor or overload resolution as applied
4611 // to M's default constructor results in an ambiguity or in a function
4612 // that is deleted or inaccessible
4613 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4614 // -- a direct or virtual base class B that cannot be copied/moved because
4615 // overload resolution, as applied to B's corresponding special member,
4616 // results in an ambiguity or a function that is deleted or inaccessible
4617 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004618 // C++11 [class.dtor]p5:
4619 // -- any direct or virtual base class [...] has a type with a destructor
4620 // that is deleted or inaccessible
4621 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004622 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004623 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004624 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004625
Richard Smith6c4c36c2012-03-30 20:53:28 +00004626 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4627 // -- any direct or virtual base class or non-static data member has a
4628 // type with a destructor that is deleted or inaccessible
4629 if (IsConstructor) {
4630 Sema::SpecialMemberOverloadResult *SMOR =
4631 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4632 false, false, false, false, false);
4633 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4634 return true;
4635 }
4636
Richard Smith9a561d52012-02-26 09:11:52 +00004637 return false;
4638}
4639
4640/// Check whether we should delete a special member function due to the class
4641/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004642bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004643 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004644 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004645}
4646
4647/// Check whether we should delete a special member function due to the class
4648/// having a particular non-static data member.
4649bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4650 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4651 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4652
4653 if (CSM == Sema::CXXDefaultConstructor) {
4654 // For a default constructor, all references must be initialized in-class
4655 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004656 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4657 if (Diagnose)
4658 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4659 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004660 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004661 }
Richard Smith79363f52012-02-27 06:07:25 +00004662 // C++11 [class.ctor]p5: any non-variant non-static data member of
4663 // const-qualified type (or array thereof) with no
4664 // brace-or-equal-initializer does not have a user-provided default
4665 // constructor.
4666 if (!inUnion() && FieldType.isConstQualified() &&
4667 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004668 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4669 if (Diagnose)
4670 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004671 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004672 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004673 }
4674
4675 if (inUnion() && !FieldType.isConstQualified())
4676 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004677 } else if (CSM == Sema::CXXCopyConstructor) {
4678 // For a copy constructor, data members must not be of rvalue reference
4679 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004680 if (FieldType->isRValueReferenceType()) {
4681 if (Diagnose)
4682 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4683 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004684 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004685 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004686 } else if (IsAssignment) {
4687 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004688 if (FieldType->isReferenceType()) {
4689 if (Diagnose)
4690 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4691 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004692 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004693 }
4694 if (!FieldRecord && FieldType.isConstQualified()) {
4695 // C++11 [class.copy]p23:
4696 // -- a non-static data member of const non-class type (or array thereof)
4697 if (Diagnose)
4698 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004699 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004700 return true;
4701 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004702 }
4703
4704 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004705 // Some additional restrictions exist on the variant members.
4706 if (!inUnion() && FieldRecord->isUnion() &&
4707 FieldRecord->isAnonymousStructOrUnion()) {
4708 bool AllVariantFieldsAreConst = true;
4709
Richard Smithdf8dc862012-03-29 19:00:10 +00004710 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004711 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4712 UE = FieldRecord->field_end();
4713 UI != UE; ++UI) {
4714 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004715
4716 if (!UnionFieldType.isConstQualified())
4717 AllVariantFieldsAreConst = false;
4718
Richard Smith9a561d52012-02-26 09:11:52 +00004719 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4720 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004721 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4722 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004723 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004724 }
4725
4726 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004727 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004728 FieldRecord->field_begin() != FieldRecord->field_end()) {
4729 if (Diagnose)
4730 S.Diag(FieldRecord->getLocation(),
4731 diag::note_deleted_default_ctor_all_const)
4732 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004733 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004734 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004735
Richard Smithdf8dc862012-03-29 19:00:10 +00004736 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004737 // This is technically non-conformant, but sanity demands it.
4738 return false;
4739 }
4740
Richard Smith517bb842012-07-18 03:51:16 +00004741 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4742 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004743 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004744 }
4745
4746 return false;
4747}
4748
4749/// C++11 [class.ctor] p5:
4750/// A defaulted default constructor for a class X is defined as deleted if
4751/// X is a union and all of its variant members are of const-qualified type.
4752bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004753 // This is a silly definition, because it gives an empty union a deleted
4754 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004755 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4756 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4757 if (Diagnose)
4758 S.Diag(MD->getParent()->getLocation(),
4759 diag::note_deleted_default_ctor_all_const)
4760 << MD->getParent() << /*not anonymous union*/0;
4761 return true;
4762 }
4763 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004764}
4765
4766/// Determine whether a defaulted special member function should be defined as
4767/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4768/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004769bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4770 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004771 if (MD->isInvalidDecl())
4772 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004773 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004774 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004775 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004776 return false;
4777
Richard Smith7d5088a2012-02-18 02:02:13 +00004778 // C++11 [expr.lambda.prim]p19:
4779 // The closure type associated with a lambda-expression has a
4780 // deleted (8.4.3) default constructor and a deleted copy
4781 // assignment operator.
4782 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004783 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4784 if (Diagnose)
4785 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004786 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004787 }
4788
Richard Smith5bdaac52012-04-02 20:59:25 +00004789 // For an anonymous struct or union, the copy and assignment special members
4790 // will never be used, so skip the check. For an anonymous union declared at
4791 // namespace scope, the constructor and destructor are used.
4792 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4793 RD->isAnonymousStructOrUnion())
4794 return false;
4795
Richard Smith6c4c36c2012-03-30 20:53:28 +00004796 // C++11 [class.copy]p7, p18:
4797 // If the class definition declares a move constructor or move assignment
4798 // operator, an implicitly declared copy constructor or copy assignment
4799 // operator is defined as deleted.
4800 if (MD->isImplicit() &&
4801 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4802 CXXMethodDecl *UserDeclaredMove = 0;
4803
4804 // In Microsoft mode, a user-declared move only causes the deletion of the
4805 // corresponding copy operation, not both copy operations.
4806 if (RD->hasUserDeclaredMoveConstructor() &&
4807 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4808 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004809
4810 // Find any user-declared move constructor.
4811 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4812 E = RD->ctor_end(); I != E; ++I) {
4813 if (I->isMoveConstructor()) {
4814 UserDeclaredMove = *I;
4815 break;
4816 }
4817 }
Richard Smith1c931be2012-04-02 18:40:40 +00004818 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004819 } else if (RD->hasUserDeclaredMoveAssignment() &&
4820 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4821 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004822
4823 // Find any user-declared move assignment operator.
4824 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4825 E = RD->method_end(); I != E; ++I) {
4826 if (I->isMoveAssignmentOperator()) {
4827 UserDeclaredMove = *I;
4828 break;
4829 }
4830 }
Richard Smith1c931be2012-04-02 18:40:40 +00004831 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004832 }
4833
4834 if (UserDeclaredMove) {
4835 Diag(UserDeclaredMove->getLocation(),
4836 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004837 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004838 << UserDeclaredMove->isMoveAssignmentOperator();
4839 return true;
4840 }
4841 }
Sean Hunte16da072011-10-10 06:18:57 +00004842
Richard Smith5bdaac52012-04-02 20:59:25 +00004843 // Do access control from the special member function
4844 ContextRAII MethodContext(*this, MD);
4845
Richard Smith9a561d52012-02-26 09:11:52 +00004846 // C++11 [class.dtor]p5:
4847 // -- for a virtual destructor, lookup of the non-array deallocation function
4848 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004849 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004850 FunctionDecl *OperatorDelete = 0;
4851 DeclarationName Name =
4852 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4853 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004854 OperatorDelete, false)) {
4855 if (Diagnose)
4856 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004857 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004858 }
Richard Smith9a561d52012-02-26 09:11:52 +00004859 }
4860
Richard Smith6c4c36c2012-03-30 20:53:28 +00004861 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004862
Sean Huntcdee3fe2011-05-11 22:34:38 +00004863 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004864 BE = RD->bases_end(); BI != BE; ++BI)
4865 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004866 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004867 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004868
4869 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004870 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004871 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004872 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004873
4874 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004875 FE = RD->field_end(); FI != FE; ++FI)
4876 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004877 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004878 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004879
Richard Smith7d5088a2012-02-18 02:02:13 +00004880 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004881 return true;
4882
4883 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004884}
4885
Richard Smithac713512012-12-08 02:53:02 +00004886/// Perform lookup for a special member of the specified kind, and determine
4887/// whether it is trivial. If the triviality can be determined without the
4888/// lookup, skip it. This is intended for use when determining whether a
4889/// special member of a containing object is trivial, and thus does not ever
4890/// perform overload resolution for default constructors.
4891///
4892/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4893/// member that was most likely to be intended to be trivial, if any.
4894static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4895 Sema::CXXSpecialMember CSM, unsigned Quals,
4896 CXXMethodDecl **Selected) {
4897 if (Selected)
4898 *Selected = 0;
4899
4900 switch (CSM) {
4901 case Sema::CXXInvalid:
4902 llvm_unreachable("not a special member");
4903
4904 case Sema::CXXDefaultConstructor:
4905 // C++11 [class.ctor]p5:
4906 // A default constructor is trivial if:
4907 // - all the [direct subobjects] have trivial default constructors
4908 //
4909 // Note, no overload resolution is performed in this case.
4910 if (RD->hasTrivialDefaultConstructor())
4911 return true;
4912
4913 if (Selected) {
4914 // If there's a default constructor which could have been trivial, dig it
4915 // out. Otherwise, if there's any user-provided default constructor, point
4916 // to that as an example of why there's not a trivial one.
4917 CXXConstructorDecl *DefCtor = 0;
4918 if (RD->needsImplicitDefaultConstructor())
4919 S.DeclareImplicitDefaultConstructor(RD);
4920 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4921 CE = RD->ctor_end(); CI != CE; ++CI) {
4922 if (!CI->isDefaultConstructor())
4923 continue;
4924 DefCtor = *CI;
4925 if (!DefCtor->isUserProvided())
4926 break;
4927 }
4928
4929 *Selected = DefCtor;
4930 }
4931
4932 return false;
4933
4934 case Sema::CXXDestructor:
4935 // C++11 [class.dtor]p5:
4936 // A destructor is trivial if:
4937 // - all the direct [subobjects] have trivial destructors
4938 if (RD->hasTrivialDestructor())
4939 return true;
4940
4941 if (Selected) {
4942 if (RD->needsImplicitDestructor())
4943 S.DeclareImplicitDestructor(RD);
4944 *Selected = RD->getDestructor();
4945 }
4946
4947 return false;
4948
4949 case Sema::CXXCopyConstructor:
4950 // C++11 [class.copy]p12:
4951 // A copy constructor is trivial if:
4952 // - the constructor selected to copy each direct [subobject] is trivial
4953 if (RD->hasTrivialCopyConstructor()) {
4954 if (Quals == Qualifiers::Const)
4955 // We must either select the trivial copy constructor or reach an
4956 // ambiguity; no need to actually perform overload resolution.
4957 return true;
4958 } else if (!Selected) {
4959 return false;
4960 }
4961 // In C++98, we are not supposed to perform overload resolution here, but we
4962 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4963 // cases like B as having a non-trivial copy constructor:
4964 // struct A { template<typename T> A(T&); };
4965 // struct B { mutable A a; };
4966 goto NeedOverloadResolution;
4967
4968 case Sema::CXXCopyAssignment:
4969 // C++11 [class.copy]p25:
4970 // A copy assignment operator is trivial if:
4971 // - the assignment operator selected to copy each direct [subobject] is
4972 // trivial
4973 if (RD->hasTrivialCopyAssignment()) {
4974 if (Quals == Qualifiers::Const)
4975 return true;
4976 } else if (!Selected) {
4977 return false;
4978 }
4979 // In C++98, we are not supposed to perform overload resolution here, but we
4980 // treat that as a language defect.
4981 goto NeedOverloadResolution;
4982
4983 case Sema::CXXMoveConstructor:
4984 case Sema::CXXMoveAssignment:
4985 NeedOverloadResolution:
4986 Sema::SpecialMemberOverloadResult *SMOR =
4987 S.LookupSpecialMember(RD, CSM,
4988 Quals & Qualifiers::Const,
4989 Quals & Qualifiers::Volatile,
4990 /*RValueThis*/false, /*ConstThis*/false,
4991 /*VolatileThis*/false);
4992
4993 // The standard doesn't describe how to behave if the lookup is ambiguous.
4994 // We treat it as not making the member non-trivial, just like the standard
4995 // mandates for the default constructor. This should rarely matter, because
4996 // the member will also be deleted.
4997 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4998 return true;
4999
5000 if (!SMOR->getMethod()) {
5001 assert(SMOR->getKind() ==
5002 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5003 return false;
5004 }
5005
5006 // We deliberately don't check if we found a deleted special member. We're
5007 // not supposed to!
5008 if (Selected)
5009 *Selected = SMOR->getMethod();
5010 return SMOR->getMethod()->isTrivial();
5011 }
5012
5013 llvm_unreachable("unknown special method kind");
5014}
5015
Benjamin Kramera574c892013-02-15 12:30:38 +00005016static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005017 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5018 CI != CE; ++CI)
5019 if (!CI->isImplicit())
5020 return *CI;
5021
5022 // Look for constructor templates.
5023 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5024 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5025 if (CXXConstructorDecl *CD =
5026 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5027 return CD;
5028 }
5029
5030 return 0;
5031}
5032
5033/// The kind of subobject we are checking for triviality. The values of this
5034/// enumeration are used in diagnostics.
5035enum TrivialSubobjectKind {
5036 /// The subobject is a base class.
5037 TSK_BaseClass,
5038 /// The subobject is a non-static data member.
5039 TSK_Field,
5040 /// The object is actually the complete object.
5041 TSK_CompleteObject
5042};
5043
5044/// Check whether the special member selected for a given type would be trivial.
5045static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5046 QualType SubType,
5047 Sema::CXXSpecialMember CSM,
5048 TrivialSubobjectKind Kind,
5049 bool Diagnose) {
5050 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5051 if (!SubRD)
5052 return true;
5053
5054 CXXMethodDecl *Selected;
5055 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5056 Diagnose ? &Selected : 0))
5057 return true;
5058
5059 if (Diagnose) {
5060 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5061 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5062 << Kind << SubType.getUnqualifiedType();
5063 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5064 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5065 } else if (!Selected)
5066 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5067 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5068 else if (Selected->isUserProvided()) {
5069 if (Kind == TSK_CompleteObject)
5070 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5071 << Kind << SubType.getUnqualifiedType() << CSM;
5072 else {
5073 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5074 << Kind << SubType.getUnqualifiedType() << CSM;
5075 S.Diag(Selected->getLocation(), diag::note_declared_at);
5076 }
5077 } else {
5078 if (Kind != TSK_CompleteObject)
5079 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5080 << Kind << SubType.getUnqualifiedType() << CSM;
5081
5082 // Explain why the defaulted or deleted special member isn't trivial.
5083 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5084 }
5085 }
5086
5087 return false;
5088}
5089
5090/// Check whether the members of a class type allow a special member to be
5091/// trivial.
5092static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5093 Sema::CXXSpecialMember CSM,
5094 bool ConstArg, bool Diagnose) {
5095 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5096 FE = RD->field_end(); FI != FE; ++FI) {
5097 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5098 continue;
5099
5100 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5101
5102 // Pretend anonymous struct or union members are members of this class.
5103 if (FI->isAnonymousStructOrUnion()) {
5104 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5105 CSM, ConstArg, Diagnose))
5106 return false;
5107 continue;
5108 }
5109
5110 // C++11 [class.ctor]p5:
5111 // A default constructor is trivial if [...]
5112 // -- no non-static data member of its class has a
5113 // brace-or-equal-initializer
5114 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5115 if (Diagnose)
5116 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5117 return false;
5118 }
5119
5120 // Objective C ARC 4.3.5:
5121 // [...] nontrivally ownership-qualified types are [...] not trivially
5122 // default constructible, copy constructible, move constructible, copy
5123 // assignable, move assignable, or destructible [...]
5124 if (S.getLangOpts().ObjCAutoRefCount &&
5125 FieldType.hasNonTrivialObjCLifetime()) {
5126 if (Diagnose)
5127 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5128 << RD << FieldType.getObjCLifetime();
5129 return false;
5130 }
5131
5132 if (ConstArg && !FI->isMutable())
5133 FieldType.addConst();
5134 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5135 TSK_Field, Diagnose))
5136 return false;
5137 }
5138
5139 return true;
5140}
5141
5142/// Diagnose why the specified class does not have a trivial special member of
5143/// the given kind.
5144void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5145 QualType Ty = Context.getRecordType(RD);
5146 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5147 Ty.addConst();
5148
5149 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5150 TSK_CompleteObject, /*Diagnose*/true);
5151}
5152
5153/// Determine whether a defaulted or deleted special member function is trivial,
5154/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5155/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5156bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5157 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005158 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5159
5160 CXXRecordDecl *RD = MD->getParent();
5161
5162 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005163
5164 // C++11 [class.copy]p12, p25:
5165 // A [special member] is trivial if its declared parameter type is the same
5166 // as if it had been implicitly declared [...]
5167 switch (CSM) {
5168 case CXXDefaultConstructor:
5169 case CXXDestructor:
5170 // Trivial default constructors and destructors cannot have parameters.
5171 break;
5172
5173 case CXXCopyConstructor:
5174 case CXXCopyAssignment: {
5175 // Trivial copy operations always have const, non-volatile parameter types.
5176 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005177 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005178 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5179 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5180 if (Diagnose)
5181 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5182 << Param0->getSourceRange() << Param0->getType()
5183 << Context.getLValueReferenceType(
5184 Context.getRecordType(RD).withConst());
5185 return false;
5186 }
5187 break;
5188 }
5189
5190 case CXXMoveConstructor:
5191 case CXXMoveAssignment: {
5192 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005193 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005194 const RValueReferenceType *RT =
5195 Param0->getType()->getAs<RValueReferenceType>();
5196 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5197 if (Diagnose)
5198 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5199 << Param0->getSourceRange() << Param0->getType()
5200 << Context.getRValueReferenceType(Context.getRecordType(RD));
5201 return false;
5202 }
5203 break;
5204 }
5205
5206 case CXXInvalid:
5207 llvm_unreachable("not a special member");
5208 }
5209
5210 // FIXME: We require that the parameter-declaration-clause is equivalent to
5211 // that of an implicit declaration, not just that the declared parameter type
5212 // matches, in order to prevent absuridities like a function simultaneously
5213 // being a trivial copy constructor and a non-trivial default constructor.
5214 // This issue has not yet been assigned a core issue number.
5215 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5216 if (Diagnose)
5217 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5218 diag::note_nontrivial_default_arg)
5219 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5220 return false;
5221 }
5222 if (MD->isVariadic()) {
5223 if (Diagnose)
5224 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5225 return false;
5226 }
5227
5228 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5229 // A copy/move [constructor or assignment operator] is trivial if
5230 // -- the [member] selected to copy/move each direct base class subobject
5231 // is trivial
5232 //
5233 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5234 // A [default constructor or destructor] is trivial if
5235 // -- all the direct base classes have trivial [default constructors or
5236 // destructors]
5237 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5238 BE = RD->bases_end(); BI != BE; ++BI)
5239 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5240 ConstArg ? BI->getType().withConst()
5241 : BI->getType(),
5242 CSM, TSK_BaseClass, Diagnose))
5243 return false;
5244
5245 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5246 // A copy/move [constructor or assignment operator] for a class X is
5247 // trivial if
5248 // -- for each non-static data member of X that is of class type (or array
5249 // thereof), the constructor selected to copy/move that member is
5250 // trivial
5251 //
5252 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5253 // A [default constructor or destructor] is trivial if
5254 // -- for all of the non-static data members of its class that are of class
5255 // type (or array thereof), each such class has a trivial [default
5256 // constructor or destructor]
5257 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5258 return false;
5259
5260 // C++11 [class.dtor]p5:
5261 // A destructor is trivial if [...]
5262 // -- the destructor is not virtual
5263 if (CSM == CXXDestructor && MD->isVirtual()) {
5264 if (Diagnose)
5265 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5266 return false;
5267 }
5268
5269 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5270 // A [special member] for class X is trivial if [...]
5271 // -- class X has no virtual functions and no virtual base classes
5272 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5273 if (!Diagnose)
5274 return false;
5275
5276 if (RD->getNumVBases()) {
5277 // Check for virtual bases. We already know that the corresponding
5278 // member in all bases is trivial, so vbases must all be direct.
5279 CXXBaseSpecifier &BS = *RD->vbases_begin();
5280 assert(BS.isVirtual());
5281 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5282 return false;
5283 }
5284
5285 // Must have a virtual method.
5286 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5287 ME = RD->method_end(); MI != ME; ++MI) {
5288 if (MI->isVirtual()) {
5289 SourceLocation MLoc = MI->getLocStart();
5290 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5291 return false;
5292 }
5293 }
5294
5295 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5296 }
5297
5298 // Looks like it's trivial!
5299 return true;
5300}
5301
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005302/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005303namespace {
5304 struct FindHiddenVirtualMethodData {
5305 Sema *S;
5306 CXXMethodDecl *Method;
5307 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005308 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005309 };
5310}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005311
David Blaikie5f750682012-10-19 00:53:08 +00005312/// \brief Check whether any most overriden method from MD in Methods
5313static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5314 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5315 if (MD->size_overridden_methods() == 0)
5316 return Methods.count(MD->getCanonicalDecl());
5317 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5318 E = MD->end_overridden_methods();
5319 I != E; ++I)
5320 if (CheckMostOverridenMethods(*I, Methods))
5321 return true;
5322 return false;
5323}
5324
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005325/// \brief Member lookup function that determines whether a given C++
5326/// method overloads virtual methods in a base class without overriding any,
5327/// to be used with CXXRecordDecl::lookupInBases().
5328static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5329 CXXBasePath &Path,
5330 void *UserData) {
5331 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5332
5333 FindHiddenVirtualMethodData &Data
5334 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5335
5336 DeclarationName Name = Data.Method->getDeclName();
5337 assert(Name.getNameKind() == DeclarationName::Identifier);
5338
5339 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005340 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005341 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005342 !Path.Decls.empty();
5343 Path.Decls = Path.Decls.slice(1)) {
5344 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005345 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005346 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005347 foundSameNameMethod = true;
5348 // Interested only in hidden virtual methods.
5349 if (!MD->isVirtual())
5350 continue;
5351 // If the method we are checking overrides a method from its base
5352 // don't warn about the other overloaded methods.
5353 if (!Data.S->IsOverload(Data.Method, MD, false))
5354 return true;
5355 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005356 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005357 overloadedMethods.push_back(MD);
5358 }
5359 }
5360
5361 if (foundSameNameMethod)
5362 Data.OverloadedMethods.append(overloadedMethods.begin(),
5363 overloadedMethods.end());
5364 return foundSameNameMethod;
5365}
5366
David Blaikie5f750682012-10-19 00:53:08 +00005367/// \brief Add the most overriden methods from MD to Methods
5368static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5369 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5370 if (MD->size_overridden_methods() == 0)
5371 Methods.insert(MD->getCanonicalDecl());
5372 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5373 E = MD->end_overridden_methods();
5374 I != E; ++I)
5375 AddMostOverridenMethods(*I, Methods);
5376}
5377
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005378/// \brief See if a method overloads virtual methods in a base class without
5379/// overriding any.
5380void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5381 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005382 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005383 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005384 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005385 return;
5386
5387 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5388 /*bool RecordPaths=*/false,
5389 /*bool DetectVirtual=*/false);
5390 FindHiddenVirtualMethodData Data;
5391 Data.Method = MD;
5392 Data.S = this;
5393
5394 // Keep the base methods that were overriden or introduced in the subclass
5395 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005396 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5397 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5398 NamedDecl *ND = *I;
5399 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005400 ND = shad->getTargetDecl();
5401 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5402 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005403 }
5404
5405 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5406 !Data.OverloadedMethods.empty()) {
5407 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5408 << MD << (Data.OverloadedMethods.size() > 1);
5409
5410 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5411 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005412 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005413 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005414 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5415 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005416 }
5417 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005418}
5419
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005420void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005421 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005422 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005423 SourceLocation RBrac,
5424 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005425 if (!TagDecl)
5426 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005427
Douglas Gregor42af25f2009-05-11 19:58:34 +00005428 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005429
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005430 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5431 if (l->getKind() != AttributeList::AT_Visibility)
5432 continue;
5433 l->setInvalid();
5434 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5435 l->getName();
5436 }
5437
David Blaikie77b6de02011-09-22 02:58:26 +00005438 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005439 // strict aliasing violation!
5440 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005441 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005442
Douglas Gregor23c94db2010-07-02 17:43:08 +00005443 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005444 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005445}
5446
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005447/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5448/// special functions, such as the default constructor, copy
5449/// constructor, or destructor, to the given C++ class (C++
5450/// [special]p1). This routine can only be executed just before the
5451/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005452void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005453 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005454 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005455
Richard Smithbc2a35d2012-12-08 08:32:28 +00005456 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005457 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005458
Richard Smithbc2a35d2012-12-08 08:32:28 +00005459 // If the properties or semantics of the copy constructor couldn't be
5460 // determined while the class was being declared, force a declaration
5461 // of it now.
5462 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5463 DeclareImplicitCopyConstructor(ClassDecl);
5464 }
5465
Richard Smith80ad52f2013-01-02 11:42:31 +00005466 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005467 ++ASTContext::NumImplicitMoveConstructors;
5468
Richard Smithbc2a35d2012-12-08 08:32:28 +00005469 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5470 DeclareImplicitMoveConstructor(ClassDecl);
5471 }
5472
Douglas Gregora376d102010-07-02 21:50:04 +00005473 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5474 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005475
5476 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005477 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005478 // it shows up in the right place in the vtable and that we diagnose
5479 // problems with the implicit exception specification.
5480 if (ClassDecl->isDynamicClass() ||
5481 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005482 DeclareImplicitCopyAssignment(ClassDecl);
5483 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005484
Richard Smith80ad52f2013-01-02 11:42:31 +00005485 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005486 ++ASTContext::NumImplicitMoveAssignmentOperators;
5487
5488 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005489 if (ClassDecl->isDynamicClass() ||
5490 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005491 DeclareImplicitMoveAssignment(ClassDecl);
5492 }
5493
Douglas Gregor4923aa22010-07-02 20:37:36 +00005494 if (!ClassDecl->hasUserDeclaredDestructor()) {
5495 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005496
5497 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005498 // have to declare the destructor immediately. This ensures that, e.g., it
5499 // shows up in the right place in the vtable and that we diagnose problems
5500 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005501 if (ClassDecl->isDynamicClass() ||
5502 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005503 DeclareImplicitDestructor(ClassDecl);
5504 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005505}
5506
Francois Pichet8387e2a2011-04-22 22:18:13 +00005507void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5508 if (!D)
5509 return;
5510
5511 int NumParamList = D->getNumTemplateParameterLists();
5512 for (int i = 0; i < NumParamList; i++) {
5513 TemplateParameterList* Params = D->getTemplateParameterList(i);
5514 for (TemplateParameterList::iterator Param = Params->begin(),
5515 ParamEnd = Params->end();
5516 Param != ParamEnd; ++Param) {
5517 NamedDecl *Named = cast<NamedDecl>(*Param);
5518 if (Named->getDeclName()) {
5519 S->AddDecl(Named);
5520 IdResolver.AddDecl(Named);
5521 }
5522 }
5523 }
5524}
5525
John McCalld226f652010-08-21 09:40:31 +00005526void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005527 if (!D)
5528 return;
5529
5530 TemplateParameterList *Params = 0;
5531 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5532 Params = Template->getTemplateParameters();
5533 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5534 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5535 Params = PartialSpec->getTemplateParameters();
5536 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005537 return;
5538
Douglas Gregor6569d682009-05-27 23:11:45 +00005539 for (TemplateParameterList::iterator Param = Params->begin(),
5540 ParamEnd = Params->end();
5541 Param != ParamEnd; ++Param) {
5542 NamedDecl *Named = cast<NamedDecl>(*Param);
5543 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005544 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005545 IdResolver.AddDecl(Named);
5546 }
5547 }
5548}
5549
John McCalld226f652010-08-21 09:40:31 +00005550void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005551 if (!RecordD) return;
5552 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005553 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005554 PushDeclContext(S, Record);
5555}
5556
John McCalld226f652010-08-21 09:40:31 +00005557void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005558 if (!RecordD) return;
5559 PopDeclContext();
5560}
5561
Douglas Gregor72b505b2008-12-16 21:30:33 +00005562/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5563/// parsing a top-level (non-nested) C++ class, and we are now
5564/// parsing those parts of the given Method declaration that could
5565/// not be parsed earlier (C++ [class.mem]p2), such as default
5566/// arguments. This action should enter the scope of the given
5567/// Method declaration as if we had just parsed the qualified method
5568/// name. However, it should not bring the parameters into scope;
5569/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005570void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005571}
5572
5573/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5574/// C++ method declaration. We're (re-)introducing the given
5575/// function parameter into scope for use in parsing later parts of
5576/// the method declaration. For example, we could see an
5577/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005578void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005579 if (!ParamD)
5580 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005581
John McCalld226f652010-08-21 09:40:31 +00005582 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005583
5584 // If this parameter has an unparsed default argument, clear it out
5585 // to make way for the parsed default argument.
5586 if (Param->hasUnparsedDefaultArg())
5587 Param->setDefaultArg(0);
5588
John McCalld226f652010-08-21 09:40:31 +00005589 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005590 if (Param->getDeclName())
5591 IdResolver.AddDecl(Param);
5592}
5593
5594/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5595/// processing the delayed method declaration for Method. The method
5596/// declaration is now considered finished. There may be a separate
5597/// ActOnStartOfFunctionDef action later (not necessarily
5598/// immediately!) for this method, if it was also defined inside the
5599/// class body.
John McCalld226f652010-08-21 09:40:31 +00005600void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005601 if (!MethodD)
5602 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005603
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005604 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005605
John McCalld226f652010-08-21 09:40:31 +00005606 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005607
5608 // Now that we have our default arguments, check the constructor
5609 // again. It could produce additional diagnostics or affect whether
5610 // the class has implicitly-declared destructors, among other
5611 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005612 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5613 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005614
5615 // Check the default arguments, which we may have added.
5616 if (!Method->isInvalidDecl())
5617 CheckCXXDefaultArguments(Method);
5618}
5619
Douglas Gregor42a552f2008-11-05 20:51:48 +00005620/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005621/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005622/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005623/// emit diagnostics and set the invalid bit to true. In any case, the type
5624/// will be updated to reflect a well-formed type for the constructor and
5625/// returned.
5626QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005627 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005628 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005629
5630 // C++ [class.ctor]p3:
5631 // A constructor shall not be virtual (10.3) or static (9.4). A
5632 // constructor can be invoked for a const, volatile or const
5633 // volatile object. A constructor shall not be declared const,
5634 // volatile, or const volatile (9.3.2).
5635 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005636 if (!D.isInvalidType())
5637 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5638 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5639 << SourceRange(D.getIdentifierLoc());
5640 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005641 }
John McCalld931b082010-08-26 03:08:43 +00005642 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005643 if (!D.isInvalidType())
5644 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5645 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5646 << SourceRange(D.getIdentifierLoc());
5647 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005648 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005649 }
Mike Stump1eb44332009-09-09 15:08:12 +00005650
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005651 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005652 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005653 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005654 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5655 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005656 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005657 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5658 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005659 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005660 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5661 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005662 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005663 }
Mike Stump1eb44332009-09-09 15:08:12 +00005664
Douglas Gregorc938c162011-01-26 05:01:58 +00005665 // C++0x [class.ctor]p4:
5666 // A constructor shall not be declared with a ref-qualifier.
5667 if (FTI.hasRefQualifier()) {
5668 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5669 << FTI.RefQualifierIsLValueRef
5670 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5671 D.setInvalidType();
5672 }
5673
Douglas Gregor42a552f2008-11-05 20:51:48 +00005674 // Rebuild the function type "R" without any type qualifiers (in
5675 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005676 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005677 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005678 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5679 return R;
5680
5681 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5682 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005683 EPI.RefQualifier = RQ_None;
5684
Richard Smith07b0fdc2013-03-18 21:12:30 +00005685 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005686}
5687
Douglas Gregor72b505b2008-12-16 21:30:33 +00005688/// CheckConstructor - Checks a fully-formed constructor for
5689/// well-formedness, issuing any diagnostics required. Returns true if
5690/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005691void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005692 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005693 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5694 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005695 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005696
5697 // C++ [class.copy]p3:
5698 // A declaration of a constructor for a class X is ill-formed if
5699 // its first parameter is of type (optionally cv-qualified) X and
5700 // either there are no other parameters or else all other
5701 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005702 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005703 ((Constructor->getNumParams() == 1) ||
5704 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005705 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5706 Constructor->getTemplateSpecializationKind()
5707 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005708 QualType ParamType = Constructor->getParamDecl(0)->getType();
5709 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5710 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005711 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005712 const char *ConstRef
5713 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5714 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005715 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005716 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005717
5718 // FIXME: Rather that making the constructor invalid, we should endeavor
5719 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005720 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005721 }
5722 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005723}
5724
John McCall15442822010-08-04 01:04:25 +00005725/// CheckDestructor - Checks a fully-formed destructor definition for
5726/// well-formedness, issuing any diagnostics required. Returns true
5727/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005728bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005729 CXXRecordDecl *RD = Destructor->getParent();
5730
5731 if (Destructor->isVirtual()) {
5732 SourceLocation Loc;
5733
5734 if (!Destructor->isImplicit())
5735 Loc = Destructor->getLocation();
5736 else
5737 Loc = RD->getLocation();
5738
5739 // If we have a virtual destructor, look up the deallocation function
5740 FunctionDecl *OperatorDelete = 0;
5741 DeclarationName Name =
5742 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005743 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005744 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005745
Eli Friedman5f2987c2012-02-02 03:46:19 +00005746 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005747
5748 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005749 }
Anders Carlsson37909802009-11-30 21:24:50 +00005750
5751 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005752}
5753
Mike Stump1eb44332009-09-09 15:08:12 +00005754static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005755FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5756 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5757 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005758 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005759}
5760
Douglas Gregor42a552f2008-11-05 20:51:48 +00005761/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5762/// the well-formednes of the destructor declarator @p D with type @p
5763/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005764/// emit diagnostics and set the declarator to invalid. Even if this happens,
5765/// will be updated to reflect a well-formed type for the destructor and
5766/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005767QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005768 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005769 // C++ [class.dtor]p1:
5770 // [...] A typedef-name that names a class is a class-name
5771 // (7.1.3); however, a typedef-name that names a class shall not
5772 // be used as the identifier in the declarator for a destructor
5773 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005774 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005775 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005776 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005777 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005778 else if (const TemplateSpecializationType *TST =
5779 DeclaratorType->getAs<TemplateSpecializationType>())
5780 if (TST->isTypeAlias())
5781 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5782 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005783
5784 // C++ [class.dtor]p2:
5785 // A destructor is used to destroy objects of its class type. A
5786 // destructor takes no parameters, and no return type can be
5787 // specified for it (not even void). The address of a destructor
5788 // shall not be taken. A destructor shall not be static. A
5789 // destructor can be invoked for a const, volatile or const
5790 // volatile object. A destructor shall not be declared const,
5791 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005792 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005793 if (!D.isInvalidType())
5794 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5795 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005796 << SourceRange(D.getIdentifierLoc())
5797 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5798
John McCalld931b082010-08-26 03:08:43 +00005799 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005800 }
Chris Lattner65401802009-04-25 08:28:21 +00005801 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005802 // Destructors don't have return types, but the parser will
5803 // happily parse something like:
5804 //
5805 // class X {
5806 // float ~X();
5807 // };
5808 //
5809 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005810 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5811 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5812 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005813 }
Mike Stump1eb44332009-09-09 15:08:12 +00005814
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005815 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005816 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005817 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005818 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5819 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005820 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005821 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5822 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005823 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005824 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5825 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005826 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005827 }
5828
Douglas Gregorc938c162011-01-26 05:01:58 +00005829 // C++0x [class.dtor]p2:
5830 // A destructor shall not be declared with a ref-qualifier.
5831 if (FTI.hasRefQualifier()) {
5832 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5833 << FTI.RefQualifierIsLValueRef
5834 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5835 D.setInvalidType();
5836 }
5837
Douglas Gregor42a552f2008-11-05 20:51:48 +00005838 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005839 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005840 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5841
5842 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005843 FTI.freeArgs();
5844 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005845 }
5846
Mike Stump1eb44332009-09-09 15:08:12 +00005847 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005848 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005849 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005850 D.setInvalidType();
5851 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005852
5853 // Rebuild the function type "R" without any type qualifiers or
5854 // parameters (in case any of the errors above fired) and with
5855 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005856 // types.
John McCalle23cf432010-12-14 08:05:40 +00005857 if (!D.isInvalidType())
5858 return R;
5859
Douglas Gregord92ec472010-07-01 05:10:53 +00005860 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005861 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5862 EPI.Variadic = false;
5863 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005864 EPI.RefQualifier = RQ_None;
Jordan Rosebea522f2013-03-08 21:51:21 +00005865 return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005866}
5867
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005868/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5869/// well-formednes of the conversion function declarator @p D with
5870/// type @p R. If there are any errors in the declarator, this routine
5871/// will emit diagnostics and return true. Otherwise, it will return
5872/// false. Either way, the type @p R will be updated to reflect a
5873/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005874void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005875 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005876 // C++ [class.conv.fct]p1:
5877 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005878 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005879 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005880 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005881 if (!D.isInvalidType())
5882 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5883 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5884 << SourceRange(D.getIdentifierLoc());
5885 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005886 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005887 }
John McCalla3f81372010-04-13 00:04:31 +00005888
5889 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5890
Chris Lattner6e475012009-04-25 08:35:12 +00005891 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005892 // Conversion functions don't have return types, but the parser will
5893 // happily parse something like:
5894 //
5895 // class X {
5896 // float operator bool();
5897 // };
5898 //
5899 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005900 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5901 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5902 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005903 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005904 }
5905
John McCalla3f81372010-04-13 00:04:31 +00005906 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5907
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005908 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005909 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005910 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5911
5912 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005913 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005914 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005915 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005916 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005917 D.setInvalidType();
5918 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005919
John McCalla3f81372010-04-13 00:04:31 +00005920 // Diagnose "&operator bool()" and other such nonsense. This
5921 // is actually a gcc extension which we don't support.
5922 if (Proto->getResultType() != ConvType) {
5923 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5924 << Proto->getResultType();
5925 D.setInvalidType();
5926 ConvType = Proto->getResultType();
5927 }
5928
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005929 // C++ [class.conv.fct]p4:
5930 // The conversion-type-id shall not represent a function type nor
5931 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005932 if (ConvType->isArrayType()) {
5933 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5934 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005935 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005936 } else if (ConvType->isFunctionType()) {
5937 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5938 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005939 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005940 }
5941
5942 // Rebuild the function type "R" without any parameters (in case any
5943 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005944 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005945 if (D.isInvalidType())
Jordan Rosebea522f2013-03-08 21:51:21 +00005946 R = Context.getFunctionType(ConvType, ArrayRef<QualType>(),
5947 Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005948
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005949 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005950 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005951 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005952 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005953 diag::warn_cxx98_compat_explicit_conversion_functions :
5954 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005955 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005956}
5957
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005958/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5959/// the declaration of the given C++ conversion function. This routine
5960/// is responsible for recording the conversion function in the C++
5961/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005962Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005963 assert(Conversion && "Expected to receive a conversion function declaration");
5964
Douglas Gregor9d350972008-12-12 08:25:50 +00005965 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005966
5967 // Make sure we aren't redeclaring the conversion function.
5968 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005969
5970 // C++ [class.conv.fct]p1:
5971 // [...] A conversion function is never used to convert a
5972 // (possibly cv-qualified) object to the (possibly cv-qualified)
5973 // same object type (or a reference to it), to a (possibly
5974 // cv-qualified) base class of that type (or a reference to it),
5975 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005976 // FIXME: Suppress this warning if the conversion function ends up being a
5977 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005978 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005979 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005980 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005981 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005982 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5983 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005984 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005985 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005986 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5987 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005988 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005989 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005990 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005991 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005992 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005993 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005994 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005995 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005996 }
5997
Douglas Gregore80622f2010-09-29 04:25:11 +00005998 if (FunctionTemplateDecl *ConversionTemplate
5999 = Conversion->getDescribedFunctionTemplate())
6000 return ConversionTemplate;
6001
John McCalld226f652010-08-21 09:40:31 +00006002 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006003}
6004
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006005//===----------------------------------------------------------------------===//
6006// Namespace Handling
6007//===----------------------------------------------------------------------===//
6008
Richard Smithd1a55a62012-10-04 22:13:39 +00006009/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6010/// reopened.
6011static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6012 SourceLocation Loc,
6013 IdentifierInfo *II, bool *IsInline,
6014 NamespaceDecl *PrevNS) {
6015 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006016
Richard Smithc969e6a2012-10-05 01:46:25 +00006017 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6018 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6019 // inline namespaces, with the intention of bringing names into namespace std.
6020 //
6021 // We support this just well enough to get that case working; this is not
6022 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006023 if (*IsInline && II && II->getName().startswith("__atomic") &&
6024 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006025 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006026 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6027 NS = NS->getPreviousDecl())
6028 NS->setInline(*IsInline);
6029 // Patch up the lookup table for the containing namespace. This isn't really
6030 // correct, but it's good enough for this particular case.
6031 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6032 E = PrevNS->decls_end(); I != E; ++I)
6033 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6034 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6035 return;
6036 }
6037
6038 if (PrevNS->isInline())
6039 // The user probably just forgot the 'inline', so suggest that it
6040 // be added back.
6041 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6042 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6043 else
6044 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6045 << IsInline;
6046
6047 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6048 *IsInline = PrevNS->isInline();
6049}
John McCallea318642010-08-26 09:15:37 +00006050
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006051/// ActOnStartNamespaceDef - This is called at the start of a namespace
6052/// definition.
John McCalld226f652010-08-21 09:40:31 +00006053Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006054 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006055 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006056 SourceLocation IdentLoc,
6057 IdentifierInfo *II,
6058 SourceLocation LBrace,
6059 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006060 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6061 // For anonymous namespace, take the location of the left brace.
6062 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006063 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006064 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006065 bool IsStd = false;
6066 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006067 Scope *DeclRegionScope = NamespcScope->getParent();
6068
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006069 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006070 if (II) {
6071 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006072 // The identifier in an original-namespace-definition shall not
6073 // have been previously defined in the declarative region in
6074 // which the original-namespace-definition appears. The
6075 // identifier in an original-namespace-definition is the name of
6076 // the namespace. Subsequently in that declarative region, it is
6077 // treated as an original-namespace-name.
6078 //
6079 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006080 // look through using directives, just look for any ordinary names.
6081
6082 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006083 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6084 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006085 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006086 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6087 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6088 ++I) {
6089 if ((*I)->getIdentifierNamespace() & IDNS) {
6090 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006091 break;
6092 }
6093 }
6094
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006095 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6096
6097 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006098 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006099 if (IsInline != PrevNS->isInline())
6100 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6101 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006102 } else if (PrevDecl) {
6103 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006104 Diag(Loc, diag::err_redefinition_different_kind)
6105 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006106 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006107 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006108 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006109 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006110 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006111 // This is the first "real" definition of the namespace "std", so update
6112 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006113 PrevNS = getStdNamespace();
6114 IsStd = true;
6115 AddToKnown = !IsInline;
6116 } else {
6117 // We've seen this namespace for the first time.
6118 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006119 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006120 } else {
John McCall9aeed322009-10-01 00:25:31 +00006121 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006122
6123 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006124 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006125 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006126 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006127 } else {
6128 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006129 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006130 }
6131
Richard Smithd1a55a62012-10-04 22:13:39 +00006132 if (PrevNS && IsInline != PrevNS->isInline())
6133 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6134 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006135 }
6136
6137 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6138 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006139 if (IsInvalid)
6140 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006141
6142 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006143
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006144 // FIXME: Should we be merging attributes?
6145 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006146 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006147
6148 if (IsStd)
6149 StdNamespace = Namespc;
6150 if (AddToKnown)
6151 KnownNamespaces[Namespc] = false;
6152
6153 if (II) {
6154 PushOnScopeChains(Namespc, DeclRegionScope);
6155 } else {
6156 // Link the anonymous namespace into its parent.
6157 DeclContext *Parent = CurContext->getRedeclContext();
6158 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6159 TU->setAnonymousNamespace(Namespc);
6160 } else {
6161 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006162 }
John McCall9aeed322009-10-01 00:25:31 +00006163
Douglas Gregora4181472010-03-24 00:46:35 +00006164 CurContext->addDecl(Namespc);
6165
John McCall9aeed322009-10-01 00:25:31 +00006166 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6167 // behaves as if it were replaced by
6168 // namespace unique { /* empty body */ }
6169 // using namespace unique;
6170 // namespace unique { namespace-body }
6171 // where all occurrences of 'unique' in a translation unit are
6172 // replaced by the same identifier and this identifier differs
6173 // from all other identifiers in the entire program.
6174
6175 // We just create the namespace with an empty name and then add an
6176 // implicit using declaration, just like the standard suggests.
6177 //
6178 // CodeGen enforces the "universally unique" aspect by giving all
6179 // declarations semantically contained within an anonymous
6180 // namespace internal linkage.
6181
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006182 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006183 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006184 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006185 /* 'using' */ LBrace,
6186 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006187 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006188 /* identifier */ SourceLocation(),
6189 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006190 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006191 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006192 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006193 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006194 }
6195
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006196 ActOnDocumentableDecl(Namespc);
6197
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006198 // Although we could have an invalid decl (i.e. the namespace name is a
6199 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006200 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6201 // for the namespace has the declarations that showed up in that particular
6202 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006203 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006204 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006205}
6206
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006207/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6208/// is a namespace alias, returns the namespace it points to.
6209static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6210 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6211 return AD->getNamespace();
6212 return dyn_cast_or_null<NamespaceDecl>(D);
6213}
6214
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006215/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6216/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006217void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006218 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6219 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006220 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006221 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006222 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006223 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006224}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006225
John McCall384aff82010-08-25 07:42:41 +00006226CXXRecordDecl *Sema::getStdBadAlloc() const {
6227 return cast_or_null<CXXRecordDecl>(
6228 StdBadAlloc.get(Context.getExternalSource()));
6229}
6230
6231NamespaceDecl *Sema::getStdNamespace() const {
6232 return cast_or_null<NamespaceDecl>(
6233 StdNamespace.get(Context.getExternalSource()));
6234}
6235
Douglas Gregor66992202010-06-29 17:53:46 +00006236/// \brief Retrieve the special "std" namespace, which may require us to
6237/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006238NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006239 if (!StdNamespace) {
6240 // The "std" namespace has not yet been defined, so build one implicitly.
6241 StdNamespace = NamespaceDecl::Create(Context,
6242 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006243 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006244 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006245 &PP.getIdentifierTable().get("std"),
6246 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006247 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006248 }
6249
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006250 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006251}
6252
Sebastian Redl395e04d2012-01-17 22:49:33 +00006253bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006254 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006255 "Looking for std::initializer_list outside of C++.");
6256
6257 // We're looking for implicit instantiations of
6258 // template <typename E> class std::initializer_list.
6259
6260 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6261 return false;
6262
Sebastian Redl84760e32012-01-17 22:49:58 +00006263 ClassTemplateDecl *Template = 0;
6264 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006265
Sebastian Redl84760e32012-01-17 22:49:58 +00006266 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006267
Sebastian Redl84760e32012-01-17 22:49:58 +00006268 ClassTemplateSpecializationDecl *Specialization =
6269 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6270 if (!Specialization)
6271 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006272
Sebastian Redl84760e32012-01-17 22:49:58 +00006273 Template = Specialization->getSpecializedTemplate();
6274 Arguments = Specialization->getTemplateArgs().data();
6275 } else if (const TemplateSpecializationType *TST =
6276 Ty->getAs<TemplateSpecializationType>()) {
6277 Template = dyn_cast_or_null<ClassTemplateDecl>(
6278 TST->getTemplateName().getAsTemplateDecl());
6279 Arguments = TST->getArgs();
6280 }
6281 if (!Template)
6282 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006283
6284 if (!StdInitializerList) {
6285 // Haven't recognized std::initializer_list yet, maybe this is it.
6286 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6287 if (TemplateClass->getIdentifier() !=
6288 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006289 !getStdNamespace()->InEnclosingNamespaceSetOf(
6290 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006291 return false;
6292 // This is a template called std::initializer_list, but is it the right
6293 // template?
6294 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006295 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006296 return false;
6297 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6298 return false;
6299
6300 // It's the right template.
6301 StdInitializerList = Template;
6302 }
6303
6304 if (Template != StdInitializerList)
6305 return false;
6306
6307 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006308 if (Element)
6309 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006310 return true;
6311}
6312
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006313static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6314 NamespaceDecl *Std = S.getStdNamespace();
6315 if (!Std) {
6316 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6317 return 0;
6318 }
6319
6320 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6321 Loc, Sema::LookupOrdinaryName);
6322 if (!S.LookupQualifiedName(Result, Std)) {
6323 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6324 return 0;
6325 }
6326 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6327 if (!Template) {
6328 Result.suppressDiagnostics();
6329 // We found something weird. Complain about the first thing we found.
6330 NamedDecl *Found = *Result.begin();
6331 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6332 return 0;
6333 }
6334
6335 // We found some template called std::initializer_list. Now verify that it's
6336 // correct.
6337 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006338 if (Params->getMinRequiredArguments() != 1 ||
6339 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006340 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6341 return 0;
6342 }
6343
6344 return Template;
6345}
6346
6347QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6348 if (!StdInitializerList) {
6349 StdInitializerList = LookupStdInitializerList(*this, Loc);
6350 if (!StdInitializerList)
6351 return QualType();
6352 }
6353
6354 TemplateArgumentListInfo Args(Loc, Loc);
6355 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6356 Context.getTrivialTypeSourceInfo(Element,
6357 Loc)));
6358 return Context.getCanonicalType(
6359 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6360}
6361
Sebastian Redl98d36062012-01-17 22:50:14 +00006362bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6363 // C++ [dcl.init.list]p2:
6364 // A constructor is an initializer-list constructor if its first parameter
6365 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6366 // std::initializer_list<E> for some type E, and either there are no other
6367 // parameters or else all other parameters have default arguments.
6368 if (Ctor->getNumParams() < 1 ||
6369 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6370 return false;
6371
6372 QualType ArgType = Ctor->getParamDecl(0)->getType();
6373 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6374 ArgType = RT->getPointeeType().getUnqualifiedType();
6375
6376 return isStdInitializerList(ArgType, 0);
6377}
6378
Douglas Gregor9172aa62011-03-26 22:25:30 +00006379/// \brief Determine whether a using statement is in a context where it will be
6380/// apply in all contexts.
6381static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6382 switch (CurContext->getDeclKind()) {
6383 case Decl::TranslationUnit:
6384 return true;
6385 case Decl::LinkageSpec:
6386 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6387 default:
6388 return false;
6389 }
6390}
6391
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006392namespace {
6393
6394// Callback to only accept typo corrections that are namespaces.
6395class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6396 public:
6397 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6398 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6399 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6400 }
6401 return false;
6402 }
6403};
6404
6405}
6406
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006407static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6408 CXXScopeSpec &SS,
6409 SourceLocation IdentLoc,
6410 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006411 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006412 R.clear();
6413 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006414 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006415 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006416 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6417 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006418 if (DeclContext *DC = S.computeDeclContext(SS, false))
6419 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6420 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006421 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6422 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006423 else
6424 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6425 << Ident << CorrectedQuotedStr
6426 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006427
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006428 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6429 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006430
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006431 R.addDecl(Corrected.getCorrectionDecl());
6432 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006433 }
6434 return false;
6435}
6436
John McCalld226f652010-08-21 09:40:31 +00006437Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006438 SourceLocation UsingLoc,
6439 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006440 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006441 SourceLocation IdentLoc,
6442 IdentifierInfo *NamespcName,
6443 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006444 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6445 assert(NamespcName && "Invalid NamespcName.");
6446 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006447
6448 // This can only happen along a recovery path.
6449 while (S->getFlags() & Scope::TemplateParamScope)
6450 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006451 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006452
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006453 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006454 NestedNameSpecifier *Qualifier = 0;
6455 if (SS.isSet())
6456 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6457
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006458 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006459 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6460 LookupParsedName(R, S, &SS);
6461 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006462 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006463
Douglas Gregor66992202010-06-29 17:53:46 +00006464 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006465 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006466 // Allow "using namespace std;" or "using namespace ::std;" even if
6467 // "std" hasn't been defined yet, for GCC compatibility.
6468 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6469 NamespcName->isStr("std")) {
6470 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006471 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006472 R.resolveKind();
6473 }
6474 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006475 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006476 }
6477
John McCallf36e02d2009-10-09 21:13:30 +00006478 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006479 NamedDecl *Named = R.getFoundDecl();
6480 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6481 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006482 // C++ [namespace.udir]p1:
6483 // A using-directive specifies that the names in the nominated
6484 // namespace can be used in the scope in which the
6485 // using-directive appears after the using-directive. During
6486 // unqualified name lookup (3.4.1), the names appear as if they
6487 // were declared in the nearest enclosing namespace which
6488 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006489 // namespace. [Note: in this context, "contains" means "contains
6490 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006491
6492 // Find enclosing context containing both using-directive and
6493 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006494 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006495 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6496 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6497 CommonAncestor = CommonAncestor->getParent();
6498
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006499 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006500 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006501 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006502
Douglas Gregor9172aa62011-03-26 22:25:30 +00006503 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006504 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006505 Diag(IdentLoc, diag::warn_using_directive_in_header);
6506 }
6507
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006508 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006509 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006510 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006511 }
6512
Richard Smith6b3d3e52013-02-20 19:22:51 +00006513 if (UDir)
6514 ProcessDeclAttributeList(S, UDir, AttrList);
6515
John McCalld226f652010-08-21 09:40:31 +00006516 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006517}
6518
6519void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006520 // If the scope has an associated entity and the using directive is at
6521 // namespace or translation unit scope, add the UsingDirectiveDecl into
6522 // its lookup structure so qualified name lookup can find it.
6523 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6524 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006525 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006526 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006527 // Otherwise, it is at block sope. The using-directives will affect lookup
6528 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006529 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006530}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006531
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006532
John McCalld226f652010-08-21 09:40:31 +00006533Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006534 AccessSpecifier AS,
6535 bool HasUsingKeyword,
6536 SourceLocation UsingLoc,
6537 CXXScopeSpec &SS,
6538 UnqualifiedId &Name,
6539 AttributeList *AttrList,
6540 bool IsTypeName,
6541 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006542 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006543
Douglas Gregor12c118a2009-11-04 16:30:06 +00006544 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006545 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006546 case UnqualifiedId::IK_Identifier:
6547 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006548 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006549 case UnqualifiedId::IK_ConversionFunctionId:
6550 break;
6551
6552 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006553 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006554 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006555 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006556 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006557 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006558 diag::err_using_decl_constructor)
6559 << SS.getRange();
6560
Richard Smith80ad52f2013-01-02 11:42:31 +00006561 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006562
John McCalld226f652010-08-21 09:40:31 +00006563 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006564
6565 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006566 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006567 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006568 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006569
6570 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006571 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006572 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006573 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006574 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006575
6576 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6577 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006578 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006579 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006580
Richard Smith07b0fdc2013-03-18 21:12:30 +00006581 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006582 // TODO: store that the declaration was written without 'using' and
6583 // talk about access decls instead of using decls in the
6584 // diagnostics.
6585 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006586 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006587
6588 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006589 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006590 }
6591
Douglas Gregor56c04582010-12-16 00:46:58 +00006592 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6593 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6594 return 0;
6595
John McCall9488ea12009-11-17 05:59:44 +00006596 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006597 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006598 /* IsInstantiation */ false,
6599 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006600 if (UD)
6601 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006602
John McCalld226f652010-08-21 09:40:31 +00006603 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006604}
6605
Douglas Gregor09acc982010-07-07 23:08:52 +00006606/// \brief Determine whether a using declaration considers the given
6607/// declarations as "equivalent", e.g., if they are redeclarations of
6608/// the same entity or are both typedefs of the same type.
6609static bool
6610IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6611 bool &SuppressRedeclaration) {
6612 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6613 SuppressRedeclaration = false;
6614 return true;
6615 }
6616
Richard Smith162e1c12011-04-15 14:24:37 +00006617 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6618 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006619 SuppressRedeclaration = true;
6620 return Context.hasSameType(TD1->getUnderlyingType(),
6621 TD2->getUnderlyingType());
6622 }
6623
6624 return false;
6625}
6626
6627
John McCall9f54ad42009-12-10 09:41:52 +00006628/// Determines whether to create a using shadow decl for a particular
6629/// decl, given the set of decls existing prior to this using lookup.
6630bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6631 const LookupResult &Previous) {
6632 // Diagnose finding a decl which is not from a base class of the
6633 // current class. We do this now because there are cases where this
6634 // function will silently decide not to build a shadow decl, which
6635 // will pre-empt further diagnostics.
6636 //
6637 // We don't need to do this in C++0x because we do the check once on
6638 // the qualifier.
6639 //
6640 // FIXME: diagnose the following if we care enough:
6641 // struct A { int foo; };
6642 // struct B : A { using A::foo; };
6643 // template <class T> struct C : A {};
6644 // template <class T> struct D : C<T> { using B::foo; } // <---
6645 // This is invalid (during instantiation) in C++03 because B::foo
6646 // resolves to the using decl in B, which is not a base class of D<T>.
6647 // We can't diagnose it immediately because C<T> is an unknown
6648 // specialization. The UsingShadowDecl in D<T> then points directly
6649 // to A::foo, which will look well-formed when we instantiate.
6650 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006651 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006652 DeclContext *OrigDC = Orig->getDeclContext();
6653
6654 // Handle enums and anonymous structs.
6655 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6656 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6657 while (OrigRec->isAnonymousStructOrUnion())
6658 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6659
6660 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6661 if (OrigDC == CurContext) {
6662 Diag(Using->getLocation(),
6663 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006664 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006665 Diag(Orig->getLocation(), diag::note_using_decl_target);
6666 return true;
6667 }
6668
Douglas Gregordc355712011-02-25 00:36:19 +00006669 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006670 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006671 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006672 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006673 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006674 Diag(Orig->getLocation(), diag::note_using_decl_target);
6675 return true;
6676 }
6677 }
6678
6679 if (Previous.empty()) return false;
6680
6681 NamedDecl *Target = Orig;
6682 if (isa<UsingShadowDecl>(Target))
6683 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6684
John McCalld7533ec2009-12-11 02:33:26 +00006685 // If the target happens to be one of the previous declarations, we
6686 // don't have a conflict.
6687 //
6688 // FIXME: but we might be increasing its access, in which case we
6689 // should redeclare it.
6690 NamedDecl *NonTag = 0, *Tag = 0;
6691 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6692 I != E; ++I) {
6693 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006694 bool Result;
6695 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6696 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006697
6698 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6699 }
6700
John McCall9f54ad42009-12-10 09:41:52 +00006701 if (Target->isFunctionOrFunctionTemplate()) {
6702 FunctionDecl *FD;
6703 if (isa<FunctionTemplateDecl>(Target))
6704 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6705 else
6706 FD = cast<FunctionDecl>(Target);
6707
6708 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006709 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006710 case Ovl_Overload:
6711 return false;
6712
6713 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006714 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006715 break;
6716
6717 // We found a decl with the exact signature.
6718 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006719 // If we're in a record, we want to hide the target, so we
6720 // return true (without a diagnostic) to tell the caller not to
6721 // build a shadow decl.
6722 if (CurContext->isRecord())
6723 return true;
6724
6725 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006726 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006727 break;
6728 }
6729
6730 Diag(Target->getLocation(), diag::note_using_decl_target);
6731 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6732 return true;
6733 }
6734
6735 // Target is not a function.
6736
John McCall9f54ad42009-12-10 09:41:52 +00006737 if (isa<TagDecl>(Target)) {
6738 // No conflict between a tag and a non-tag.
6739 if (!Tag) return false;
6740
John McCall41ce66f2009-12-10 19:51:03 +00006741 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006742 Diag(Target->getLocation(), diag::note_using_decl_target);
6743 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6744 return true;
6745 }
6746
6747 // No conflict between a tag and a non-tag.
6748 if (!NonTag) return false;
6749
John McCall41ce66f2009-12-10 19:51:03 +00006750 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006751 Diag(Target->getLocation(), diag::note_using_decl_target);
6752 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6753 return true;
6754}
6755
John McCall9488ea12009-11-17 05:59:44 +00006756/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006757UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006758 UsingDecl *UD,
6759 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006760
6761 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006762 NamedDecl *Target = Orig;
6763 if (isa<UsingShadowDecl>(Target)) {
6764 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6765 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006766 }
6767
6768 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006769 = UsingShadowDecl::Create(Context, CurContext,
6770 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006771 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006772
6773 Shadow->setAccess(UD->getAccess());
6774 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6775 Shadow->setInvalidDecl();
6776
John McCall9488ea12009-11-17 05:59:44 +00006777 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006778 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006779 else
John McCall604e7f12009-12-08 07:46:18 +00006780 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006781
John McCall604e7f12009-12-08 07:46:18 +00006782
John McCall9f54ad42009-12-10 09:41:52 +00006783 return Shadow;
6784}
John McCall604e7f12009-12-08 07:46:18 +00006785
John McCall9f54ad42009-12-10 09:41:52 +00006786/// Hides a using shadow declaration. This is required by the current
6787/// using-decl implementation when a resolvable using declaration in a
6788/// class is followed by a declaration which would hide or override
6789/// one or more of the using decl's targets; for example:
6790///
6791/// struct Base { void foo(int); };
6792/// struct Derived : Base {
6793/// using Base::foo;
6794/// void foo(int);
6795/// };
6796///
6797/// The governing language is C++03 [namespace.udecl]p12:
6798///
6799/// When a using-declaration brings names from a base class into a
6800/// derived class scope, member functions in the derived class
6801/// override and/or hide member functions with the same name and
6802/// parameter types in a base class (rather than conflicting).
6803///
6804/// There are two ways to implement this:
6805/// (1) optimistically create shadow decls when they're not hidden
6806/// by existing declarations, or
6807/// (2) don't create any shadow decls (or at least don't make them
6808/// visible) until we've fully parsed/instantiated the class.
6809/// The problem with (1) is that we might have to retroactively remove
6810/// a shadow decl, which requires several O(n) operations because the
6811/// decl structures are (very reasonably) not designed for removal.
6812/// (2) avoids this but is very fiddly and phase-dependent.
6813void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006814 if (Shadow->getDeclName().getNameKind() ==
6815 DeclarationName::CXXConversionFunctionName)
6816 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6817
John McCall9f54ad42009-12-10 09:41:52 +00006818 // Remove it from the DeclContext...
6819 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006820
John McCall9f54ad42009-12-10 09:41:52 +00006821 // ...and the scope, if applicable...
6822 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006823 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006824 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006825 }
6826
John McCall9f54ad42009-12-10 09:41:52 +00006827 // ...and the using decl.
6828 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6829
6830 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006831 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006832}
6833
John McCall7ba107a2009-11-18 02:36:19 +00006834/// Builds a using declaration.
6835///
6836/// \param IsInstantiation - Whether this call arises from an
6837/// instantiation of an unresolved using declaration. We treat
6838/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006839NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6840 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006841 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006842 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006843 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006844 bool IsInstantiation,
6845 bool IsTypeName,
6846 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006847 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006848 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006849 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006850
Anders Carlsson550b14b2009-08-28 05:49:21 +00006851 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006852
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006853 if (SS.isEmpty()) {
6854 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006855 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006856 }
Mike Stump1eb44332009-09-09 15:08:12 +00006857
John McCall9f54ad42009-12-10 09:41:52 +00006858 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006859 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006860 ForRedeclaration);
6861 Previous.setHideTags(false);
6862 if (S) {
6863 LookupName(Previous, S);
6864
6865 // It is really dumb that we have to do this.
6866 LookupResult::Filter F = Previous.makeFilter();
6867 while (F.hasNext()) {
6868 NamedDecl *D = F.next();
6869 if (!isDeclInScope(D, CurContext, S))
6870 F.erase();
6871 }
6872 F.done();
6873 } else {
6874 assert(IsInstantiation && "no scope in non-instantiation");
6875 assert(CurContext->isRecord() && "scope not record in instantiation");
6876 LookupQualifiedName(Previous, CurContext);
6877 }
6878
John McCall9f54ad42009-12-10 09:41:52 +00006879 // Check for invalid redeclarations.
6880 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6881 return 0;
6882
6883 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006884 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6885 return 0;
6886
John McCallaf8e6ed2009-11-12 03:15:40 +00006887 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006888 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006889 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006890 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006891 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006892 // FIXME: not all declaration name kinds are legal here
6893 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6894 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006895 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006896 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006897 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006898 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6899 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006900 }
John McCalled976492009-12-04 22:46:56 +00006901 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006902 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6903 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006904 }
John McCalled976492009-12-04 22:46:56 +00006905 D->setAccess(AS);
6906 CurContext->addDecl(D);
6907
6908 if (!LookupContext) return D;
6909 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006910
John McCall77bb1aa2010-05-01 00:40:08 +00006911 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006912 UD->setInvalidDecl();
6913 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006914 }
6915
Richard Smithc5a89a12012-04-02 01:30:27 +00006916 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006917 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006918 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006919 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006920 return UD;
6921 }
6922
6923 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006924
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006925 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006926
John McCall604e7f12009-12-08 07:46:18 +00006927 // Unlike most lookups, we don't always want to hide tag
6928 // declarations: tag names are visible through the using declaration
6929 // even if hidden by ordinary names, *except* in a dependent context
6930 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006931 if (!IsInstantiation)
6932 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006933
John McCallb9abd8722012-04-07 03:04:20 +00006934 // For the purposes of this lookup, we have a base object type
6935 // equal to that of the current context.
6936 if (CurContext->isRecord()) {
6937 R.setBaseObjectType(
6938 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6939 }
6940
John McCalla24dc2e2009-11-17 02:14:36 +00006941 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006942
John McCallf36e02d2009-10-09 21:13:30 +00006943 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006944 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006945 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006946 UD->setInvalidDecl();
6947 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006948 }
6949
John McCalled976492009-12-04 22:46:56 +00006950 if (R.isAmbiguous()) {
6951 UD->setInvalidDecl();
6952 return UD;
6953 }
Mike Stump1eb44332009-09-09 15:08:12 +00006954
John McCall7ba107a2009-11-18 02:36:19 +00006955 if (IsTypeName) {
6956 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006957 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006958 Diag(IdentLoc, diag::err_using_typename_non_type);
6959 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6960 Diag((*I)->getUnderlyingDecl()->getLocation(),
6961 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006962 UD->setInvalidDecl();
6963 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006964 }
6965 } else {
6966 // If we asked for a non-typename and we got a type, error out,
6967 // but only if this is an instantiation of an unresolved using
6968 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006969 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006970 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6971 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006972 UD->setInvalidDecl();
6973 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006974 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006975 }
6976
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006977 // C++0x N2914 [namespace.udecl]p6:
6978 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006979 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006980 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6981 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006982 UD->setInvalidDecl();
6983 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006984 }
Mike Stump1eb44332009-09-09 15:08:12 +00006985
John McCall9f54ad42009-12-10 09:41:52 +00006986 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6987 if (!CheckUsingShadowDecl(UD, *I, Previous))
6988 BuildUsingShadowDecl(S, UD, *I);
6989 }
John McCall9488ea12009-11-17 05:59:44 +00006990
6991 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006992}
6993
Sebastian Redlf677ea32011-02-05 19:23:19 +00006994/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006995bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6996 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006997
Douglas Gregordc355712011-02-25 00:36:19 +00006998 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006999 assert(SourceType &&
7000 "Using decl naming constructor doesn't have type in scope spec.");
7001 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7002
7003 // Check whether the named type is a direct base class.
7004 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7005 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7006 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7007 BaseIt != BaseE; ++BaseIt) {
7008 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7009 if (CanonicalSourceType == BaseType)
7010 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007011 if (BaseIt->getType()->isDependentType())
7012 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007013 }
7014
7015 if (BaseIt == BaseE) {
7016 // Did not find SourceType in the bases.
7017 Diag(UD->getUsingLocation(),
7018 diag::err_using_decl_constructor_not_in_direct_base)
7019 << UD->getNameInfo().getSourceRange()
7020 << QualType(SourceType, 0) << TargetClass;
7021 return true;
7022 }
7023
Richard Smithc5a89a12012-04-02 01:30:27 +00007024 if (!CurContext->isDependentContext())
7025 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007026
7027 return false;
7028}
7029
John McCall9f54ad42009-12-10 09:41:52 +00007030/// Checks that the given using declaration is not an invalid
7031/// redeclaration. Note that this is checking only for the using decl
7032/// itself, not for any ill-formedness among the UsingShadowDecls.
7033bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7034 bool isTypeName,
7035 const CXXScopeSpec &SS,
7036 SourceLocation NameLoc,
7037 const LookupResult &Prev) {
7038 // C++03 [namespace.udecl]p8:
7039 // C++0x [namespace.udecl]p10:
7040 // A using-declaration is a declaration and can therefore be used
7041 // repeatedly where (and only where) multiple declarations are
7042 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007043 //
John McCall8a726212010-11-29 18:01:58 +00007044 // That's in non-member contexts.
7045 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007046 return false;
7047
7048 NestedNameSpecifier *Qual
7049 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7050
7051 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7052 NamedDecl *D = *I;
7053
7054 bool DTypename;
7055 NestedNameSpecifier *DQual;
7056 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7057 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007058 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007059 } else if (UnresolvedUsingValueDecl *UD
7060 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7061 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007062 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007063 } else if (UnresolvedUsingTypenameDecl *UD
7064 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7065 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007066 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007067 } else continue;
7068
7069 // using decls differ if one says 'typename' and the other doesn't.
7070 // FIXME: non-dependent using decls?
7071 if (isTypeName != DTypename) continue;
7072
7073 // using decls differ if they name different scopes (but note that
7074 // template instantiation can cause this check to trigger when it
7075 // didn't before instantiation).
7076 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7077 Context.getCanonicalNestedNameSpecifier(DQual))
7078 continue;
7079
7080 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007081 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007082 return true;
7083 }
7084
7085 return false;
7086}
7087
John McCall604e7f12009-12-08 07:46:18 +00007088
John McCalled976492009-12-04 22:46:56 +00007089/// Checks that the given nested-name qualifier used in a using decl
7090/// in the current context is appropriately related to the current
7091/// scope. If an error is found, diagnoses it and returns true.
7092bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7093 const CXXScopeSpec &SS,
7094 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007095 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007096
John McCall604e7f12009-12-08 07:46:18 +00007097 if (!CurContext->isRecord()) {
7098 // C++03 [namespace.udecl]p3:
7099 // C++0x [namespace.udecl]p8:
7100 // A using-declaration for a class member shall be a member-declaration.
7101
7102 // If we weren't able to compute a valid scope, it must be a
7103 // dependent class scope.
7104 if (!NamedContext || NamedContext->isRecord()) {
7105 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7106 << SS.getRange();
7107 return true;
7108 }
7109
7110 // Otherwise, everything is known to be fine.
7111 return false;
7112 }
7113
7114 // The current scope is a record.
7115
7116 // If the named context is dependent, we can't decide much.
7117 if (!NamedContext) {
7118 // FIXME: in C++0x, we can diagnose if we can prove that the
7119 // nested-name-specifier does not refer to a base class, which is
7120 // still possible in some cases.
7121
7122 // Otherwise we have to conservatively report that things might be
7123 // okay.
7124 return false;
7125 }
7126
7127 if (!NamedContext->isRecord()) {
7128 // Ideally this would point at the last name in the specifier,
7129 // but we don't have that level of source info.
7130 Diag(SS.getRange().getBegin(),
7131 diag::err_using_decl_nested_name_specifier_is_not_class)
7132 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7133 return true;
7134 }
7135
Douglas Gregor6fb07292010-12-21 07:41:49 +00007136 if (!NamedContext->isDependentContext() &&
7137 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7138 return true;
7139
Richard Smith80ad52f2013-01-02 11:42:31 +00007140 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007141 // C++0x [namespace.udecl]p3:
7142 // In a using-declaration used as a member-declaration, the
7143 // nested-name-specifier shall name a base class of the class
7144 // being defined.
7145
7146 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7147 cast<CXXRecordDecl>(NamedContext))) {
7148 if (CurContext == NamedContext) {
7149 Diag(NameLoc,
7150 diag::err_using_decl_nested_name_specifier_is_current_class)
7151 << SS.getRange();
7152 return true;
7153 }
7154
7155 Diag(SS.getRange().getBegin(),
7156 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7157 << (NestedNameSpecifier*) SS.getScopeRep()
7158 << cast<CXXRecordDecl>(CurContext)
7159 << SS.getRange();
7160 return true;
7161 }
7162
7163 return false;
7164 }
7165
7166 // C++03 [namespace.udecl]p4:
7167 // A using-declaration used as a member-declaration shall refer
7168 // to a member of a base class of the class being defined [etc.].
7169
7170 // Salient point: SS doesn't have to name a base class as long as
7171 // lookup only finds members from base classes. Therefore we can
7172 // diagnose here only if we can prove that that can't happen,
7173 // i.e. if the class hierarchies provably don't intersect.
7174
7175 // TODO: it would be nice if "definitely valid" results were cached
7176 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7177 // need to be repeated.
7178
7179 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007180 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007181
7182 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7183 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7184 Data->Bases.insert(Base);
7185 return true;
7186 }
7187
7188 bool hasDependentBases(const CXXRecordDecl *Class) {
7189 return !Class->forallBases(collect, this);
7190 }
7191
7192 /// Returns true if the base is dependent or is one of the
7193 /// accumulated base classes.
7194 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7195 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7196 return !Data->Bases.count(Base);
7197 }
7198
7199 bool mightShareBases(const CXXRecordDecl *Class) {
7200 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7201 }
7202 };
7203
7204 UserData Data;
7205
7206 // Returns false if we find a dependent base.
7207 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7208 return false;
7209
7210 // Returns false if the class has a dependent base or if it or one
7211 // of its bases is present in the base set of the current context.
7212 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7213 return false;
7214
7215 Diag(SS.getRange().getBegin(),
7216 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7217 << (NestedNameSpecifier*) SS.getScopeRep()
7218 << cast<CXXRecordDecl>(CurContext)
7219 << SS.getRange();
7220
7221 return true;
John McCalled976492009-12-04 22:46:56 +00007222}
7223
Richard Smith162e1c12011-04-15 14:24:37 +00007224Decl *Sema::ActOnAliasDeclaration(Scope *S,
7225 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007226 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007227 SourceLocation UsingLoc,
7228 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007229 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007230 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007231 // Skip up to the relevant declaration scope.
7232 while (S->getFlags() & Scope::TemplateParamScope)
7233 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007234 assert((S->getFlags() & Scope::DeclScope) &&
7235 "got alias-declaration outside of declaration scope");
7236
7237 if (Type.isInvalid())
7238 return 0;
7239
7240 bool Invalid = false;
7241 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7242 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007243 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007244
7245 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7246 return 0;
7247
7248 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007249 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007250 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007251 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7252 TInfo->getTypeLoc().getBeginLoc());
7253 }
Richard Smith162e1c12011-04-15 14:24:37 +00007254
7255 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7256 LookupName(Previous, S);
7257
7258 // Warn about shadowing the name of a template parameter.
7259 if (Previous.isSingleResult() &&
7260 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007261 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007262 Previous.clear();
7263 }
7264
7265 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7266 "name in alias declaration must be an identifier");
7267 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7268 Name.StartLocation,
7269 Name.Identifier, TInfo);
7270
7271 NewTD->setAccess(AS);
7272
7273 if (Invalid)
7274 NewTD->setInvalidDecl();
7275
Richard Smith6b3d3e52013-02-20 19:22:51 +00007276 ProcessDeclAttributeList(S, NewTD, AttrList);
7277
Richard Smith3e4c6c42011-05-05 21:57:07 +00007278 CheckTypedefForVariablyModifiedType(S, NewTD);
7279 Invalid |= NewTD->isInvalidDecl();
7280
Richard Smith162e1c12011-04-15 14:24:37 +00007281 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007282
7283 NamedDecl *NewND;
7284 if (TemplateParamLists.size()) {
7285 TypeAliasTemplateDecl *OldDecl = 0;
7286 TemplateParameterList *OldTemplateParams = 0;
7287
7288 if (TemplateParamLists.size() != 1) {
7289 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007290 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7291 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007292 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007293 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007294
7295 // Only consider previous declarations in the same scope.
7296 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7297 /*ExplicitInstantiationOrSpecialization*/false);
7298 if (!Previous.empty()) {
7299 Redeclaration = true;
7300
7301 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7302 if (!OldDecl && !Invalid) {
7303 Diag(UsingLoc, diag::err_redefinition_different_kind)
7304 << Name.Identifier;
7305
7306 NamedDecl *OldD = Previous.getRepresentativeDecl();
7307 if (OldD->getLocation().isValid())
7308 Diag(OldD->getLocation(), diag::note_previous_definition);
7309
7310 Invalid = true;
7311 }
7312
7313 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7314 if (TemplateParameterListsAreEqual(TemplateParams,
7315 OldDecl->getTemplateParameters(),
7316 /*Complain=*/true,
7317 TPL_TemplateMatch))
7318 OldTemplateParams = OldDecl->getTemplateParameters();
7319 else
7320 Invalid = true;
7321
7322 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7323 if (!Invalid &&
7324 !Context.hasSameType(OldTD->getUnderlyingType(),
7325 NewTD->getUnderlyingType())) {
7326 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7327 // but we can't reasonably accept it.
7328 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7329 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7330 if (OldTD->getLocation().isValid())
7331 Diag(OldTD->getLocation(), diag::note_previous_definition);
7332 Invalid = true;
7333 }
7334 }
7335 }
7336
7337 // Merge any previous default template arguments into our parameters,
7338 // and check the parameter list.
7339 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7340 TPC_TypeAliasTemplate))
7341 return 0;
7342
7343 TypeAliasTemplateDecl *NewDecl =
7344 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7345 Name.Identifier, TemplateParams,
7346 NewTD);
7347
7348 NewDecl->setAccess(AS);
7349
7350 if (Invalid)
7351 NewDecl->setInvalidDecl();
7352 else if (OldDecl)
7353 NewDecl->setPreviousDeclaration(OldDecl);
7354
7355 NewND = NewDecl;
7356 } else {
7357 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7358 NewND = NewTD;
7359 }
Richard Smith162e1c12011-04-15 14:24:37 +00007360
7361 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007362 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007363
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007364 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007365 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007366}
7367
John McCalld226f652010-08-21 09:40:31 +00007368Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007369 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007370 SourceLocation AliasLoc,
7371 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007372 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007373 SourceLocation IdentLoc,
7374 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007375
Anders Carlsson81c85c42009-03-28 23:53:49 +00007376 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007377 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7378 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007379
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007380 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007381 NamedDecl *PrevDecl
7382 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7383 ForRedeclaration);
7384 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7385 PrevDecl = 0;
7386
7387 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007388 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007389 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007390 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007391 // FIXME: At some point, we'll want to create the (redundant)
7392 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007393 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007394 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007395 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007396 }
Mike Stump1eb44332009-09-09 15:08:12 +00007397
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007398 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7399 diag::err_redefinition_different_kind;
7400 Diag(AliasLoc, DiagID) << Alias;
7401 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007402 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007403 }
7404
John McCalla24dc2e2009-11-17 02:14:36 +00007405 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007406 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007407
John McCallf36e02d2009-10-09 21:13:30 +00007408 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007409 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007410 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007411 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007412 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007413 }
Mike Stump1eb44332009-09-09 15:08:12 +00007414
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007415 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007416 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007417 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007418 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007419
John McCall3dbd3d52010-02-16 06:53:13 +00007420 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007421 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007422}
7423
Sean Hunt001cad92011-05-10 00:49:42 +00007424Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007425Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7426 CXXMethodDecl *MD) {
7427 CXXRecordDecl *ClassDecl = MD->getParent();
7428
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007429 // C++ [except.spec]p14:
7430 // An implicitly declared special member function (Clause 12) shall have an
7431 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007432 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007433 if (ClassDecl->isInvalidDecl())
7434 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007435
Sebastian Redl60618fa2011-03-12 11:50:43 +00007436 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007437 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7438 BEnd = ClassDecl->bases_end();
7439 B != BEnd; ++B) {
7440 if (B->isVirtual()) // Handled below.
7441 continue;
7442
Douglas Gregor18274032010-07-03 00:47:00 +00007443 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7444 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007445 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7446 // If this is a deleted function, add it anyway. This might be conformant
7447 // with the standard. This might not. I'm not sure. It might not matter.
7448 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007449 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007450 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007451 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007452
7453 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007454 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7455 BEnd = ClassDecl->vbases_end();
7456 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007457 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7458 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007459 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7460 // If this is a deleted function, add it anyway. This might be conformant
7461 // with the standard. This might not. I'm not sure. It might not matter.
7462 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007463 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007464 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007465 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007466
7467 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007468 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7469 FEnd = ClassDecl->field_end();
7470 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007471 if (F->hasInClassInitializer()) {
7472 if (Expr *E = F->getInClassInitializer())
7473 ExceptSpec.CalledExpr(E);
7474 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007475 // DR1351:
7476 // If the brace-or-equal-initializer of a non-static data member
7477 // invokes a defaulted default constructor of its class or of an
7478 // enclosing class in a potentially evaluated subexpression, the
7479 // program is ill-formed.
7480 //
7481 // This resolution is unworkable: the exception specification of the
7482 // default constructor can be needed in an unevaluated context, in
7483 // particular, in the operand of a noexcept-expression, and we can be
7484 // unable to compute an exception specification for an enclosed class.
7485 //
7486 // We do not allow an in-class initializer to require the evaluation
7487 // of the exception specification for any in-class initializer whose
7488 // definition is not lexically complete.
7489 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007490 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007491 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007492 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7493 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7494 // If this is a deleted function, add it anyway. This might be conformant
7495 // with the standard. This might not. I'm not sure. It might not matter.
7496 // In particular, the problem is that this function never gets called. It
7497 // might just be ill-formed because this function attempts to refer to
7498 // a deleted function here.
7499 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007500 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007501 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007502 }
John McCalle23cf432010-12-14 08:05:40 +00007503
Sean Hunt001cad92011-05-10 00:49:42 +00007504 return ExceptSpec;
7505}
7506
Richard Smith07b0fdc2013-03-18 21:12:30 +00007507Sema::ImplicitExceptionSpecification
7508Sema::ComputeInheritingCtorExceptionSpec(CXXMethodDecl *MD) {
7509 ImplicitExceptionSpecification ExceptSpec(*this);
7510 // FIXME: Compute the exception spec.
7511 return ExceptSpec;
7512}
7513
Richard Smithafb49182012-11-29 01:34:07 +00007514namespace {
7515/// RAII object to register a special member as being currently declared.
7516struct DeclaringSpecialMember {
7517 Sema &S;
7518 Sema::SpecialMemberDecl D;
7519 bool WasAlreadyBeingDeclared;
7520
7521 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7522 : S(S), D(RD, CSM) {
7523 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7524 if (WasAlreadyBeingDeclared)
7525 // This almost never happens, but if it does, ensure that our cache
7526 // doesn't contain a stale result.
7527 S.SpecialMemberCache.clear();
7528
7529 // FIXME: Register a note to be produced if we encounter an error while
7530 // declaring the special member.
7531 }
7532 ~DeclaringSpecialMember() {
7533 if (!WasAlreadyBeingDeclared)
7534 S.SpecialMembersBeingDeclared.erase(D);
7535 }
7536
7537 /// \brief Are we already trying to declare this special member?
7538 bool isAlreadyBeingDeclared() const {
7539 return WasAlreadyBeingDeclared;
7540 }
7541};
7542}
7543
Sean Hunt001cad92011-05-10 00:49:42 +00007544CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7545 CXXRecordDecl *ClassDecl) {
7546 // C++ [class.ctor]p5:
7547 // A default constructor for a class X is a constructor of class X
7548 // that can be called without an argument. If there is no
7549 // user-declared constructor for class X, a default constructor is
7550 // implicitly declared. An implicitly-declared default constructor
7551 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007552 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007553 "Should not build implicit default constructor!");
7554
Richard Smithafb49182012-11-29 01:34:07 +00007555 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7556 if (DSM.isAlreadyBeingDeclared())
7557 return 0;
7558
Richard Smith7756afa2012-06-10 05:43:50 +00007559 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7560 CXXDefaultConstructor,
7561 false);
7562
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007563 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007564 CanQualType ClassType
7565 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007566 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007567 DeclarationName Name
7568 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007569 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007570 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007571 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007572 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007573 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007574 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007575 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007576 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007577
7578 // Build an exception specification pointing back at this constructor.
7579 FunctionProtoType::ExtProtoInfo EPI;
7580 EPI.ExceptionSpecType = EST_Unevaluated;
7581 EPI.ExceptionSpecDecl = DefaultCon;
Jordan Rosebea522f2013-03-08 21:51:21 +00007582 DefaultCon->setType(Context.getFunctionType(Context.VoidTy,
7583 ArrayRef<QualType>(),
7584 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007585
Richard Smithbc2a35d2012-12-08 08:32:28 +00007586 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7587 // constructors is easy to compute.
7588 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7589
7590 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007591 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007592
Douglas Gregor18274032010-07-03 00:47:00 +00007593 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007594 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007595
Douglas Gregor23c94db2010-07-02 17:43:08 +00007596 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007597 PushOnScopeChains(DefaultCon, S, false);
7598 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007599
Douglas Gregor32df23e2010-07-01 22:02:46 +00007600 return DefaultCon;
7601}
7602
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007603void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7604 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007605 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007606 !Constructor->doesThisDeclarationHaveABody() &&
7607 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007608 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007609
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007610 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007611 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007612
Eli Friedman9a14db32012-10-18 20:14:08 +00007613 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007614 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007615 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007616 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007617 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007618 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007619 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007620 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007621 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007622
7623 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007624 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007625
7626 Constructor->setUsed();
7627 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007628
7629 if (ASTMutationListener *L = getASTMutationListener()) {
7630 L->CompletedImplicitDefinition(Constructor);
7631 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007632}
7633
Richard Smith7a614d82011-06-11 17:19:42 +00007634void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007635 // Check that any explicitly-defaulted methods have exception specifications
7636 // compatible with their implicit exception specifications.
7637 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007638}
7639
Richard Smith07b0fdc2013-03-18 21:12:30 +00007640void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
Sebastian Redlf677ea32011-02-05 19:23:19 +00007641 // We start with an initial pass over the base classes to collect those that
7642 // inherit constructors from. If there are none, we can forgo all further
7643 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007644 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007645 BasesVector BasesToInheritFrom;
7646 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7647 BaseE = ClassDecl->bases_end();
7648 BaseIt != BaseE; ++BaseIt) {
7649 if (BaseIt->getInheritConstructors()) {
7650 QualType Base = BaseIt->getType();
7651 if (Base->isDependentType()) {
7652 // If we inherit constructors from anything that is dependent, just
7653 // abort processing altogether. We'll get another chance for the
7654 // instantiations.
Richard Smith07b0fdc2013-03-18 21:12:30 +00007655 // FIXME: We need to ensure that any call to a constructor of this class
7656 // is considered instantiation-dependent in this case.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007657 return;
7658 }
7659 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7660 }
7661 }
7662 if (BasesToInheritFrom.empty())
7663 return;
7664
Richard Smith07b0fdc2013-03-18 21:12:30 +00007665 // FIXME: Constructor templates.
7666
Sebastian Redlf677ea32011-02-05 19:23:19 +00007667 // Now collect the constructors that we already have in the current class.
7668 // Those take precedence over inherited constructors.
Richard Smith07b0fdc2013-03-18 21:12:30 +00007669 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007670 // unless there is a user-declared constructor with the same signature in
7671 // the class where the using-declaration appears.
7672 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7673 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7674 CtorE = ClassDecl->ctor_end();
Richard Smith07b0fdc2013-03-18 21:12:30 +00007675 CtorIt != CtorE; ++CtorIt)
Sebastian Redlf677ea32011-02-05 19:23:19 +00007676 ExistingConstructors.insert(
7677 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007678
Sebastian Redlf677ea32011-02-05 19:23:19 +00007679 DeclarationName CreatedCtorName =
7680 Context.DeclarationNames.getCXXConstructorName(
7681 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7682
7683 // Now comes the true work.
7684 // First, we keep a map from constructor types to the base that introduced
7685 // them. Needed for finding conflicting constructors. We also keep the
7686 // actually inserted declarations in there, for pretty diagnostics.
7687 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7688 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7689 ConstructorToSourceMap InheritedConstructors;
7690 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7691 BaseE = BasesToInheritFrom.end();
7692 BaseIt != BaseE; ++BaseIt) {
7693 const RecordType *Base = *BaseIt;
7694 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7695 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7696 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7697 CtorE = BaseDecl->ctor_end();
7698 CtorIt != CtorE; ++CtorIt) {
7699 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00007700 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00007701 DeclarationName Name =
7702 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00007703 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7704 LookupQualifiedName(Result, CurContext);
7705 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007706 SourceLocation UsingLoc = UD ? UD->getLocation() :
7707 ClassDecl->getLocation();
7708
Richard Smith07b0fdc2013-03-18 21:12:30 +00007709 // C++11 [class.inhctor]p1:
7710 // The candidate set of inherited constructors from the class X named in
7711 // the using-declaration consists of actual constructors and notional
7712 // constructors that result from the transformation of defaulted
7713 // parameters as follows:
7714 // - all non-template constructors of X, and
Sebastian Redlf677ea32011-02-05 19:23:19 +00007715 // - for each non-template constructor of X that has at least one
7716 // parameter with a default argument, the set of constructors that
7717 // results from omitting any ellipsis parameter specification and
7718 // successively omitting parameters with a default argument from the
Richard Smith07b0fdc2013-03-18 21:12:30 +00007719 // end of the parameter-type-list, and
7720 // FIXME: ...also constructor templates.
David Blaikie581deb32012-06-06 20:45:41 +00007721 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007722 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7723 const FunctionProtoType *BaseCtorType =
7724 BaseCtor->getType()->getAs<FunctionProtoType>();
7725
Richard Smith07b0fdc2013-03-18 21:12:30 +00007726 // Determine whether this would be a copy or move constructor for the
7727 // derived class.
7728 if (BaseCtorType->getNumArgs() >= 1 &&
7729 BaseCtorType->getArgType(0)->isReferenceType() &&
7730 Context.hasSameUnqualifiedType(
7731 BaseCtorType->getArgType(0)->getPointeeType(),
7732 Context.getTagDeclType(ClassDecl)))
7733 CanBeCopyOrMove = true;
7734
7735 ArrayRef<QualType> ArgTypes(BaseCtorType->getArgTypes());
7736 FunctionProtoType::ExtProtoInfo EPI = BaseCtorType->getExtProtoInfo();
7737 // Core issue (no number yet): the ellipsis is always discarded.
7738 if (EPI.Variadic) {
7739 Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7740 Diag(BaseCtor->getLocation(),
7741 diag::note_using_decl_constructor_ellipsis);
7742 EPI.Variadic = false;
7743 }
7744
7745 for (unsigned Params = BaseCtor->getMinRequiredArguments(),
7746 MaxParams = BaseCtor->getNumParams();
7747 Params <= MaxParams; ++Params) {
Sebastian Redlf677ea32011-02-05 19:23:19 +00007748 // Skip default constructors. They're never inherited.
Richard Smith07b0fdc2013-03-18 21:12:30 +00007749 if (Params == 0)
Sebastian Redlf677ea32011-02-05 19:23:19 +00007750 continue;
Richard Smith07b0fdc2013-03-18 21:12:30 +00007751
7752 // Skip copy and move constructors for both base and derived class
7753 // for the same reason.
7754 if (CanBeCopyOrMove && Params == 1)
Sebastian Redlf677ea32011-02-05 19:23:19 +00007755 continue;
7756
7757 // Build up a function type for this particular constructor.
Richard Smith07b0fdc2013-03-18 21:12:30 +00007758 QualType NewCtorType =
7759 Context.getFunctionType(Context.VoidTy, ArgTypes.slice(0, Params),
7760 EPI);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007761 const Type *CanonicalNewCtorType =
Richard Smith07b0fdc2013-03-18 21:12:30 +00007762 Context.getCanonicalType(NewCtorType).getTypePtr();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007763
Richard Smith07b0fdc2013-03-18 21:12:30 +00007764 // C++11 [class.inhctor]p3:
7765 // ... a constructor is implicitly declared with the same constructor
7766 // characteristics unless there is a user-declared constructor with
7767 // the same signature in the class where the using-declaration appears
Sebastian Redlf677ea32011-02-05 19:23:19 +00007768 if (ExistingConstructors.count(CanonicalNewCtorType))
7769 continue;
7770
Richard Smith07b0fdc2013-03-18 21:12:30 +00007771 // C++11 [class.inhctor]p7:
7772 // If two using-declarations declare inheriting constructors with the
7773 // same signature, the program is ill-formed
Sebastian Redlf677ea32011-02-05 19:23:19 +00007774 std::pair<ConstructorToSourceMap::iterator, bool> result =
7775 InheritedConstructors.insert(std::make_pair(
7776 CanonicalNewCtorType,
7777 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7778 if (!result.second) {
7779 // Already in the map. If it came from a different class, that's an
7780 // error. Not if it's from the same.
7781 CanQualType PreviousBase = result.first->second.first;
7782 if (CanonicalBase != PreviousBase) {
7783 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7784 const CXXConstructorDecl *PrevBaseCtor =
7785 PrevCtor->getInheritedConstructor();
7786 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7787
7788 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7789 Diag(BaseCtor->getLocation(),
7790 diag::note_using_decl_constructor_conflict_current_ctor);
7791 Diag(PrevBaseCtor->getLocation(),
7792 diag::note_using_decl_constructor_conflict_previous_ctor);
7793 Diag(PrevCtor->getLocation(),
7794 diag::note_using_decl_constructor_conflict_previous_using);
Richard Smith07b0fdc2013-03-18 21:12:30 +00007795 } else {
7796 // Core issue (no number): if the same inheriting constructor is
7797 // produced by multiple base class constructors from the same base
7798 // class, the inheriting constructor is defined as deleted.
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007799 SetDeclDeleted(result.first->second.second, UsingLoc);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007800 }
7801 continue;
7802 }
7803
7804 // OK, we're there, now add the constructor.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007805 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7806 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Richard Smith07b0fdc2013-03-18 21:12:30 +00007807 Context, ClassDecl, UsingLoc, DNI, NewCtorType,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007808 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smith07b0fdc2013-03-18 21:12:30 +00007809 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007810 NewCtor->setAccess(BaseCtor->getAccess());
7811
Richard Smith07b0fdc2013-03-18 21:12:30 +00007812 // Build an unevaluated exception specification for this constructor.
7813 EPI.ExceptionSpecType = EST_Unevaluated;
7814 EPI.ExceptionSpecDecl = NewCtor;
7815 NewCtor->setType(Context.getFunctionType(Context.VoidTy,
7816 ArgTypes.slice(0, Params),
7817 EPI));
7818
Sebastian Redlf677ea32011-02-05 19:23:19 +00007819 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007820 SmallVector<ParmVarDecl *, 16> ParamDecls;
Richard Smith07b0fdc2013-03-18 21:12:30 +00007821 for (unsigned i = 0; i < Params; ++i) {
7822 ParmVarDecl *PD = ParmVarDecl::Create(Context, NewCtor,
7823 UsingLoc, UsingLoc,
7824 /*IdentifierInfo=*/0,
7825 BaseCtorType->getArgType(i),
7826 /*TInfo=*/0, SC_None,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00007827 /*DefaultArg=*/0);
Richard Smith07b0fdc2013-03-18 21:12:30 +00007828 PD->setScopeInfo(0, i);
7829 PD->setImplicit();
7830 ParamDecls.push_back(PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007831 }
David Blaikie4278c652011-09-21 18:16:56 +00007832 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007833 NewCtor->setInheritedConstructor(BaseCtor);
Richard Smith07b0fdc2013-03-18 21:12:30 +00007834 if (BaseCtor->isDeleted())
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007835 SetDeclDeleted(NewCtor, UsingLoc);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007836
Sebastian Redlf677ea32011-02-05 19:23:19 +00007837 ClassDecl->addDecl(NewCtor);
7838 result.first->second.second = NewCtor;
7839 }
7840 }
7841 }
7842}
7843
Richard Smith07b0fdc2013-03-18 21:12:30 +00007844void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
7845 CXXConstructorDecl *Constructor) {
7846 CXXRecordDecl *ClassDecl = Constructor->getParent();
7847 assert(Constructor->getInheritedConstructor() &&
7848 !Constructor->doesThisDeclarationHaveABody() &&
7849 !Constructor->isDeleted());
7850
7851 SynthesizedFunctionScope Scope(*this, Constructor);
7852 DiagnosticErrorTrap Trap(Diags);
7853 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
7854 Trap.hasErrorOccurred()) {
7855 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
7856 << Context.getTagDeclType(ClassDecl);
7857 Constructor->setInvalidDecl();
7858 return;
7859 }
7860
7861 SourceLocation Loc = Constructor->getLocation();
7862 Constructor->setBody(new (Context) CompoundStmt(Loc));
7863
7864 Constructor->setUsed();
7865 MarkVTableUsed(CurrentLocation, ClassDecl);
7866
7867 if (ASTMutationListener *L = getASTMutationListener()) {
7868 L->CompletedImplicitDefinition(Constructor);
7869 }
7870}
7871
7872
Sean Huntcb45a0f2011-05-12 22:46:25 +00007873Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007874Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7875 CXXRecordDecl *ClassDecl = MD->getParent();
7876
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007877 // C++ [except.spec]p14:
7878 // An implicitly declared special member function (Clause 12) shall have
7879 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007880 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007881 if (ClassDecl->isInvalidDecl())
7882 return ExceptSpec;
7883
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007884 // Direct base-class destructors.
7885 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7886 BEnd = ClassDecl->bases_end();
7887 B != BEnd; ++B) {
7888 if (B->isVirtual()) // Handled below.
7889 continue;
7890
7891 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007892 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007893 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007894 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007895
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007896 // Virtual base-class destructors.
7897 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7898 BEnd = ClassDecl->vbases_end();
7899 B != BEnd; ++B) {
7900 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007901 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007902 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007903 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007904
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007905 // Field destructors.
7906 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7907 FEnd = ClassDecl->field_end();
7908 F != FEnd; ++F) {
7909 if (const RecordType *RecordTy
7910 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007911 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007912 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007913 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007914
Sean Huntcb45a0f2011-05-12 22:46:25 +00007915 return ExceptSpec;
7916}
7917
7918CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7919 // C++ [class.dtor]p2:
7920 // If a class has no user-declared destructor, a destructor is
7921 // declared implicitly. An implicitly-declared destructor is an
7922 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00007923 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00007924
Richard Smithafb49182012-11-29 01:34:07 +00007925 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7926 if (DSM.isAlreadyBeingDeclared())
7927 return 0;
7928
Douglas Gregor4923aa22010-07-02 20:37:36 +00007929 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007930 CanQualType ClassType
7931 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007932 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007933 DeclarationName Name
7934 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007935 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007936 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007937 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7938 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007939 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007940 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007941 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007942 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007943
7944 // Build an exception specification pointing back at this destructor.
7945 FunctionProtoType::ExtProtoInfo EPI;
7946 EPI.ExceptionSpecType = EST_Unevaluated;
7947 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00007948 Destructor->setType(Context.getFunctionType(Context.VoidTy,
7949 ArrayRef<QualType>(),
7950 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007951
Richard Smithbc2a35d2012-12-08 08:32:28 +00007952 AddOverriddenMethods(ClassDecl, Destructor);
7953
7954 // We don't need to use SpecialMemberIsTrivial here; triviality for
7955 // destructors is easy to compute.
7956 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7957
7958 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007959 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007960
Douglas Gregor4923aa22010-07-02 20:37:36 +00007961 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007962 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007963
Douglas Gregor4923aa22010-07-02 20:37:36 +00007964 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007965 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007966 PushOnScopeChains(Destructor, S, false);
7967 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007968
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007969 return Destructor;
7970}
7971
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007972void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007973 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007974 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007975 !Destructor->doesThisDeclarationHaveABody() &&
7976 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007977 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007978 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007979 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007980
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007981 if (Destructor->isInvalidDecl())
7982 return;
7983
Eli Friedman9a14db32012-10-18 20:14:08 +00007984 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007985
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007986 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007987 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7988 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007989
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007990 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007991 Diag(CurrentLocation, diag::note_member_synthesized_at)
7992 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7993
7994 Destructor->setInvalidDecl();
7995 return;
7996 }
7997
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007998 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007999 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008000 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008001 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008002 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008003
8004 if (ASTMutationListener *L = getASTMutationListener()) {
8005 L->CompletedImplicitDefinition(Destructor);
8006 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008007}
8008
Richard Smitha4156b82012-04-21 18:42:51 +00008009/// \brief Perform any semantic analysis which needs to be delayed until all
8010/// pending class member declarations have been parsed.
8011void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008012 // If the context is an invalid C++ class, just suppress these checks.
8013 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8014 if (Record->isInvalidDecl()) {
8015 DelayedDestructorExceptionSpecChecks.clear();
8016 return;
8017 }
8018 }
8019
Richard Smitha4156b82012-04-21 18:42:51 +00008020 // Perform any deferred checking of exception specifications for virtual
8021 // destructors.
8022 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8023 i != e; ++i) {
8024 const CXXDestructorDecl *Dtor =
8025 DelayedDestructorExceptionSpecChecks[i].first;
8026 assert(!Dtor->getParent()->isDependentType() &&
8027 "Should not ever add destructors of templates into the list.");
8028 CheckOverridingFunctionExceptionSpec(Dtor,
8029 DelayedDestructorExceptionSpecChecks[i].second);
8030 }
8031 DelayedDestructorExceptionSpecChecks.clear();
8032}
8033
Richard Smithb9d0b762012-07-27 04:22:15 +00008034void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8035 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008036 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008037 "adjusting dtor exception specs was introduced in c++11");
8038
Sebastian Redl0ee33912011-05-19 05:13:44 +00008039 // C++11 [class.dtor]p3:
8040 // A declaration of a destructor that does not have an exception-
8041 // specification is implicitly considered to have the same exception-
8042 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008043 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008044 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008045 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008046 return;
8047
Chandler Carruth3f224b22011-09-20 04:55:26 +00008048 // Replace the destructor's type, building off the existing one. Fortunately,
8049 // the only thing of interest in the destructor type is its extended info.
8050 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008051 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8052 EPI.ExceptionSpecType = EST_Unevaluated;
8053 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00008054 Destructor->setType(Context.getFunctionType(Context.VoidTy,
8055 ArrayRef<QualType>(),
8056 EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008057
Sebastian Redl0ee33912011-05-19 05:13:44 +00008058 // FIXME: If the destructor has a body that could throw, and the newly created
8059 // spec doesn't allow exceptions, we should emit a warning, because this
8060 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008061 // However, we don't have a body or an exception specification yet, so it
8062 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008063}
8064
Richard Smith8c889532012-11-14 00:50:40 +00008065/// When generating a defaulted copy or move assignment operator, if a field
8066/// should be copied with __builtin_memcpy rather than via explicit assignments,
8067/// do so. This optimization only applies for arrays of scalars, and for arrays
8068/// of class type where the selected copy/move-assignment operator is trivial.
8069static StmtResult
8070buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8071 Expr *To, Expr *From) {
8072 // Compute the size of the memory buffer to be copied.
8073 QualType SizeType = S.Context.getSizeType();
8074 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8075 S.Context.getTypeSizeInChars(T).getQuantity());
8076
8077 // Take the address of the field references for "from" and "to". We
8078 // directly construct UnaryOperators here because semantic analysis
8079 // does not permit us to take the address of an xvalue.
8080 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8081 S.Context.getPointerType(From->getType()),
8082 VK_RValue, OK_Ordinary, Loc);
8083 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8084 S.Context.getPointerType(To->getType()),
8085 VK_RValue, OK_Ordinary, Loc);
8086
8087 const Type *E = T->getBaseElementTypeUnsafe();
8088 bool NeedsCollectableMemCpy =
8089 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8090
8091 // Create a reference to the __builtin_objc_memmove_collectable function
8092 StringRef MemCpyName = NeedsCollectableMemCpy ?
8093 "__builtin_objc_memmove_collectable" :
8094 "__builtin_memcpy";
8095 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8096 Sema::LookupOrdinaryName);
8097 S.LookupName(R, S.TUScope, true);
8098
8099 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8100 if (!MemCpy)
8101 // Something went horribly wrong earlier, and we will have complained
8102 // about it.
8103 return StmtError();
8104
8105 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8106 VK_RValue, Loc, 0);
8107 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8108
8109 Expr *CallArgs[] = {
8110 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8111 };
8112 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8113 Loc, CallArgs, Loc);
8114
8115 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8116 return S.Owned(Call.takeAs<Stmt>());
8117}
8118
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008119/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008120/// \c To.
8121///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008122/// This routine is used to copy/move the members of a class with an
8123/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008124/// copied are arrays, this routine builds for loops to copy them.
8125///
8126/// \param S The Sema object used for type-checking.
8127///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008128/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008129///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008130/// \param T The type of the expressions being copied/moved. Both expressions
8131/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008132///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008133/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008134///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008135/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008136///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008137/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008138/// Otherwise, it's a non-static member subobject.
8139///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008140/// \param Copying Whether we're copying or moving.
8141///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008142/// \param Depth Internal parameter recording the depth of the recursion.
8143///
Richard Smith8c889532012-11-14 00:50:40 +00008144/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8145/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008146static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008147buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8148 Expr *To, Expr *From,
8149 bool CopyingBaseSubobject, bool Copying,
8150 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008151 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008152 // Each subobject is assigned in the manner appropriate to its type:
8153 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008154 // - if the subobject is of class type, as if by a call to operator= with
8155 // the subobject as the object expression and the corresponding
8156 // subobject of x as a single function argument (as if by explicit
8157 // qualification; that is, ignoring any possible virtual overriding
8158 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008159 //
8160 // C++03 [class.copy]p13:
8161 // - if the subobject is of class type, the copy assignment operator for
8162 // the class is used (as if by explicit qualification; that is,
8163 // ignoring any possible virtual overriding functions in more derived
8164 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008165 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8166 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008167
Douglas Gregor06a9f362010-05-01 20:49:11 +00008168 // Look for operator=.
8169 DeclarationName Name
8170 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8171 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8172 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008173
Richard Smith044c8aa2012-11-13 00:54:12 +00008174 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8175 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008176 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008177 LookupResult::Filter F = OpLookup.makeFilter();
8178 while (F.hasNext()) {
8179 NamedDecl *D = F.next();
8180 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8181 if (Method->isCopyAssignmentOperator() ||
8182 (!Copying && Method->isMoveAssignmentOperator()))
8183 continue;
8184
8185 F.erase();
8186 }
8187 F.done();
John McCallb0207482010-03-16 06:11:48 +00008188 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008189
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008190 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008191 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008192 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008193 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008194 // ambiguities), we need to cast "this" to that subobject type; to
8195 // ensure that we don't go through the virtual call mechanism, we need
8196 // to qualify the operator= name with the base class (see below). However,
8197 // this means that if the base class has a protected copy assignment
8198 // operator, the protected member access check will fail. So, we
8199 // rewrite "protected" access to "public" access in this case, since we
8200 // know by construction that we're calling from a derived class.
8201 if (CopyingBaseSubobject) {
8202 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8203 L != LEnd; ++L) {
8204 if (L.getAccess() == AS_protected)
8205 L.setAccess(AS_public);
8206 }
8207 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008208
Douglas Gregor06a9f362010-05-01 20:49:11 +00008209 // Create the nested-name-specifier that will be used to qualify the
8210 // reference to operator=; this is required to suppress the virtual
8211 // call mechanism.
8212 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008213 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008214 SS.MakeTrivial(S.Context,
8215 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008216 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008217 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008218
Douglas Gregor06a9f362010-05-01 20:49:11 +00008219 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008220 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008221 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008222 /*TemplateKWLoc=*/SourceLocation(),
8223 /*FirstQualifierInScope=*/0,
8224 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008225 /*TemplateArgs=*/0,
8226 /*SuppressQualifierCheck=*/true);
8227 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008228 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008229
Douglas Gregor06a9f362010-05-01 20:49:11 +00008230 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008231
Richard Smith044c8aa2012-11-13 00:54:12 +00008232 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008233 OpEqualRef.takeAs<Expr>(),
8234 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008235 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008236 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008237
Richard Smith8c889532012-11-14 00:50:40 +00008238 // If we built a call to a trivial 'operator=' while copying an array,
8239 // bail out. We'll replace the whole shebang with a memcpy.
8240 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8241 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8242 return StmtResult((Stmt*)0);
8243
Richard Smith044c8aa2012-11-13 00:54:12 +00008244 // Convert to an expression-statement, and clean up any produced
8245 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008246 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008247 }
John McCallb0207482010-03-16 06:11:48 +00008248
Richard Smith044c8aa2012-11-13 00:54:12 +00008249 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008250 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008251 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008252 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008253 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008254 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008255 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008256 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008257 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008258
8259 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008260 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008261
Douglas Gregor06a9f362010-05-01 20:49:11 +00008262 // Construct a loop over the array bounds, e.g.,
8263 //
8264 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8265 //
8266 // that will copy each of the array elements.
8267 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008268
Douglas Gregor06a9f362010-05-01 20:49:11 +00008269 // Create the iteration variable.
8270 IdentifierInfo *IterationVarName = 0;
8271 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008272 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008273 llvm::raw_svector_ostream OS(Str);
8274 OS << "__i" << Depth;
8275 IterationVarName = &S.Context.Idents.get(OS.str());
8276 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008277 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008278 IterationVarName, SizeType,
8279 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008280 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008281
Douglas Gregor06a9f362010-05-01 20:49:11 +00008282 // Initialize the iteration variable to zero.
8283 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008284 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008285
8286 // Create a reference to the iteration variable; we'll use this several
8287 // times throughout.
8288 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008289 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008290 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008291 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8292 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8293
Douglas Gregor06a9f362010-05-01 20:49:11 +00008294 // Create the DeclStmt that holds the iteration variable.
8295 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008296
Douglas Gregor06a9f362010-05-01 20:49:11 +00008297 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008298 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008299 IterationVarRefRVal,
8300 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008301 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008302 IterationVarRefRVal,
8303 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008304 if (!Copying) // Cast to rvalue
8305 From = CastForMoving(S, From);
8306
8307 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008308 StmtResult Copy =
8309 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8310 To, From, CopyingBaseSubobject,
8311 Copying, Depth + 1);
8312 // Bail out if copying fails or if we determined that we should use memcpy.
8313 if (Copy.isInvalid() || !Copy.get())
8314 return Copy;
8315
8316 // Create the comparison against the array bound.
8317 llvm::APInt Upper
8318 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8319 Expr *Comparison
8320 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8321 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8322 BO_NE, S.Context.BoolTy,
8323 VK_RValue, OK_Ordinary, Loc, false);
8324
8325 // Create the pre-increment of the iteration variable.
8326 Expr *Increment
8327 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8328 VK_LValue, OK_Ordinary, Loc);
8329
Douglas Gregor06a9f362010-05-01 20:49:11 +00008330 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008331 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008332 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008333 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008334 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008335}
8336
Richard Smith8c889532012-11-14 00:50:40 +00008337static StmtResult
8338buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8339 Expr *To, Expr *From,
8340 bool CopyingBaseSubobject, bool Copying) {
8341 // Maybe we should use a memcpy?
8342 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8343 T.isTriviallyCopyableType(S.Context))
8344 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8345
8346 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8347 CopyingBaseSubobject,
8348 Copying, 0));
8349
8350 // If we ended up picking a trivial assignment operator for an array of a
8351 // non-trivially-copyable class type, just emit a memcpy.
8352 if (!Result.isInvalid() && !Result.get())
8353 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8354
8355 return Result;
8356}
8357
Richard Smithb9d0b762012-07-27 04:22:15 +00008358Sema::ImplicitExceptionSpecification
8359Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8360 CXXRecordDecl *ClassDecl = MD->getParent();
8361
8362 ImplicitExceptionSpecification ExceptSpec(*this);
8363 if (ClassDecl->isInvalidDecl())
8364 return ExceptSpec;
8365
8366 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8367 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8368 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8369
Douglas Gregorb87786f2010-07-01 17:48:08 +00008370 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008371 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008372 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008373
8374 // It is unspecified whether or not an implicit copy assignment operator
8375 // attempts to deduplicate calls to assignment operators of virtual bases are
8376 // made. As such, this exception specification is effectively unspecified.
8377 // Based on a similar decision made for constness in C++0x, we're erring on
8378 // the side of assuming such calls to be made regardless of whether they
8379 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008380 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8381 BaseEnd = ClassDecl->bases_end();
8382 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008383 if (Base->isVirtual())
8384 continue;
8385
Douglas Gregora376d102010-07-02 21:50:04 +00008386 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008387 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008388 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8389 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008390 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008391 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008392
8393 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8394 BaseEnd = ClassDecl->vbases_end();
8395 Base != BaseEnd; ++Base) {
8396 CXXRecordDecl *BaseClassDecl
8397 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8398 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8399 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008400 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008401 }
8402
Douglas Gregorb87786f2010-07-01 17:48:08 +00008403 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8404 FieldEnd = ClassDecl->field_end();
8405 Field != FieldEnd;
8406 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008407 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008408 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8409 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008410 LookupCopyingAssignment(FieldClassDecl,
8411 ArgQuals | FieldType.getCVRQualifiers(),
8412 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008413 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008414 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008415 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008416
Richard Smithb9d0b762012-07-27 04:22:15 +00008417 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008418}
8419
8420CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8421 // Note: The following rules are largely analoguous to the copy
8422 // constructor rules. Note that virtual bases are not taken into account
8423 // for determining the argument type of the operator. Note also that
8424 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008425 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008426
Richard Smithafb49182012-11-29 01:34:07 +00008427 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8428 if (DSM.isAlreadyBeingDeclared())
8429 return 0;
8430
Sean Hunt30de05c2011-05-14 05:23:20 +00008431 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8432 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008433 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008434 ArgType = ArgType.withConst();
8435 ArgType = Context.getLValueReferenceType(ArgType);
8436
Douglas Gregord3c35902010-07-01 16:36:15 +00008437 // An implicitly-declared copy assignment operator is an inline public
8438 // member of its class.
8439 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008440 SourceLocation ClassLoc = ClassDecl->getLocation();
8441 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008442 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008443 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008444 /*TInfo=*/0,
8445 /*StorageClass=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008446 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008447 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008448 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008449 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008450 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008451
8452 // Build an exception specification pointing back at this member.
8453 FunctionProtoType::ExtProtoInfo EPI;
8454 EPI.ExceptionSpecType = EST_Unevaluated;
8455 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008456 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008457
Douglas Gregord3c35902010-07-01 16:36:15 +00008458 // Add the parameter to the operator.
8459 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008460 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008461 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008462 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008463 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008464
Richard Smithbc2a35d2012-12-08 08:32:28 +00008465 AddOverriddenMethods(ClassDecl, CopyAssignment);
8466
8467 CopyAssignment->setTrivial(
8468 ClassDecl->needsOverloadResolutionForCopyAssignment()
8469 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8470 : ClassDecl->hasTrivialCopyAssignment());
8471
Nico Weberafcc96a2012-01-23 03:19:29 +00008472 // C++0x [class.copy]p19:
8473 // .... If the class definition does not explicitly declare a copy
8474 // assignment operator, there is no user-declared move constructor, and
8475 // there is no user-declared move assignment operator, a copy assignment
8476 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008477 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008478 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008479
Richard Smithbc2a35d2012-12-08 08:32:28 +00008480 // Note that we have added this copy-assignment operator.
8481 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8482
8483 if (Scope *S = getScopeForContext(ClassDecl))
8484 PushOnScopeChains(CopyAssignment, S, false);
8485 ClassDecl->addDecl(CopyAssignment);
8486
Douglas Gregord3c35902010-07-01 16:36:15 +00008487 return CopyAssignment;
8488}
8489
Douglas Gregor06a9f362010-05-01 20:49:11 +00008490void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8491 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008492 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008493 CopyAssignOperator->isOverloadedOperator() &&
8494 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008495 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8496 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008497 "DefineImplicitCopyAssignment called for wrong function");
8498
8499 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8500
8501 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8502 CopyAssignOperator->setInvalidDecl();
8503 return;
8504 }
8505
8506 CopyAssignOperator->setUsed();
8507
Eli Friedman9a14db32012-10-18 20:14:08 +00008508 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008509 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008510
8511 // C++0x [class.copy]p30:
8512 // The implicitly-defined or explicitly-defaulted copy assignment operator
8513 // for a non-union class X performs memberwise copy assignment of its
8514 // subobjects. The direct base classes of X are assigned first, in the
8515 // order of their declaration in the base-specifier-list, and then the
8516 // immediate non-static data members of X are assigned, in the order in
8517 // which they were declared in the class definition.
8518
8519 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008520 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008521
8522 // The parameter for the "other" object, which we are copying from.
8523 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8524 Qualifiers OtherQuals = Other->getType().getQualifiers();
8525 QualType OtherRefType = Other->getType();
8526 if (const LValueReferenceType *OtherRef
8527 = OtherRefType->getAs<LValueReferenceType>()) {
8528 OtherRefType = OtherRef->getPointeeType();
8529 OtherQuals = OtherRefType.getQualifiers();
8530 }
8531
8532 // Our location for everything implicitly-generated.
8533 SourceLocation Loc = CopyAssignOperator->getLocation();
8534
8535 // Construct a reference to the "other" object. We'll be using this
8536 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008537 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008538 assert(OtherRef && "Reference to parameter cannot fail!");
8539
8540 // Construct the "this" pointer. We'll be using this throughout the generated
8541 // ASTs.
8542 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8543 assert(This && "Reference to this cannot fail!");
8544
8545 // Assign base classes.
8546 bool Invalid = false;
8547 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8548 E = ClassDecl->bases_end(); Base != E; ++Base) {
8549 // Form the assignment:
8550 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8551 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008552 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008553 Invalid = true;
8554 continue;
8555 }
8556
John McCallf871d0c2010-08-07 06:22:56 +00008557 CXXCastPath BasePath;
8558 BasePath.push_back(Base);
8559
Douglas Gregor06a9f362010-05-01 20:49:11 +00008560 // Construct the "from" expression, which is an implicit cast to the
8561 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008562 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008563 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8564 CK_UncheckedDerivedToBase,
8565 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008566
8567 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008568 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008569
8570 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008571 To = ImpCastExprToType(To.take(),
8572 Context.getCVRQualifiedType(BaseType,
8573 CopyAssignOperator->getTypeQualifiers()),
8574 CK_UncheckedDerivedToBase,
8575 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008576
8577 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008578 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008579 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008580 /*CopyingBaseSubobject=*/true,
8581 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008582 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008583 Diag(CurrentLocation, diag::note_member_synthesized_at)
8584 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8585 CopyAssignOperator->setInvalidDecl();
8586 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008587 }
8588
8589 // Success! Record the copy.
8590 Statements.push_back(Copy.takeAs<Expr>());
8591 }
8592
Douglas Gregor06a9f362010-05-01 20:49:11 +00008593 // Assign non-static members.
8594 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8595 FieldEnd = ClassDecl->field_end();
8596 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008597 if (Field->isUnnamedBitfield())
8598 continue;
8599
Douglas Gregor06a9f362010-05-01 20:49:11 +00008600 // Check for members of reference type; we can't copy those.
8601 if (Field->getType()->isReferenceType()) {
8602 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8603 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8604 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008605 Diag(CurrentLocation, diag::note_member_synthesized_at)
8606 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008607 Invalid = true;
8608 continue;
8609 }
8610
8611 // Check for members of const-qualified, non-class type.
8612 QualType BaseType = Context.getBaseElementType(Field->getType());
8613 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8614 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8615 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8616 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008617 Diag(CurrentLocation, diag::note_member_synthesized_at)
8618 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008619 Invalid = true;
8620 continue;
8621 }
John McCallb77115d2011-06-17 00:18:42 +00008622
8623 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008624 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8625 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008626
8627 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008628 if (FieldType->isIncompleteArrayType()) {
8629 assert(ClassDecl->hasFlexibleArrayMember() &&
8630 "Incomplete array type is not valid");
8631 continue;
8632 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008633
8634 // Build references to the field in the object we're copying from and to.
8635 CXXScopeSpec SS; // Intentionally empty
8636 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8637 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008638 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008639 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008640 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008641 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008642 SS, SourceLocation(), 0,
8643 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008644 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008645 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008646 SS, SourceLocation(), 0,
8647 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008648 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8649 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008650
Douglas Gregor06a9f362010-05-01 20:49:11 +00008651 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008652 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008653 To.get(), From.get(),
8654 /*CopyingBaseSubobject=*/false,
8655 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008656 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008657 Diag(CurrentLocation, diag::note_member_synthesized_at)
8658 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8659 CopyAssignOperator->setInvalidDecl();
8660 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008661 }
8662
8663 // Success! Record the copy.
8664 Statements.push_back(Copy.takeAs<Stmt>());
8665 }
8666
8667 if (!Invalid) {
8668 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008669 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008670
John McCall60d7b3a2010-08-24 06:29:42 +00008671 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008672 if (Return.isInvalid())
8673 Invalid = true;
8674 else {
8675 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008676
8677 if (Trap.hasErrorOccurred()) {
8678 Diag(CurrentLocation, diag::note_member_synthesized_at)
8679 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8680 Invalid = true;
8681 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008682 }
8683 }
8684
8685 if (Invalid) {
8686 CopyAssignOperator->setInvalidDecl();
8687 return;
8688 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008689
8690 StmtResult Body;
8691 {
8692 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008693 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008694 /*isStmtExpr=*/false);
8695 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8696 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008697 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008698
8699 if (ASTMutationListener *L = getASTMutationListener()) {
8700 L->CompletedImplicitDefinition(CopyAssignOperator);
8701 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008702}
8703
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008704Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008705Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8706 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008707
Richard Smithb9d0b762012-07-27 04:22:15 +00008708 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008709 if (ClassDecl->isInvalidDecl())
8710 return ExceptSpec;
8711
8712 // C++0x [except.spec]p14:
8713 // An implicitly declared special member function (Clause 12) shall have an
8714 // exception-specification. [...]
8715
8716 // It is unspecified whether or not an implicit move assignment operator
8717 // attempts to deduplicate calls to assignment operators of virtual bases are
8718 // made. As such, this exception specification is effectively unspecified.
8719 // Based on a similar decision made for constness in C++0x, we're erring on
8720 // the side of assuming such calls to be made regardless of whether they
8721 // actually happen.
8722 // Note that a move constructor is not implicitly declared when there are
8723 // virtual bases, but it can still be user-declared and explicitly defaulted.
8724 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8725 BaseEnd = ClassDecl->bases_end();
8726 Base != BaseEnd; ++Base) {
8727 if (Base->isVirtual())
8728 continue;
8729
8730 CXXRecordDecl *BaseClassDecl
8731 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8732 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008733 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008734 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008735 }
8736
8737 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8738 BaseEnd = ClassDecl->vbases_end();
8739 Base != BaseEnd; ++Base) {
8740 CXXRecordDecl *BaseClassDecl
8741 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8742 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008743 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008744 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008745 }
8746
8747 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8748 FieldEnd = ClassDecl->field_end();
8749 Field != FieldEnd;
8750 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008751 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008752 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008753 if (CXXMethodDecl *MoveAssign =
8754 LookupMovingAssignment(FieldClassDecl,
8755 FieldType.getCVRQualifiers(),
8756 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008757 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008758 }
8759 }
8760
8761 return ExceptSpec;
8762}
8763
Richard Smith1c931be2012-04-02 18:40:40 +00008764/// Determine whether the class type has any direct or indirect virtual base
8765/// classes which have a non-trivial move assignment operator.
8766static bool
8767hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8768 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8769 BaseEnd = ClassDecl->vbases_end();
8770 Base != BaseEnd; ++Base) {
8771 CXXRecordDecl *BaseClass =
8772 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8773
8774 // Try to declare the move assignment. If it would be deleted, then the
8775 // class does not have a non-trivial move assignment.
8776 if (BaseClass->needsImplicitMoveAssignment())
8777 S.DeclareImplicitMoveAssignment(BaseClass);
8778
Richard Smith426391c2012-11-16 00:53:38 +00008779 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008780 return true;
8781 }
8782
8783 return false;
8784}
8785
8786/// Determine whether the given type either has a move constructor or is
8787/// trivially copyable.
8788static bool
8789hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8790 Type = S.Context.getBaseElementType(Type);
8791
8792 // FIXME: Technically, non-trivially-copyable non-class types, such as
8793 // reference types, are supposed to return false here, but that appears
8794 // to be a standard defect.
8795 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008796 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008797 return true;
8798
8799 if (Type.isTriviallyCopyableType(S.Context))
8800 return true;
8801
8802 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008803 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8804 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008805 if (ClassDecl->needsImplicitMoveConstructor())
8806 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008807 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008808 }
8809
Richard Smithe5411b72012-12-01 02:35:44 +00008810 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8811 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008812 if (ClassDecl->needsImplicitMoveAssignment())
8813 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008814 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008815}
8816
8817/// Determine whether all non-static data members and direct or virtual bases
8818/// of class \p ClassDecl have either a move operation, or are trivially
8819/// copyable.
8820static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8821 bool IsConstructor) {
8822 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8823 BaseEnd = ClassDecl->bases_end();
8824 Base != BaseEnd; ++Base) {
8825 if (Base->isVirtual())
8826 continue;
8827
8828 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8829 return false;
8830 }
8831
8832 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8833 BaseEnd = ClassDecl->vbases_end();
8834 Base != BaseEnd; ++Base) {
8835 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8836 return false;
8837 }
8838
8839 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8840 FieldEnd = ClassDecl->field_end();
8841 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008842 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008843 return false;
8844 }
8845
8846 return true;
8847}
8848
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008849CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008850 // C++11 [class.copy]p20:
8851 // If the definition of a class X does not explicitly declare a move
8852 // assignment operator, one will be implicitly declared as defaulted
8853 // if and only if:
8854 //
8855 // - [first 4 bullets]
8856 assert(ClassDecl->needsImplicitMoveAssignment());
8857
Richard Smithafb49182012-11-29 01:34:07 +00008858 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8859 if (DSM.isAlreadyBeingDeclared())
8860 return 0;
8861
Richard Smith1c931be2012-04-02 18:40:40 +00008862 // [Checked after we build the declaration]
8863 // - the move assignment operator would not be implicitly defined as
8864 // deleted,
8865
8866 // [DR1402]:
8867 // - X has no direct or indirect virtual base class with a non-trivial
8868 // move assignment operator, and
8869 // - each of X's non-static data members and direct or virtual base classes
8870 // has a type that either has a move assignment operator or is trivially
8871 // copyable.
8872 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8873 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8874 ClassDecl->setFailedImplicitMoveAssignment();
8875 return 0;
8876 }
8877
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008878 // Note: The following rules are largely analoguous to the move
8879 // constructor rules.
8880
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008881 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8882 QualType RetType = Context.getLValueReferenceType(ArgType);
8883 ArgType = Context.getRValueReferenceType(ArgType);
8884
8885 // An implicitly-declared move assignment operator is an inline public
8886 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008887 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8888 SourceLocation ClassLoc = ClassDecl->getLocation();
8889 DeclarationNameInfo NameInfo(Name, ClassLoc);
8890 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008891 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008892 /*TInfo=*/0,
8893 /*StorageClass=*/SC_None,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008894 /*isInline=*/true,
8895 /*isConstexpr=*/false,
8896 SourceLocation());
8897 MoveAssignment->setAccess(AS_public);
8898 MoveAssignment->setDefaulted();
8899 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008900
Richard Smithb9d0b762012-07-27 04:22:15 +00008901 // Build an exception specification pointing back at this member.
8902 FunctionProtoType::ExtProtoInfo EPI;
8903 EPI.ExceptionSpecType = EST_Unevaluated;
8904 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008905 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008906
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008907 // Add the parameter to the operator.
8908 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8909 ClassLoc, ClassLoc, /*Id=*/0,
8910 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008911 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008912 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008913
Richard Smithbc2a35d2012-12-08 08:32:28 +00008914 AddOverriddenMethods(ClassDecl, MoveAssignment);
8915
8916 MoveAssignment->setTrivial(
8917 ClassDecl->needsOverloadResolutionForMoveAssignment()
8918 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8919 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008920
8921 // C++0x [class.copy]p9:
8922 // If the definition of a class X does not explicitly declare a move
8923 // assignment operator, one will be implicitly declared as defaulted if and
8924 // only if:
8925 // [...]
8926 // - the move assignment operator would not be implicitly defined as
8927 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008928 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008929 // Cache this result so that we don't try to generate this over and over
8930 // on every lookup, leaking memory and wasting time.
8931 ClassDecl->setFailedImplicitMoveAssignment();
8932 return 0;
8933 }
8934
Richard Smithbc2a35d2012-12-08 08:32:28 +00008935 // Note that we have added this copy-assignment operator.
8936 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8937
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008938 if (Scope *S = getScopeForContext(ClassDecl))
8939 PushOnScopeChains(MoveAssignment, S, false);
8940 ClassDecl->addDecl(MoveAssignment);
8941
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008942 return MoveAssignment;
8943}
8944
8945void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8946 CXXMethodDecl *MoveAssignOperator) {
8947 assert((MoveAssignOperator->isDefaulted() &&
8948 MoveAssignOperator->isOverloadedOperator() &&
8949 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008950 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8951 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008952 "DefineImplicitMoveAssignment called for wrong function");
8953
8954 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8955
8956 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8957 MoveAssignOperator->setInvalidDecl();
8958 return;
8959 }
8960
8961 MoveAssignOperator->setUsed();
8962
Eli Friedman9a14db32012-10-18 20:14:08 +00008963 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008964 DiagnosticErrorTrap Trap(Diags);
8965
8966 // C++0x [class.copy]p28:
8967 // The implicitly-defined or move assignment operator for a non-union class
8968 // X performs memberwise move assignment of its subobjects. The direct base
8969 // classes of X are assigned first, in the order of their declaration in the
8970 // base-specifier-list, and then the immediate non-static data members of X
8971 // are assigned, in the order in which they were declared in the class
8972 // definition.
8973
8974 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008975 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008976
8977 // The parameter for the "other" object, which we are move from.
8978 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8979 QualType OtherRefType = Other->getType()->
8980 getAs<RValueReferenceType>()->getPointeeType();
8981 assert(OtherRefType.getQualifiers() == 0 &&
8982 "Bad argument type of defaulted move assignment");
8983
8984 // Our location for everything implicitly-generated.
8985 SourceLocation Loc = MoveAssignOperator->getLocation();
8986
8987 // Construct a reference to the "other" object. We'll be using this
8988 // throughout the generated ASTs.
8989 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8990 assert(OtherRef && "Reference to parameter cannot fail!");
8991 // Cast to rvalue.
8992 OtherRef = CastForMoving(*this, OtherRef);
8993
8994 // Construct the "this" pointer. We'll be using this throughout the generated
8995 // ASTs.
8996 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8997 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008998
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008999 // Assign base classes.
9000 bool Invalid = false;
9001 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9002 E = ClassDecl->bases_end(); Base != E; ++Base) {
9003 // Form the assignment:
9004 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9005 QualType BaseType = Base->getType().getUnqualifiedType();
9006 if (!BaseType->isRecordType()) {
9007 Invalid = true;
9008 continue;
9009 }
9010
9011 CXXCastPath BasePath;
9012 BasePath.push_back(Base);
9013
9014 // Construct the "from" expression, which is an implicit cast to the
9015 // appropriately-qualified base type.
9016 Expr *From = OtherRef;
9017 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009018 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009019
9020 // Dereference "this".
9021 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9022
9023 // Implicitly cast "this" to the appropriately-qualified base type.
9024 To = ImpCastExprToType(To.take(),
9025 Context.getCVRQualifiedType(BaseType,
9026 MoveAssignOperator->getTypeQualifiers()),
9027 CK_UncheckedDerivedToBase,
9028 VK_LValue, &BasePath);
9029
9030 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009031 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009032 To.get(), From,
9033 /*CopyingBaseSubobject=*/true,
9034 /*Copying=*/false);
9035 if (Move.isInvalid()) {
9036 Diag(CurrentLocation, diag::note_member_synthesized_at)
9037 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9038 MoveAssignOperator->setInvalidDecl();
9039 return;
9040 }
9041
9042 // Success! Record the move.
9043 Statements.push_back(Move.takeAs<Expr>());
9044 }
9045
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009046 // Assign non-static members.
9047 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9048 FieldEnd = ClassDecl->field_end();
9049 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009050 if (Field->isUnnamedBitfield())
9051 continue;
9052
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009053 // Check for members of reference type; we can't move those.
9054 if (Field->getType()->isReferenceType()) {
9055 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9056 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9057 Diag(Field->getLocation(), diag::note_declared_at);
9058 Diag(CurrentLocation, diag::note_member_synthesized_at)
9059 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9060 Invalid = true;
9061 continue;
9062 }
9063
9064 // Check for members of const-qualified, non-class type.
9065 QualType BaseType = Context.getBaseElementType(Field->getType());
9066 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9067 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9068 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9069 Diag(Field->getLocation(), diag::note_declared_at);
9070 Diag(CurrentLocation, diag::note_member_synthesized_at)
9071 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9072 Invalid = true;
9073 continue;
9074 }
9075
9076 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009077 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9078 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009079
9080 QualType FieldType = Field->getType().getNonReferenceType();
9081 if (FieldType->isIncompleteArrayType()) {
9082 assert(ClassDecl->hasFlexibleArrayMember() &&
9083 "Incomplete array type is not valid");
9084 continue;
9085 }
9086
9087 // Build references to the field in the object we're copying from and to.
9088 CXXScopeSpec SS; // Intentionally empty
9089 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9090 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009091 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009092 MemberLookup.resolveKind();
9093 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9094 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009095 SS, SourceLocation(), 0,
9096 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009097 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9098 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009099 SS, SourceLocation(), 0,
9100 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009101 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9102 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9103
9104 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9105 "Member reference with rvalue base must be rvalue except for reference "
9106 "members, which aren't allowed for move assignment.");
9107
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009108 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009109 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009110 To.get(), From.get(),
9111 /*CopyingBaseSubobject=*/false,
9112 /*Copying=*/false);
9113 if (Move.isInvalid()) {
9114 Diag(CurrentLocation, diag::note_member_synthesized_at)
9115 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9116 MoveAssignOperator->setInvalidDecl();
9117 return;
9118 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009119
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009120 // Success! Record the copy.
9121 Statements.push_back(Move.takeAs<Stmt>());
9122 }
9123
9124 if (!Invalid) {
9125 // Add a "return *this;"
9126 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9127
9128 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9129 if (Return.isInvalid())
9130 Invalid = true;
9131 else {
9132 Statements.push_back(Return.takeAs<Stmt>());
9133
9134 if (Trap.hasErrorOccurred()) {
9135 Diag(CurrentLocation, diag::note_member_synthesized_at)
9136 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9137 Invalid = true;
9138 }
9139 }
9140 }
9141
9142 if (Invalid) {
9143 MoveAssignOperator->setInvalidDecl();
9144 return;
9145 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009146
9147 StmtResult Body;
9148 {
9149 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009150 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009151 /*isStmtExpr=*/false);
9152 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9153 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009154 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9155
9156 if (ASTMutationListener *L = getASTMutationListener()) {
9157 L->CompletedImplicitDefinition(MoveAssignOperator);
9158 }
9159}
9160
Richard Smithb9d0b762012-07-27 04:22:15 +00009161Sema::ImplicitExceptionSpecification
9162Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9163 CXXRecordDecl *ClassDecl = MD->getParent();
9164
9165 ImplicitExceptionSpecification ExceptSpec(*this);
9166 if (ClassDecl->isInvalidDecl())
9167 return ExceptSpec;
9168
9169 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9170 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9171 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9172
Douglas Gregor0d405db2010-07-01 20:59:04 +00009173 // C++ [except.spec]p14:
9174 // An implicitly declared special member function (Clause 12) shall have an
9175 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009176 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9177 BaseEnd = ClassDecl->bases_end();
9178 Base != BaseEnd;
9179 ++Base) {
9180 // Virtual bases are handled below.
9181 if (Base->isVirtual())
9182 continue;
9183
Douglas Gregor22584312010-07-02 23:41:54 +00009184 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009185 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009186 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009187 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009188 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009189 }
9190 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9191 BaseEnd = ClassDecl->vbases_end();
9192 Base != BaseEnd;
9193 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009194 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009195 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009196 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009197 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009198 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009199 }
9200 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9201 FieldEnd = ClassDecl->field_end();
9202 Field != FieldEnd;
9203 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009204 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009205 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9206 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009207 LookupCopyingConstructor(FieldClassDecl,
9208 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009209 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009210 }
9211 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009212
Richard Smithb9d0b762012-07-27 04:22:15 +00009213 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009214}
9215
9216CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9217 CXXRecordDecl *ClassDecl) {
9218 // C++ [class.copy]p4:
9219 // If the class definition does not explicitly declare a copy
9220 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009221 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009222
Richard Smithafb49182012-11-29 01:34:07 +00009223 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9224 if (DSM.isAlreadyBeingDeclared())
9225 return 0;
9226
Sean Hunt49634cf2011-05-13 06:10:58 +00009227 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9228 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009229 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009230 if (Const)
9231 ArgType = ArgType.withConst();
9232 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009233
Richard Smith7756afa2012-06-10 05:43:50 +00009234 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9235 CXXCopyConstructor,
9236 Const);
9237
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009238 DeclarationName Name
9239 = Context.DeclarationNames.getCXXConstructorName(
9240 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009241 SourceLocation ClassLoc = ClassDecl->getLocation();
9242 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009243
9244 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009245 // member of its class.
9246 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009247 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009248 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009249 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009250 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009251 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009252
Richard Smithb9d0b762012-07-27 04:22:15 +00009253 // Build an exception specification pointing back at this member.
9254 FunctionProtoType::ExtProtoInfo EPI;
9255 EPI.ExceptionSpecType = EST_Unevaluated;
9256 EPI.ExceptionSpecDecl = CopyConstructor;
9257 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009258 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009259
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009260 // Add the parameter to the constructor.
9261 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009262 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009263 /*IdentifierInfo=*/0,
9264 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009265 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009266 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009267
Richard Smithbc2a35d2012-12-08 08:32:28 +00009268 CopyConstructor->setTrivial(
9269 ClassDecl->needsOverloadResolutionForCopyConstructor()
9270 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9271 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009272
Nico Weberafcc96a2012-01-23 03:19:29 +00009273 // C++11 [class.copy]p8:
9274 // ... If the class definition does not explicitly declare a copy
9275 // constructor, there is no user-declared move constructor, and there is no
9276 // user-declared move assignment operator, a copy constructor is implicitly
9277 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009278 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009279 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009280
Richard Smithbc2a35d2012-12-08 08:32:28 +00009281 // Note that we have declared this constructor.
9282 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9283
9284 if (Scope *S = getScopeForContext(ClassDecl))
9285 PushOnScopeChains(CopyConstructor, S, false);
9286 ClassDecl->addDecl(CopyConstructor);
9287
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009288 return CopyConstructor;
9289}
9290
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009291void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009292 CXXConstructorDecl *CopyConstructor) {
9293 assert((CopyConstructor->isDefaulted() &&
9294 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009295 !CopyConstructor->doesThisDeclarationHaveABody() &&
9296 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009297 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009298
Anders Carlsson63010a72010-04-23 16:24:12 +00009299 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009300 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009301
Eli Friedman9a14db32012-10-18 20:14:08 +00009302 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009303 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009304
David Blaikie93c86172013-01-17 05:26:25 +00009305 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009306 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009307 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009308 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009309 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009310 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009311 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009312 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9313 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009314 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009315 /*isStmtExpr=*/false)
9316 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009317 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009318 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009319
9320 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009321 if (ASTMutationListener *L = getASTMutationListener()) {
9322 L->CompletedImplicitDefinition(CopyConstructor);
9323 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009324}
9325
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009326Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009327Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9328 CXXRecordDecl *ClassDecl = MD->getParent();
9329
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009330 // C++ [except.spec]p14:
9331 // An implicitly declared special member function (Clause 12) shall have an
9332 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009333 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009334 if (ClassDecl->isInvalidDecl())
9335 return ExceptSpec;
9336
9337 // Direct base-class constructors.
9338 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9339 BEnd = ClassDecl->bases_end();
9340 B != BEnd; ++B) {
9341 if (B->isVirtual()) // Handled below.
9342 continue;
9343
9344 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9345 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009346 CXXConstructorDecl *Constructor =
9347 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009348 // If this is a deleted function, add it anyway. This might be conformant
9349 // with the standard. This might not. I'm not sure. It might not matter.
9350 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009351 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009352 }
9353 }
9354
9355 // Virtual base-class constructors.
9356 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9357 BEnd = ClassDecl->vbases_end();
9358 B != BEnd; ++B) {
9359 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9360 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009361 CXXConstructorDecl *Constructor =
9362 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009363 // If this is a deleted function, add it anyway. This might be conformant
9364 // with the standard. This might not. I'm not sure. It might not matter.
9365 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009366 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009367 }
9368 }
9369
9370 // Field constructors.
9371 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9372 FEnd = ClassDecl->field_end();
9373 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009374 QualType FieldType = Context.getBaseElementType(F->getType());
9375 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9376 CXXConstructorDecl *Constructor =
9377 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009378 // If this is a deleted function, add it anyway. This might be conformant
9379 // with the standard. This might not. I'm not sure. It might not matter.
9380 // In particular, the problem is that this function never gets called. It
9381 // might just be ill-formed because this function attempts to refer to
9382 // a deleted function here.
9383 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009384 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009385 }
9386 }
9387
9388 return ExceptSpec;
9389}
9390
9391CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9392 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009393 // C++11 [class.copy]p9:
9394 // If the definition of a class X does not explicitly declare a move
9395 // constructor, one will be implicitly declared as defaulted if and only if:
9396 //
9397 // - [first 4 bullets]
9398 assert(ClassDecl->needsImplicitMoveConstructor());
9399
Richard Smithafb49182012-11-29 01:34:07 +00009400 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9401 if (DSM.isAlreadyBeingDeclared())
9402 return 0;
9403
Richard Smith1c931be2012-04-02 18:40:40 +00009404 // [Checked after we build the declaration]
9405 // - the move assignment operator would not be implicitly defined as
9406 // deleted,
9407
9408 // [DR1402]:
9409 // - each of X's non-static data members and direct or virtual base classes
9410 // has a type that either has a move constructor or is trivially copyable.
9411 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9412 ClassDecl->setFailedImplicitMoveConstructor();
9413 return 0;
9414 }
9415
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009416 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9417 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009418
Richard Smith7756afa2012-06-10 05:43:50 +00009419 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9420 CXXMoveConstructor,
9421 false);
9422
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009423 DeclarationName Name
9424 = Context.DeclarationNames.getCXXConstructorName(
9425 Context.getCanonicalType(ClassType));
9426 SourceLocation ClassLoc = ClassDecl->getLocation();
9427 DeclarationNameInfo NameInfo(Name, ClassLoc);
9428
9429 // C++0x [class.copy]p11:
9430 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009431 // member of its class.
9432 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009433 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009434 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009435 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009436 MoveConstructor->setAccess(AS_public);
9437 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009438
Richard Smithb9d0b762012-07-27 04:22:15 +00009439 // Build an exception specification pointing back at this member.
9440 FunctionProtoType::ExtProtoInfo EPI;
9441 EPI.ExceptionSpecType = EST_Unevaluated;
9442 EPI.ExceptionSpecDecl = MoveConstructor;
9443 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009444 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009445
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009446 // Add the parameter to the constructor.
9447 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9448 ClassLoc, ClassLoc,
9449 /*IdentifierInfo=*/0,
9450 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009451 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009452 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009453
Richard Smithbc2a35d2012-12-08 08:32:28 +00009454 MoveConstructor->setTrivial(
9455 ClassDecl->needsOverloadResolutionForMoveConstructor()
9456 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9457 : ClassDecl->hasTrivialMoveConstructor());
9458
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009459 // C++0x [class.copy]p9:
9460 // If the definition of a class X does not explicitly declare a move
9461 // constructor, one will be implicitly declared as defaulted if and only if:
9462 // [...]
9463 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009464 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009465 // Cache this result so that we don't try to generate this over and over
9466 // on every lookup, leaking memory and wasting time.
9467 ClassDecl->setFailedImplicitMoveConstructor();
9468 return 0;
9469 }
9470
9471 // Note that we have declared this constructor.
9472 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9473
9474 if (Scope *S = getScopeForContext(ClassDecl))
9475 PushOnScopeChains(MoveConstructor, S, false);
9476 ClassDecl->addDecl(MoveConstructor);
9477
9478 return MoveConstructor;
9479}
9480
9481void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9482 CXXConstructorDecl *MoveConstructor) {
9483 assert((MoveConstructor->isDefaulted() &&
9484 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009485 !MoveConstructor->doesThisDeclarationHaveABody() &&
9486 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009487 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9488
9489 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9490 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9491
Eli Friedman9a14db32012-10-18 20:14:08 +00009492 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009493 DiagnosticErrorTrap Trap(Diags);
9494
David Blaikie93c86172013-01-17 05:26:25 +00009495 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009496 Trap.hasErrorOccurred()) {
9497 Diag(CurrentLocation, diag::note_member_synthesized_at)
9498 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9499 MoveConstructor->setInvalidDecl();
9500 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009501 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009502 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9503 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009504 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009505 /*isStmtExpr=*/false)
9506 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009507 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009508 }
9509
9510 MoveConstructor->setUsed();
9511
9512 if (ASTMutationListener *L = getASTMutationListener()) {
9513 L->CompletedImplicitDefinition(MoveConstructor);
9514 }
9515}
9516
Douglas Gregore4e68d42012-02-15 19:33:52 +00009517bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9518 return FD->isDeleted() &&
9519 (FD->isDefaulted() || FD->isImplicit()) &&
9520 isa<CXXMethodDecl>(FD);
9521}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009522
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009523/// \brief Mark the call operator of the given lambda closure type as "used".
9524static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9525 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009526 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009527 Lambda->lookup(
9528 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009529 CallOperator->setReferenced();
9530 CallOperator->setUsed();
9531}
9532
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009533void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9534 SourceLocation CurrentLocation,
9535 CXXConversionDecl *Conv)
9536{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009537 CXXRecordDecl *Lambda = Conv->getParent();
9538
9539 // Make sure that the lambda call operator is marked used.
9540 markLambdaCallOperatorUsed(*this, Lambda);
9541
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009542 Conv->setUsed();
9543
Eli Friedman9a14db32012-10-18 20:14:08 +00009544 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009545 DiagnosticErrorTrap Trap(Diags);
9546
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009547 // Return the address of the __invoke function.
9548 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9549 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009550 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009551 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9552 VK_LValue, Conv->getLocation()).take();
9553 assert(FunctionRef && "Can't refer to __invoke function?");
9554 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009555 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009556 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009557 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009558
9559 // Fill in the __invoke function with a dummy implementation. IR generation
9560 // will fill in the actual details.
9561 Invoke->setUsed();
9562 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009563 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009564
9565 if (ASTMutationListener *L = getASTMutationListener()) {
9566 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009567 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009568 }
9569}
9570
9571void Sema::DefineImplicitLambdaToBlockPointerConversion(
9572 SourceLocation CurrentLocation,
9573 CXXConversionDecl *Conv)
9574{
9575 Conv->setUsed();
9576
Eli Friedman9a14db32012-10-18 20:14:08 +00009577 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009578 DiagnosticErrorTrap Trap(Diags);
9579
Douglas Gregorac1303e2012-02-22 05:02:47 +00009580 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009581 Expr *This = ActOnCXXThis(CurrentLocation).take();
9582 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009583
Eli Friedman23f02672012-03-01 04:01:32 +00009584 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9585 Conv->getLocation(),
9586 Conv, DerefThis);
9587
9588 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9589 // behavior. Note that only the general conversion function does this
9590 // (since it's unusable otherwise); in the case where we inline the
9591 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009592 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009593 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9594 CK_CopyAndAutoreleaseBlockObject,
9595 BuildBlock.get(), 0, VK_RValue);
9596
9597 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009598 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009599 Conv->setInvalidDecl();
9600 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009601 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009602
Douglas Gregorac1303e2012-02-22 05:02:47 +00009603 // Create the return statement that returns the block from the conversion
9604 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009605 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009606 if (Return.isInvalid()) {
9607 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9608 Conv->setInvalidDecl();
9609 return;
9610 }
9611
9612 // Set the body of the conversion function.
9613 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009614 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009615 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009616 Conv->getLocation()));
9617
Douglas Gregorac1303e2012-02-22 05:02:47 +00009618 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009619 if (ASTMutationListener *L = getASTMutationListener()) {
9620 L->CompletedImplicitDefinition(Conv);
9621 }
9622}
9623
Douglas Gregorf52757d2012-03-10 06:53:13 +00009624/// \brief Determine whether the given list arguments contains exactly one
9625/// "real" (non-default) argument.
9626static bool hasOneRealArgument(MultiExprArg Args) {
9627 switch (Args.size()) {
9628 case 0:
9629 return false;
9630
9631 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009632 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009633 return false;
9634
9635 // fall through
9636 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009637 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009638 }
9639
9640 return false;
9641}
9642
John McCall60d7b3a2010-08-24 06:29:42 +00009643ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009644Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009645 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009646 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009647 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009648 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009649 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009650 unsigned ConstructKind,
9651 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009652 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009653
Douglas Gregor2f599792010-04-02 18:24:57 +00009654 // C++0x [class.copy]p34:
9655 // When certain criteria are met, an implementation is allowed to
9656 // omit the copy/move construction of a class object, even if the
9657 // copy/move constructor and/or destructor for the object have
9658 // side effects. [...]
9659 // - when a temporary class object that has not been bound to a
9660 // reference (12.2) would be copied/moved to a class object
9661 // with the same cv-unqualified type, the copy/move operation
9662 // can be omitted by constructing the temporary object
9663 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009664 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009665 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009666 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009667 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009668 }
Mike Stump1eb44332009-09-09 15:08:12 +00009669
9670 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009671 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009672 IsListInitialization, RequiresZeroInit,
9673 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009674}
9675
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009676/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9677/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009678ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009679Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9680 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009681 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009682 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009683 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009684 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009685 unsigned ConstructKind,
9686 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009687 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009688 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009689 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +00009690 HadMultipleCandidates,
9691 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009692 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9693 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009694}
9695
John McCall68c6c9a2010-02-02 09:10:11 +00009696void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009697 if (VD->isInvalidDecl()) return;
9698
John McCall68c6c9a2010-02-02 09:10:11 +00009699 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009700 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009701 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009702 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009703
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009704 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009705 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009706 CheckDestructorAccess(VD->getLocation(), Destructor,
9707 PDiag(diag::err_access_dtor_var)
9708 << VD->getDeclName()
9709 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009710 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009711
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009712 if (!VD->hasGlobalStorage()) return;
9713
9714 // Emit warning for non-trivial dtor in global scope (a real global,
9715 // class-static, function-static).
9716 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9717
9718 // TODO: this should be re-enabled for static locals by !CXAAtExit
9719 if (!VD->isStaticLocal())
9720 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009721}
9722
Douglas Gregor39da0b82009-09-09 23:08:42 +00009723/// \brief Given a constructor and the set of arguments provided for the
9724/// constructor, convert the arguments and add any required default arguments
9725/// to form a proper call to this constructor.
9726///
9727/// \returns true if an error occurred, false otherwise.
9728bool
9729Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9730 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009731 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009732 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009733 bool AllowExplicit,
9734 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009735 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9736 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009737 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009738
9739 const FunctionProtoType *Proto
9740 = Constructor->getType()->getAs<FunctionProtoType>();
9741 assert(Proto && "Constructor without a prototype?");
9742 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009743
9744 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009745 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009746 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009747 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009748 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009749
9750 VariadicCallType CallType =
9751 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009752 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009753 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9754 Proto, 0, Args, NumArgs, AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009755 CallType, AllowExplicit,
9756 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009757 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009758
9759 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9760
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00009761 CheckConstructorCall(Constructor,
9762 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9763 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +00009764 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009765
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009766 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009767}
9768
Anders Carlsson20d45d22009-12-12 00:32:00 +00009769static inline bool
9770CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9771 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009772 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009773 if (isa<NamespaceDecl>(DC)) {
9774 return SemaRef.Diag(FnDecl->getLocation(),
9775 diag::err_operator_new_delete_declared_in_namespace)
9776 << FnDecl->getDeclName();
9777 }
9778
9779 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009780 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009781 return SemaRef.Diag(FnDecl->getLocation(),
9782 diag::err_operator_new_delete_declared_static)
9783 << FnDecl->getDeclName();
9784 }
9785
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009786 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009787}
9788
Anders Carlsson156c78e2009-12-13 17:53:43 +00009789static inline bool
9790CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9791 CanQualType ExpectedResultType,
9792 CanQualType ExpectedFirstParamType,
9793 unsigned DependentParamTypeDiag,
9794 unsigned InvalidParamTypeDiag) {
9795 QualType ResultType =
9796 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9797
9798 // Check that the result type is not dependent.
9799 if (ResultType->isDependentType())
9800 return SemaRef.Diag(FnDecl->getLocation(),
9801 diag::err_operator_new_delete_dependent_result_type)
9802 << FnDecl->getDeclName() << ExpectedResultType;
9803
9804 // Check that the result type is what we expect.
9805 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9806 return SemaRef.Diag(FnDecl->getLocation(),
9807 diag::err_operator_new_delete_invalid_result_type)
9808 << FnDecl->getDeclName() << ExpectedResultType;
9809
9810 // A function template must have at least 2 parameters.
9811 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9812 return SemaRef.Diag(FnDecl->getLocation(),
9813 diag::err_operator_new_delete_template_too_few_parameters)
9814 << FnDecl->getDeclName();
9815
9816 // The function decl must have at least 1 parameter.
9817 if (FnDecl->getNumParams() == 0)
9818 return SemaRef.Diag(FnDecl->getLocation(),
9819 diag::err_operator_new_delete_too_few_parameters)
9820 << FnDecl->getDeclName();
9821
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009822 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009823 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9824 if (FirstParamType->isDependentType())
9825 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9826 << FnDecl->getDeclName() << ExpectedFirstParamType;
9827
9828 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009829 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009830 ExpectedFirstParamType)
9831 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9832 << FnDecl->getDeclName() << ExpectedFirstParamType;
9833
9834 return false;
9835}
9836
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009837static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009838CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009839 // C++ [basic.stc.dynamic.allocation]p1:
9840 // A program is ill-formed if an allocation function is declared in a
9841 // namespace scope other than global scope or declared static in global
9842 // scope.
9843 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9844 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009845
9846 CanQualType SizeTy =
9847 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9848
9849 // C++ [basic.stc.dynamic.allocation]p1:
9850 // The return type shall be void*. The first parameter shall have type
9851 // std::size_t.
9852 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9853 SizeTy,
9854 diag::err_operator_new_dependent_param_type,
9855 diag::err_operator_new_param_type))
9856 return true;
9857
9858 // C++ [basic.stc.dynamic.allocation]p1:
9859 // The first parameter shall not have an associated default argument.
9860 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009861 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009862 diag::err_operator_new_default_arg)
9863 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9864
9865 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009866}
9867
9868static bool
Richard Smith444d3842012-10-20 08:26:51 +00009869CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009870 // C++ [basic.stc.dynamic.deallocation]p1:
9871 // A program is ill-formed if deallocation functions are declared in a
9872 // namespace scope other than global scope or declared static in global
9873 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009874 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9875 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009876
9877 // C++ [basic.stc.dynamic.deallocation]p2:
9878 // Each deallocation function shall return void and its first parameter
9879 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009880 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9881 SemaRef.Context.VoidPtrTy,
9882 diag::err_operator_delete_dependent_param_type,
9883 diag::err_operator_delete_param_type))
9884 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009885
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009886 return false;
9887}
9888
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009889/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9890/// of this overloaded operator is well-formed. If so, returns false;
9891/// otherwise, emits appropriate diagnostics and returns true.
9892bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009893 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009894 "Expected an overloaded operator declaration");
9895
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009896 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9897
Mike Stump1eb44332009-09-09 15:08:12 +00009898 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009899 // The allocation and deallocation functions, operator new,
9900 // operator new[], operator delete and operator delete[], are
9901 // described completely in 3.7.3. The attributes and restrictions
9902 // found in the rest of this subclause do not apply to them unless
9903 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009904 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009905 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009906
Anders Carlssona3ccda52009-12-12 00:26:23 +00009907 if (Op == OO_New || Op == OO_Array_New)
9908 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009909
9910 // C++ [over.oper]p6:
9911 // An operator function shall either be a non-static member
9912 // function or be a non-member function and have at least one
9913 // parameter whose type is a class, a reference to a class, an
9914 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009915 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9916 if (MethodDecl->isStatic())
9917 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009918 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009919 } else {
9920 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009921 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9922 ParamEnd = FnDecl->param_end();
9923 Param != ParamEnd; ++Param) {
9924 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009925 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9926 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009927 ClassOrEnumParam = true;
9928 break;
9929 }
9930 }
9931
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009932 if (!ClassOrEnumParam)
9933 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009934 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009935 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009936 }
9937
9938 // C++ [over.oper]p8:
9939 // An operator function cannot have default arguments (8.3.6),
9940 // except where explicitly stated below.
9941 //
Mike Stump1eb44332009-09-09 15:08:12 +00009942 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009943 // (C++ [over.call]p1).
9944 if (Op != OO_Call) {
9945 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9946 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009947 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009948 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009949 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009950 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009951 }
9952 }
9953
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009954 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9955 { false, false, false }
9956#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9957 , { Unary, Binary, MemberOnly }
9958#include "clang/Basic/OperatorKinds.def"
9959 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009960
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009961 bool CanBeUnaryOperator = OperatorUses[Op][0];
9962 bool CanBeBinaryOperator = OperatorUses[Op][1];
9963 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009964
9965 // C++ [over.oper]p8:
9966 // [...] Operator functions cannot have more or fewer parameters
9967 // than the number required for the corresponding operator, as
9968 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009969 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009970 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009971 if (Op != OO_Call &&
9972 ((NumParams == 1 && !CanBeUnaryOperator) ||
9973 (NumParams == 2 && !CanBeBinaryOperator) ||
9974 (NumParams < 1) || (NumParams > 2))) {
9975 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009976 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009977 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009978 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009979 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009980 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009981 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009982 assert(CanBeBinaryOperator &&
9983 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009984 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009985 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009986
Chris Lattner416e46f2008-11-21 07:57:12 +00009987 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009988 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009989 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009990
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009991 // Overloaded operators other than operator() cannot be variadic.
9992 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009993 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009994 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009995 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009996 }
9997
9998 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009999 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10000 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010001 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010002 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010003 }
10004
10005 // C++ [over.inc]p1:
10006 // The user-defined function called operator++ implements the
10007 // prefix and postfix ++ operator. If this function is a member
10008 // function with no parameters, or a non-member function with one
10009 // parameter of class or enumeration type, it defines the prefix
10010 // increment operator ++ for objects of that type. If the function
10011 // is a member function with one parameter (which shall be of type
10012 // int) or a non-member function with two parameters (the second
10013 // of which shall be of type int), it defines the postfix
10014 // increment operator ++ for objects of that type.
10015 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10016 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10017 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010018 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010019 ParamIsInt = BT->getKind() == BuiltinType::Int;
10020
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010021 if (!ParamIsInt)
10022 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010023 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010024 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010025 }
10026
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010027 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010028}
Chris Lattner5a003a42008-12-17 07:09:26 +000010029
Sean Hunta6c058d2010-01-13 09:01:02 +000010030/// CheckLiteralOperatorDeclaration - Check whether the declaration
10031/// of this literal operator function is well-formed. If so, returns
10032/// false; otherwise, emits appropriate diagnostics and returns true.
10033bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010034 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010035 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10036 << FnDecl->getDeclName();
10037 return true;
10038 }
10039
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010040 if (FnDecl->isExternC()) {
10041 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10042 return true;
10043 }
10044
Sean Hunta6c058d2010-01-13 09:01:02 +000010045 bool Valid = false;
10046
Richard Smith36f5cfe2012-03-09 08:00:36 +000010047 // This might be the definition of a literal operator template.
10048 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10049 // This might be a specialization of a literal operator template.
10050 if (!TpDecl)
10051 TpDecl = FnDecl->getPrimaryTemplate();
10052
Sean Hunt216c2782010-04-07 23:11:06 +000010053 // template <char...> type operator "" name() is the only valid template
10054 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010055 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010056 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010057 // Must have only one template parameter
10058 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10059 if (Params->size() == 1) {
10060 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010061 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010062
Sean Hunt216c2782010-04-07 23:11:06 +000010063 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010064 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10065 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10066 Valid = true;
10067 }
10068 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010069 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010070 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010071 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10072
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010073 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010074
Sean Hunt30019c02010-04-07 22:57:35 +000010075 // unsigned long long int, long double, and any character type are allowed
10076 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010077 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10078 Context.hasSameType(T, Context.LongDoubleTy) ||
10079 Context.hasSameType(T, Context.CharTy) ||
10080 Context.hasSameType(T, Context.WCharTy) ||
10081 Context.hasSameType(T, Context.Char16Ty) ||
10082 Context.hasSameType(T, Context.Char32Ty)) {
10083 if (++Param == FnDecl->param_end())
10084 Valid = true;
10085 goto FinishedParams;
10086 }
10087
Sean Hunt30019c02010-04-07 22:57:35 +000010088 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010089 const PointerType *PT = T->getAs<PointerType>();
10090 if (!PT)
10091 goto FinishedParams;
10092 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010093 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010094 goto FinishedParams;
10095 T = T.getUnqualifiedType();
10096
10097 // Move on to the second parameter;
10098 ++Param;
10099
10100 // If there is no second parameter, the first must be a const char *
10101 if (Param == FnDecl->param_end()) {
10102 if (Context.hasSameType(T, Context.CharTy))
10103 Valid = true;
10104 goto FinishedParams;
10105 }
10106
10107 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10108 // are allowed as the first parameter to a two-parameter function
10109 if (!(Context.hasSameType(T, Context.CharTy) ||
10110 Context.hasSameType(T, Context.WCharTy) ||
10111 Context.hasSameType(T, Context.Char16Ty) ||
10112 Context.hasSameType(T, Context.Char32Ty)))
10113 goto FinishedParams;
10114
10115 // The second and final parameter must be an std::size_t
10116 T = (*Param)->getType().getUnqualifiedType();
10117 if (Context.hasSameType(T, Context.getSizeType()) &&
10118 ++Param == FnDecl->param_end())
10119 Valid = true;
10120 }
10121
10122 // FIXME: This diagnostic is absolutely terrible.
10123FinishedParams:
10124 if (!Valid) {
10125 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10126 << FnDecl->getDeclName();
10127 return true;
10128 }
10129
Richard Smitha9e88b22012-03-09 08:16:22 +000010130 // A parameter-declaration-clause containing a default argument is not
10131 // equivalent to any of the permitted forms.
10132 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10133 ParamEnd = FnDecl->param_end();
10134 Param != ParamEnd; ++Param) {
10135 if ((*Param)->hasDefaultArg()) {
10136 Diag((*Param)->getDefaultArgRange().getBegin(),
10137 diag::err_literal_operator_default_argument)
10138 << (*Param)->getDefaultArgRange();
10139 break;
10140 }
10141 }
10142
Richard Smith2fb4ae32012-03-08 02:39:21 +000010143 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010144 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10145 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010146 // C++11 [usrlit.suffix]p1:
10147 // Literal suffix identifiers that do not start with an underscore
10148 // are reserved for future standardization.
10149 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010150 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010151
Sean Hunta6c058d2010-01-13 09:01:02 +000010152 return false;
10153}
10154
Douglas Gregor074149e2009-01-05 19:45:36 +000010155/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10156/// linkage specification, including the language and (if present)
10157/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10158/// the location of the language string literal, which is provided
10159/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10160/// the '{' brace. Otherwise, this linkage specification does not
10161/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010162Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10163 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010164 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010165 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010166 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010167 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010168 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010169 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010170 Language = LinkageSpecDecl::lang_cxx;
10171 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010172 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010173 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010174 }
Mike Stump1eb44332009-09-09 15:08:12 +000010175
Chris Lattnercc98eac2008-12-17 07:13:27 +000010176 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010177
Douglas Gregor074149e2009-01-05 19:45:36 +000010178 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010179 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010180 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010181 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010182 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010183}
10184
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010185/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010186/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10187/// valid, it's the position of the closing '}' brace in a linkage
10188/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010189Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010190 Decl *LinkageSpec,
10191 SourceLocation RBraceLoc) {
10192 if (LinkageSpec) {
10193 if (RBraceLoc.isValid()) {
10194 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10195 LSDecl->setRBraceLoc(RBraceLoc);
10196 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010197 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010198 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010199 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010200}
10201
Michael Han684aa732013-02-22 17:15:32 +000010202Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10203 AttributeList *AttrList,
10204 SourceLocation SemiLoc) {
10205 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10206 // Attribute declarations appertain to empty declaration so we handle
10207 // them here.
10208 if (AttrList)
10209 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010210
Michael Han684aa732013-02-22 17:15:32 +000010211 CurContext->addDecl(ED);
10212 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010213}
10214
Douglas Gregord308e622009-05-18 20:51:54 +000010215/// \brief Perform semantic analysis for the variable declaration that
10216/// occurs within a C++ catch clause, returning the newly-created
10217/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010218VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010219 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010220 SourceLocation StartLoc,
10221 SourceLocation Loc,
10222 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010223 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010224 QualType ExDeclType = TInfo->getType();
10225
Sebastian Redl4b07b292008-12-22 19:15:10 +000010226 // Arrays and functions decay.
10227 if (ExDeclType->isArrayType())
10228 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10229 else if (ExDeclType->isFunctionType())
10230 ExDeclType = Context.getPointerType(ExDeclType);
10231
10232 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10233 // The exception-declaration shall not denote a pointer or reference to an
10234 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010235 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010236 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010237 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010238 Invalid = true;
10239 }
Douglas Gregord308e622009-05-18 20:51:54 +000010240
Sebastian Redl4b07b292008-12-22 19:15:10 +000010241 QualType BaseType = ExDeclType;
10242 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010243 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010244 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010245 BaseType = Ptr->getPointeeType();
10246 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010247 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010248 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010249 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010250 BaseType = Ref->getPointeeType();
10251 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010252 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010253 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010254 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010255 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010256 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010257
Mike Stump1eb44332009-09-09 15:08:12 +000010258 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010259 RequireNonAbstractType(Loc, ExDeclType,
10260 diag::err_abstract_type_in_decl,
10261 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010262 Invalid = true;
10263
John McCall5a180392010-07-24 00:37:23 +000010264 // Only the non-fragile NeXT runtime currently supports C++ catches
10265 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010266 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010267 QualType T = ExDeclType;
10268 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10269 T = RT->getPointeeType();
10270
10271 if (T->isObjCObjectType()) {
10272 Diag(Loc, diag::err_objc_object_catch);
10273 Invalid = true;
10274 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010275 // FIXME: should this be a test for macosx-fragile specifically?
10276 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010277 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010278 }
10279 }
10280
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010281 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010282 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010283 ExDecl->setExceptionVariable(true);
10284
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010285 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010286 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010287 Invalid = true;
10288
Douglas Gregorc41b8782011-07-06 18:14:43 +000010289 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010290 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010291 // Insulate this from anything else we might currently be parsing.
10292 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10293
Douglas Gregor6d182892010-03-05 23:38:39 +000010294 // C++ [except.handle]p16:
10295 // The object declared in an exception-declaration or, if the
10296 // exception-declaration does not specify a name, a temporary (12.2) is
10297 // copy-initialized (8.5) from the exception object. [...]
10298 // The object is destroyed when the handler exits, after the destruction
10299 // of any automatic objects initialized within the handler.
10300 //
10301 // We just pretend to initialize the object with itself, then make sure
10302 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010303 QualType initType = ExDeclType;
10304
10305 InitializedEntity entity =
10306 InitializedEntity::InitializeVariable(ExDecl);
10307 InitializationKind initKind =
10308 InitializationKind::CreateCopy(Loc, SourceLocation());
10309
10310 Expr *opaqueValue =
10311 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10312 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10313 ExprResult result = sequence.Perform(*this, entity, initKind,
10314 MultiExprArg(&opaqueValue, 1));
10315 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010316 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010317 else {
10318 // If the constructor used was non-trivial, set this as the
10319 // "initializer".
10320 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10321 if (!construct->getConstructor()->isTrivial()) {
10322 Expr *init = MaybeCreateExprWithCleanups(construct);
10323 ExDecl->setInit(init);
10324 }
10325
10326 // And make sure it's destructable.
10327 FinalizeVarWithDestructor(ExDecl, recordType);
10328 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010329 }
10330 }
10331
Douglas Gregord308e622009-05-18 20:51:54 +000010332 if (Invalid)
10333 ExDecl->setInvalidDecl();
10334
10335 return ExDecl;
10336}
10337
10338/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10339/// handler.
John McCalld226f652010-08-21 09:40:31 +000010340Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010341 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010342 bool Invalid = D.isInvalidType();
10343
10344 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010345 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10346 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010347 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10348 D.getIdentifierLoc());
10349 Invalid = true;
10350 }
10351
Sebastian Redl4b07b292008-12-22 19:15:10 +000010352 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010353 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010354 LookupOrdinaryName,
10355 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010356 // The scope should be freshly made just for us. There is just no way
10357 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010358 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010359 if (PrevDecl->isTemplateParameter()) {
10360 // Maybe we will complain about the shadowed template parameter.
10361 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010362 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010363 }
10364 }
10365
Chris Lattnereaaebc72009-04-25 08:06:05 +000010366 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010367 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10368 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010369 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010370 }
10371
Douglas Gregor83cb9422010-09-09 17:09:21 +000010372 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010373 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010374 D.getIdentifierLoc(),
10375 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010376 if (Invalid)
10377 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010378
Sebastian Redl4b07b292008-12-22 19:15:10 +000010379 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010380 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010381 PushOnScopeChains(ExDecl, S);
10382 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010383 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010384
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010385 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010386 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010387}
Anders Carlssonfb311762009-03-14 00:25:26 +000010388
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010389Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010390 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010391 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010392 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010393 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010394
Richard Smithe3f470a2012-07-11 22:37:56 +000010395 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10396 return 0;
10397
10398 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10399 AssertMessage, RParenLoc, false);
10400}
10401
10402Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10403 Expr *AssertExpr,
10404 StringLiteral *AssertMessage,
10405 SourceLocation RParenLoc,
10406 bool Failed) {
10407 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10408 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010409 // In a static_assert-declaration, the constant-expression shall be a
10410 // constant expression that can be contextually converted to bool.
10411 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10412 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010413 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010414
Richard Smithdaaefc52011-12-14 23:32:26 +000010415 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010416 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010417 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010418 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010419 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010420
Richard Smithe3f470a2012-07-11 22:37:56 +000010421 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010422 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010423 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010424 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010425 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010426 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010427 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010428 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010429 }
Mike Stump1eb44332009-09-09 15:08:12 +000010430
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010431 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010432 AssertExpr, AssertMessage, RParenLoc,
10433 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010434
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010435 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010436 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010437}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010438
Douglas Gregor1d869352010-04-07 16:53:43 +000010439/// \brief Perform semantic analysis of the given friend type declaration.
10440///
10441/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010442FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010443 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010444 TypeSourceInfo *TSInfo) {
10445 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10446
10447 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010448 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010449
Richard Smith6b130222011-10-18 21:39:00 +000010450 // C++03 [class.friend]p2:
10451 // An elaborated-type-specifier shall be used in a friend declaration
10452 // for a class.*
10453 //
10454 // * The class-key of the elaborated-type-specifier is required.
10455 if (!ActiveTemplateInstantiations.empty()) {
10456 // Do not complain about the form of friend template types during
10457 // template instantiation; we will already have complained when the
10458 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010459 } else {
10460 if (!T->isElaboratedTypeSpecifier()) {
10461 // If we evaluated the type to a record type, suggest putting
10462 // a tag in front.
10463 if (const RecordType *RT = T->getAs<RecordType>()) {
10464 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010465
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010466 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010467
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010468 Diag(TypeRange.getBegin(),
10469 getLangOpts().CPlusPlus11 ?
10470 diag::warn_cxx98_compat_unelaborated_friend_type :
10471 diag::ext_unelaborated_friend_type)
10472 << (unsigned) RD->getTagKind()
10473 << T
10474 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10475 InsertionText);
10476 } else {
10477 Diag(FriendLoc,
10478 getLangOpts().CPlusPlus11 ?
10479 diag::warn_cxx98_compat_nonclass_type_friend :
10480 diag::ext_nonclass_type_friend)
10481 << T
10482 << TypeRange;
10483 }
10484 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010485 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010486 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010487 diag::warn_cxx98_compat_enum_friend :
10488 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010489 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010490 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010491 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010492
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010493 // C++11 [class.friend]p3:
10494 // A friend declaration that does not declare a function shall have one
10495 // of the following forms:
10496 // friend elaborated-type-specifier ;
10497 // friend simple-type-specifier ;
10498 // friend typename-specifier ;
10499 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10500 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10501 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010502
Douglas Gregor06245bf2010-04-07 17:57:12 +000010503 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010504 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010505 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010506 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010507}
10508
John McCall9a34edb2010-10-19 01:40:49 +000010509/// Handle a friend tag declaration where the scope specifier was
10510/// templated.
10511Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10512 unsigned TagSpec, SourceLocation TagLoc,
10513 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010514 IdentifierInfo *Name,
10515 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010516 AttributeList *Attr,
10517 MultiTemplateParamsArg TempParamLists) {
10518 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10519
10520 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010521 bool Invalid = false;
10522
10523 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010524 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010525 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010526 TempParamLists.size(),
10527 /*friend*/ true,
10528 isExplicitSpecialization,
10529 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010530 if (TemplateParams->size() > 0) {
10531 // This is a declaration of a class template.
10532 if (Invalid)
10533 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010534
Eric Christopher4110e132011-07-21 05:34:24 +000010535 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10536 SS, Name, NameLoc, Attr,
10537 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010538 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010539 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010540 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010541 } else {
10542 // The "template<>" header is extraneous.
10543 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10544 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10545 isExplicitSpecialization = true;
10546 }
10547 }
10548
10549 if (Invalid) return 0;
10550
John McCall9a34edb2010-10-19 01:40:49 +000010551 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010552 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010553 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010554 isAllExplicitSpecializations = false;
10555 break;
10556 }
10557 }
10558
10559 // FIXME: don't ignore attributes.
10560
10561 // If it's explicit specializations all the way down, just forget
10562 // about the template header and build an appropriate non-templated
10563 // friend. TODO: for source fidelity, remember the headers.
10564 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010565 if (SS.isEmpty()) {
10566 bool Owned = false;
10567 bool IsDependent = false;
10568 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10569 Attr, AS_public,
10570 /*ModulePrivateLoc=*/SourceLocation(),
10571 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010572 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010573 /*ScopedEnumUsesClassTag=*/false,
10574 /*UnderlyingType=*/TypeResult());
10575 }
10576
Douglas Gregor2494dd02011-03-01 01:34:45 +000010577 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010578 ElaboratedTypeKeyword Keyword
10579 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010580 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010581 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010582 if (T.isNull())
10583 return 0;
10584
10585 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10586 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010587 DependentNameTypeLoc TL =
10588 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010589 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010590 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010591 TL.setNameLoc(NameLoc);
10592 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010593 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010594 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010595 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010596 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010597 }
10598
10599 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010600 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010601 Friend->setAccess(AS_public);
10602 CurContext->addDecl(Friend);
10603 return Friend;
10604 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010605
10606 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10607
10608
John McCall9a34edb2010-10-19 01:40:49 +000010609
10610 // Handle the case of a templated-scope friend class. e.g.
10611 // template <class T> class A<T>::B;
10612 // FIXME: we don't support these right now.
10613 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10614 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10615 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000010616 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010617 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010618 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010619 TL.setNameLoc(NameLoc);
10620
10621 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010622 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010623 Friend->setAccess(AS_public);
10624 Friend->setUnsupportedFriend(true);
10625 CurContext->addDecl(Friend);
10626 return Friend;
10627}
10628
10629
John McCalldd4a3b02009-09-16 22:47:08 +000010630/// Handle a friend type declaration. This works in tandem with
10631/// ActOnTag.
10632///
10633/// Notes on friend class templates:
10634///
10635/// We generally treat friend class declarations as if they were
10636/// declaring a class. So, for example, the elaborated type specifier
10637/// in a friend declaration is required to obey the restrictions of a
10638/// class-head (i.e. no typedefs in the scope chain), template
10639/// parameters are required to match up with simple template-ids, &c.
10640/// However, unlike when declaring a template specialization, it's
10641/// okay to refer to a template specialization without an empty
10642/// template parameter declaration, e.g.
10643/// friend class A<T>::B<unsigned>;
10644/// We permit this as a special case; if there are any template
10645/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010646/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010647Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010648 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010649 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010650
10651 assert(DS.isFriendSpecified());
10652 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10653
John McCalldd4a3b02009-09-16 22:47:08 +000010654 // Try to convert the decl specifier to a type. This works for
10655 // friend templates because ActOnTag never produces a ClassTemplateDecl
10656 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010657 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010658 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10659 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010660 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010661 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010662
Douglas Gregor6ccab972010-12-16 01:14:37 +000010663 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10664 return 0;
10665
John McCalldd4a3b02009-09-16 22:47:08 +000010666 // This is definitely an error in C++98. It's probably meant to
10667 // be forbidden in C++0x, too, but the specification is just
10668 // poorly written.
10669 //
10670 // The problem is with declarations like the following:
10671 // template <T> friend A<T>::foo;
10672 // where deciding whether a class C is a friend or not now hinges
10673 // on whether there exists an instantiation of A that causes
10674 // 'foo' to equal C. There are restrictions on class-heads
10675 // (which we declare (by fiat) elaborated friend declarations to
10676 // be) that makes this tractable.
10677 //
10678 // FIXME: handle "template <> friend class A<T>;", which
10679 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010680 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010681 Diag(Loc, diag::err_tagless_friend_type_template)
10682 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010683 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010684 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010685
John McCall02cace72009-08-28 07:59:38 +000010686 // C++98 [class.friend]p1: A friend of a class is a function
10687 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010688 // This is fixed in DR77, which just barely didn't make the C++03
10689 // deadline. It's also a very silly restriction that seriously
10690 // affects inner classes and which nobody else seems to implement;
10691 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010692 //
10693 // But note that we could warn about it: it's always useless to
10694 // friend one of your own members (it's not, however, worthless to
10695 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010696
John McCalldd4a3b02009-09-16 22:47:08 +000010697 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010698 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010699 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010700 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010701 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010702 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010703 DS.getFriendSpecLoc());
10704 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010705 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010706
10707 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010708 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010709
John McCalldd4a3b02009-09-16 22:47:08 +000010710 D->setAccess(AS_public);
10711 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010712
John McCalld226f652010-08-21 09:40:31 +000010713 return D;
John McCall02cace72009-08-28 07:59:38 +000010714}
10715
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000010716NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10717 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010718 const DeclSpec &DS = D.getDeclSpec();
10719
10720 assert(DS.isFriendSpecified());
10721 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10722
10723 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010724 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010725
10726 // C++ [class.friend]p1
10727 // A friend of a class is a function or class....
10728 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010729 // It *doesn't* see through dependent types, which is correct
10730 // according to [temp.arg.type]p3:
10731 // If a declaration acquires a function type through a
10732 // type dependent on a template-parameter and this causes
10733 // a declaration that does not use the syntactic form of a
10734 // function declarator to have a function type, the program
10735 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010736 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010737 Diag(Loc, diag::err_unexpected_friend);
10738
10739 // It might be worthwhile to try to recover by creating an
10740 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010741 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010742 }
10743
10744 // C++ [namespace.memdef]p3
10745 // - If a friend declaration in a non-local class first declares a
10746 // class or function, the friend class or function is a member
10747 // of the innermost enclosing namespace.
10748 // - The name of the friend is not found by simple name lookup
10749 // until a matching declaration is provided in that namespace
10750 // scope (either before or after the class declaration granting
10751 // friendship).
10752 // - If a friend function is called, its name may be found by the
10753 // name lookup that considers functions from namespaces and
10754 // classes associated with the types of the function arguments.
10755 // - When looking for a prior declaration of a class or a function
10756 // declared as a friend, scopes outside the innermost enclosing
10757 // namespace scope are not considered.
10758
John McCall337ec3d2010-10-12 23:13:28 +000010759 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010760 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10761 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010762 assert(Name);
10763
Douglas Gregor6ccab972010-12-16 01:14:37 +000010764 // Check for unexpanded parameter packs.
10765 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10766 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10767 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10768 return 0;
10769
John McCall67d1a672009-08-06 02:15:43 +000010770 // The context we found the declaration in, or in which we should
10771 // create the declaration.
10772 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010773 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010774 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010775 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010776
John McCall337ec3d2010-10-12 23:13:28 +000010777 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010778
John McCall337ec3d2010-10-12 23:13:28 +000010779 // There are four cases here.
10780 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010781 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010782 // there as appropriate.
10783 // Recover from invalid scope qualifiers as if they just weren't there.
10784 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010785 // C++0x [namespace.memdef]p3:
10786 // If the name in a friend declaration is neither qualified nor
10787 // a template-id and the declaration is a function or an
10788 // elaborated-type-specifier, the lookup to determine whether
10789 // the entity has been previously declared shall not consider
10790 // any scopes outside the innermost enclosing namespace.
10791 // C++0x [class.friend]p11:
10792 // If a friend declaration appears in a local class and the name
10793 // specified is an unqualified name, a prior declaration is
10794 // looked up without considering scopes that are outside the
10795 // innermost enclosing non-class scope. For a friend function
10796 // declaration, if there is no prior declaration, the program is
10797 // ill-formed.
10798 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010799 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010800
John McCall29ae6e52010-10-13 05:45:15 +000010801 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010802 DC = CurContext;
10803 while (true) {
10804 // Skip class contexts. If someone can cite chapter and verse
10805 // for this behavior, that would be nice --- it's what GCC and
10806 // EDG do, and it seems like a reasonable intent, but the spec
10807 // really only says that checks for unqualified existing
10808 // declarations should stop at the nearest enclosing namespace,
10809 // not that they should only consider the nearest enclosing
10810 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010811 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010812 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010813
John McCall68263142009-11-18 22:49:29 +000010814 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010815
10816 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010817 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010818 break;
John McCall29ae6e52010-10-13 05:45:15 +000010819
John McCall8a407372010-10-14 22:22:28 +000010820 if (isTemplateId) {
10821 if (isa<TranslationUnitDecl>(DC)) break;
10822 } else {
10823 if (DC->isFileContext()) break;
10824 }
John McCall67d1a672009-08-06 02:15:43 +000010825 DC = DC->getParent();
10826 }
10827
John McCall380aaa42010-10-13 06:22:15 +000010828 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010829
Douglas Gregor883af832011-10-10 01:11:59 +000010830 // C++ [class.friend]p6:
10831 // A function can be defined in a friend declaration of a class if and
10832 // only if the class is a non-local class (9.8), the function name is
10833 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010834 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010835 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10836 }
10837
John McCall337ec3d2010-10-12 23:13:28 +000010838 // - There's a non-dependent scope specifier, in which case we
10839 // compute it and do a previous lookup there for a function
10840 // or function template.
10841 } else if (!SS.getScopeRep()->isDependent()) {
10842 DC = computeDeclContext(SS);
10843 if (!DC) return 0;
10844
10845 if (RequireCompleteDeclContext(SS, DC)) return 0;
10846
10847 LookupQualifiedName(Previous, DC);
10848
10849 // Ignore things found implicitly in the wrong scope.
10850 // TODO: better diagnostics for this case. Suggesting the right
10851 // qualified scope would be nice...
10852 LookupResult::Filter F = Previous.makeFilter();
10853 while (F.hasNext()) {
10854 NamedDecl *D = F.next();
10855 if (!DC->InEnclosingNamespaceSetOf(
10856 D->getDeclContext()->getRedeclContext()))
10857 F.erase();
10858 }
10859 F.done();
10860
10861 if (Previous.empty()) {
10862 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010863 Diag(Loc, diag::err_qualified_friend_not_found)
10864 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010865 return 0;
10866 }
10867
10868 // C++ [class.friend]p1: A friend of a class is a function or
10869 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010870 if (DC->Equals(CurContext))
10871 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010872 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010873 diag::warn_cxx98_compat_friend_is_member :
10874 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010875
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010876 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010877 // C++ [class.friend]p6:
10878 // A function can be defined in a friend declaration of a class if and
10879 // only if the class is a non-local class (9.8), the function name is
10880 // unqualified, and the function has namespace scope.
10881 SemaDiagnosticBuilder DB
10882 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10883
10884 DB << SS.getScopeRep();
10885 if (DC->isFileContext())
10886 DB << FixItHint::CreateRemoval(SS.getRange());
10887 SS.clear();
10888 }
John McCall337ec3d2010-10-12 23:13:28 +000010889
10890 // - There's a scope specifier that does not match any template
10891 // parameter lists, in which case we use some arbitrary context,
10892 // create a method or method template, and wait for instantiation.
10893 // - There's a scope specifier that does match some template
10894 // parameter lists, which we don't handle right now.
10895 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010896 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010897 // C++ [class.friend]p6:
10898 // A function can be defined in a friend declaration of a class if and
10899 // only if the class is a non-local class (9.8), the function name is
10900 // unqualified, and the function has namespace scope.
10901 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10902 << SS.getScopeRep();
10903 }
10904
John McCall337ec3d2010-10-12 23:13:28 +000010905 DC = CurContext;
10906 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010907 }
Douglas Gregor883af832011-10-10 01:11:59 +000010908
John McCall29ae6e52010-10-13 05:45:15 +000010909 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010910 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010911 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10912 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10913 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010914 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010915 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10916 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010917 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010918 }
John McCall67d1a672009-08-06 02:15:43 +000010919 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010920
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010921 // FIXME: This is an egregious hack to cope with cases where the scope stack
10922 // does not contain the declaration context, i.e., in an out-of-line
10923 // definition of a class.
10924 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10925 if (!DCScope) {
10926 FakeDCScope.setEntity(DC);
10927 DCScope = &FakeDCScope;
10928 }
10929
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010930 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010931 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010932 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010933 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010934
Douglas Gregor182ddf02009-09-28 00:08:27 +000010935 assert(ND->getDeclContext() == DC);
10936 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010937
John McCallab88d972009-08-31 22:39:49 +000010938 // Add the function declaration to the appropriate lookup tables,
10939 // adjusting the redeclarations list as necessary. We don't
10940 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010941 //
John McCallab88d972009-08-31 22:39:49 +000010942 // Also update the scope-based lookup if the target context's
10943 // lookup context is in lexical scope.
10944 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010945 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010946 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010947 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010948 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010949 }
John McCall02cace72009-08-28 07:59:38 +000010950
10951 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010952 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010953 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010954 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010955 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010956
John McCall1f2e1a92012-08-10 03:15:35 +000010957 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010958 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010959 } else {
10960 if (DC->isRecord()) CheckFriendAccess(ND);
10961
John McCall6102ca12010-10-16 06:59:13 +000010962 FunctionDecl *FD;
10963 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10964 FD = FTD->getTemplatedDecl();
10965 else
10966 FD = cast<FunctionDecl>(ND);
10967
10968 // Mark templated-scope function declarations as unsupported.
10969 if (FD->getNumTemplateParameterLists())
10970 FrD->setUnsupportedFriend(true);
10971 }
John McCall337ec3d2010-10-12 23:13:28 +000010972
John McCalld226f652010-08-21 09:40:31 +000010973 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010974}
10975
John McCalld226f652010-08-21 09:40:31 +000010976void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10977 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010978
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000010979 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000010980 if (!Fn) {
10981 Diag(DelLoc, diag::err_deleted_non_function);
10982 return;
10983 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000010984
Douglas Gregoref96ee02012-01-14 16:38:05 +000010985 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010986 // Don't consider the implicit declaration we generate for explicit
10987 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010988 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10989 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010990 Diag(DelLoc, diag::err_deleted_decl_not_first);
10991 Diag(Prev->getLocation(), diag::note_previous_declaration);
10992 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010993 // If the declaration wasn't the first, we delete the function anyway for
10994 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000010995 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010996 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000010997
10998 if (Fn->isDeleted())
10999 return;
11000
11001 // See if we're deleting a function which is already known to override a
11002 // non-deleted virtual function.
11003 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11004 bool IssuedDiagnostic = false;
11005 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11006 E = MD->end_overridden_methods();
11007 I != E; ++I) {
11008 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11009 if (!IssuedDiagnostic) {
11010 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11011 IssuedDiagnostic = true;
11012 }
11013 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11014 }
11015 }
11016 }
11017
Sean Hunt10620eb2011-05-06 20:44:56 +000011018 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011019}
Sebastian Redl13e88542009-04-27 21:33:24 +000011020
Sean Hunte4246a62011-05-12 06:15:49 +000011021void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011022 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011023
11024 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011025 if (MD->getParent()->isDependentType()) {
11026 MD->setDefaulted();
11027 MD->setExplicitlyDefaulted();
11028 return;
11029 }
11030
Sean Hunte4246a62011-05-12 06:15:49 +000011031 CXXSpecialMember Member = getSpecialMember(MD);
11032 if (Member == CXXInvalid) {
11033 Diag(DefaultLoc, diag::err_default_special_members);
11034 return;
11035 }
11036
11037 MD->setDefaulted();
11038 MD->setExplicitlyDefaulted();
11039
Sean Huntcd10dec2011-05-23 23:14:04 +000011040 // If this definition appears within the record, do the checking when
11041 // the record is complete.
11042 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011043 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011044 // Find the uninstantiated declaration that actually had the '= default'
11045 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011046 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011047
Richard Smith12fef492013-03-27 00:22:47 +000011048 // If the method was defaulted on its first declaration, we will have
11049 // already performed the checking in CheckCompletedCXXClass. Such a
11050 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011051 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011052 return;
11053
Richard Smithb9d0b762012-07-27 04:22:15 +000011054 CheckExplicitlyDefaultedSpecialMember(MD);
11055
Richard Smith1d28caf2012-12-11 01:14:52 +000011056 // The exception specification is needed because we are defining the
11057 // function.
11058 ResolveExceptionSpec(DefaultLoc,
11059 MD->getType()->castAs<FunctionProtoType>());
11060
Sean Hunte4246a62011-05-12 06:15:49 +000011061 switch (Member) {
11062 case CXXDefaultConstructor: {
11063 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011064 if (!CD->isInvalidDecl())
11065 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11066 break;
11067 }
11068
11069 case CXXCopyConstructor: {
11070 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011071 if (!CD->isInvalidDecl())
11072 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011073 break;
11074 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011075
Sean Hunt2b188082011-05-14 05:23:28 +000011076 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011077 if (!MD->isInvalidDecl())
11078 DefineImplicitCopyAssignment(DefaultLoc, MD);
11079 break;
11080 }
11081
Sean Huntcb45a0f2011-05-12 22:46:25 +000011082 case CXXDestructor: {
11083 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011084 if (!DD->isInvalidDecl())
11085 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011086 break;
11087 }
11088
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011089 case CXXMoveConstructor: {
11090 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011091 if (!CD->isInvalidDecl())
11092 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011093 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011094 }
Sean Hunt82713172011-05-25 23:16:36 +000011095
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011096 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011097 if (!MD->isInvalidDecl())
11098 DefineImplicitMoveAssignment(DefaultLoc, MD);
11099 break;
11100 }
11101
11102 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011103 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011104 }
11105 } else {
11106 Diag(DefaultLoc, diag::err_default_special_members);
11107 }
11108}
11109
Sebastian Redl13e88542009-04-27 21:33:24 +000011110static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011111 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011112 Stmt *SubStmt = *CI;
11113 if (!SubStmt)
11114 continue;
11115 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011116 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011117 diag::err_return_in_constructor_handler);
11118 if (!isa<Expr>(SubStmt))
11119 SearchForReturnInStmt(Self, SubStmt);
11120 }
11121}
11122
11123void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11124 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11125 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11126 SearchForReturnInStmt(*this, Handler);
11127 }
11128}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011129
David Blaikie299adab2013-01-18 23:03:15 +000011130bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011131 const CXXMethodDecl *Old) {
11132 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11133 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11134
11135 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11136
11137 // If the calling conventions match, everything is fine
11138 if (NewCC == OldCC)
11139 return false;
11140
11141 // If either of the calling conventions are set to "default", we need to pick
11142 // something more sensible based on the target. This supports code where the
11143 // one method explicitly sets thiscall, and another has no explicit calling
11144 // convention.
11145 CallingConv Default =
11146 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11147 if (NewCC == CC_Default)
11148 NewCC = Default;
11149 if (OldCC == CC_Default)
11150 OldCC = Default;
11151
11152 // If the calling conventions still don't match, then report the error
11153 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011154 Diag(New->getLocation(),
11155 diag::err_conflicting_overriding_cc_attributes)
11156 << New->getDeclName() << New->getType() << Old->getType();
11157 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11158 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011159 }
11160
11161 return false;
11162}
11163
Mike Stump1eb44332009-09-09 15:08:12 +000011164bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011165 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011166 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11167 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011168
Chandler Carruth73857792010-02-15 11:53:20 +000011169 if (Context.hasSameType(NewTy, OldTy) ||
11170 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011171 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011172
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011173 // Check if the return types are covariant
11174 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011175
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011176 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011177 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11178 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011179 NewClassTy = NewPT->getPointeeType();
11180 OldClassTy = OldPT->getPointeeType();
11181 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011182 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11183 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11184 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11185 NewClassTy = NewRT->getPointeeType();
11186 OldClassTy = OldRT->getPointeeType();
11187 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011188 }
11189 }
Mike Stump1eb44332009-09-09 15:08:12 +000011190
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011191 // The return types aren't either both pointers or references to a class type.
11192 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011193 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011194 diag::err_different_return_type_for_overriding_virtual_function)
11195 << New->getDeclName() << NewTy << OldTy;
11196 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011197
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011198 return true;
11199 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011200
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011201 // C++ [class.virtual]p6:
11202 // If the return type of D::f differs from the return type of B::f, the
11203 // class type in the return type of D::f shall be complete at the point of
11204 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011205 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11206 if (!RT->isBeingDefined() &&
11207 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011208 diag::err_covariant_return_incomplete,
11209 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011210 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011211 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011212
Douglas Gregora4923eb2009-11-16 21:35:15 +000011213 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011214 // Check if the new class derives from the old class.
11215 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11216 Diag(New->getLocation(),
11217 diag::err_covariant_return_not_derived)
11218 << New->getDeclName() << NewTy << OldTy;
11219 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11220 return true;
11221 }
Mike Stump1eb44332009-09-09 15:08:12 +000011222
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011223 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011224 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011225 diag::err_covariant_return_inaccessible_base,
11226 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11227 // FIXME: Should this point to the return type?
11228 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011229 // FIXME: this note won't trigger for delayed access control
11230 // diagnostics, and it's impossible to get an undelayed error
11231 // here from access control during the original parse because
11232 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011233 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11234 return true;
11235 }
11236 }
Mike Stump1eb44332009-09-09 15:08:12 +000011237
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011238 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011239 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011240 Diag(New->getLocation(),
11241 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011242 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011243 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11244 return true;
11245 };
Mike Stump1eb44332009-09-09 15:08:12 +000011246
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011247
11248 // The new class type must have the same or less qualifiers as the old type.
11249 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11250 Diag(New->getLocation(),
11251 diag::err_covariant_return_type_class_type_more_qualified)
11252 << New->getDeclName() << NewTy << OldTy;
11253 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11254 return true;
11255 };
Mike Stump1eb44332009-09-09 15:08:12 +000011256
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011257 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011258}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011259
Douglas Gregor4ba31362009-12-01 17:24:26 +000011260/// \brief Mark the given method pure.
11261///
11262/// \param Method the method to be marked pure.
11263///
11264/// \param InitRange the source range that covers the "0" initializer.
11265bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011266 SourceLocation EndLoc = InitRange.getEnd();
11267 if (EndLoc.isValid())
11268 Method->setRangeEnd(EndLoc);
11269
Douglas Gregor4ba31362009-12-01 17:24:26 +000011270 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11271 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011272 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011273 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011274
11275 if (!Method->isInvalidDecl())
11276 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11277 << Method->getDeclName() << InitRange;
11278 return true;
11279}
11280
Douglas Gregor552e2992012-02-21 02:22:07 +000011281/// \brief Determine whether the given declaration is a static data member.
11282static bool isStaticDataMember(Decl *D) {
11283 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11284 if (!Var)
11285 return false;
11286
11287 return Var->isStaticDataMember();
11288}
John McCall731ad842009-12-19 09:28:58 +000011289/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11290/// an initializer for the out-of-line declaration 'Dcl'. The scope
11291/// is a fresh scope pushed for just this purpose.
11292///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011293/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11294/// static data member of class X, names should be looked up in the scope of
11295/// class X.
John McCalld226f652010-08-21 09:40:31 +000011296void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011297 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011298 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011299
John McCall731ad842009-12-19 09:28:58 +000011300 // We should only get called for declarations with scope specifiers, like:
11301 // int foo::bar;
11302 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011303 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011304
11305 // If we are parsing the initializer for a static data member, push a
11306 // new expression evaluation context that is associated with this static
11307 // data member.
11308 if (isStaticDataMember(D))
11309 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011310}
11311
11312/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011313/// initializer for the out-of-line declaration 'D'.
11314void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011315 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011316 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011317
Douglas Gregor552e2992012-02-21 02:22:07 +000011318 if (isStaticDataMember(D))
11319 PopExpressionEvaluationContext();
11320
John McCall731ad842009-12-19 09:28:58 +000011321 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011322 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011323}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011324
11325/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11326/// C++ if/switch/while/for statement.
11327/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011328DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011329 // C++ 6.4p2:
11330 // The declarator shall not specify a function or an array.
11331 // The type-specifier-seq shall not contain typedef and shall not declare a
11332 // new class or enumeration.
11333 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11334 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011335
11336 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011337 if (!Dcl)
11338 return true;
11339
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011340 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11341 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011342 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011343 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011344 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011345
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011346 return Dcl;
11347}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011348
Douglas Gregordfe65432011-07-28 19:11:31 +000011349void Sema::LoadExternalVTableUses() {
11350 if (!ExternalSource)
11351 return;
11352
11353 SmallVector<ExternalVTableUse, 4> VTables;
11354 ExternalSource->ReadUsedVTables(VTables);
11355 SmallVector<VTableUse, 4> NewUses;
11356 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11357 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11358 = VTablesUsed.find(VTables[I].Record);
11359 // Even if a definition wasn't required before, it may be required now.
11360 if (Pos != VTablesUsed.end()) {
11361 if (!Pos->second && VTables[I].DefinitionRequired)
11362 Pos->second = true;
11363 continue;
11364 }
11365
11366 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11367 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11368 }
11369
11370 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11371}
11372
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011373void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11374 bool DefinitionRequired) {
11375 // Ignore any vtable uses in unevaluated operands or for classes that do
11376 // not have a vtable.
11377 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11378 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011379 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011380 return;
11381
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011382 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011383 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011384 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11385 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11386 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11387 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011388 // If we already had an entry, check to see if we are promoting this vtable
11389 // to required a definition. If so, we need to reappend to the VTableUses
11390 // list, since we may have already processed the first entry.
11391 if (DefinitionRequired && !Pos.first->second) {
11392 Pos.first->second = true;
11393 } else {
11394 // Otherwise, we can early exit.
11395 return;
11396 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011397 }
11398
11399 // Local classes need to have their virtual members marked
11400 // immediately. For all other classes, we mark their virtual members
11401 // at the end of the translation unit.
11402 if (Class->isLocalClass())
11403 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011404 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011405 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011406}
11407
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011408bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011409 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011410 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011411 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011412
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011413 // Note: The VTableUses vector could grow as a result of marking
11414 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011415 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011416 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011417 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011418 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011419 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011420 if (!Class)
11421 continue;
11422
11423 SourceLocation Loc = VTableUses[I].second;
11424
Richard Smithb9d0b762012-07-27 04:22:15 +000011425 bool DefineVTable = true;
11426
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011427 // If this class has a key function, but that key function is
11428 // defined in another translation unit, we don't need to emit the
11429 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011430 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011431 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011432 switch (KeyFunction->getTemplateSpecializationKind()) {
11433 case TSK_Undeclared:
11434 case TSK_ExplicitSpecialization:
11435 case TSK_ExplicitInstantiationDeclaration:
11436 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011437 DefineVTable = false;
11438 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011439
11440 case TSK_ExplicitInstantiationDefinition:
11441 case TSK_ImplicitInstantiation:
11442 // We will be instantiating the key function.
11443 break;
11444 }
11445 } else if (!KeyFunction) {
11446 // If we have a class with no key function that is the subject
11447 // of an explicit instantiation declaration, suppress the
11448 // vtable; it will live with the explicit instantiation
11449 // definition.
11450 bool IsExplicitInstantiationDeclaration
11451 = Class->getTemplateSpecializationKind()
11452 == TSK_ExplicitInstantiationDeclaration;
11453 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11454 REnd = Class->redecls_end();
11455 R != REnd; ++R) {
11456 TemplateSpecializationKind TSK
11457 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11458 if (TSK == TSK_ExplicitInstantiationDeclaration)
11459 IsExplicitInstantiationDeclaration = true;
11460 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11461 IsExplicitInstantiationDeclaration = false;
11462 break;
11463 }
11464 }
11465
11466 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011467 DefineVTable = false;
11468 }
11469
11470 // The exception specifications for all virtual members may be needed even
11471 // if we are not providing an authoritative form of the vtable in this TU.
11472 // We may choose to emit it available_externally anyway.
11473 if (!DefineVTable) {
11474 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11475 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011476 }
11477
11478 // Mark all of the virtual members of this class as referenced, so
11479 // that we can build a vtable. Then, tell the AST consumer that a
11480 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011481 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011482 MarkVirtualMembersReferenced(Loc, Class);
11483 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11484 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11485
11486 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola531db822013-03-07 02:00:27 +000011487 if (Class->hasExternalLinkage() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011488 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011489 const FunctionDecl *KeyFunctionDef = 0;
11490 if (!KeyFunction ||
11491 (KeyFunction->hasBody(KeyFunctionDef) &&
11492 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011493 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11494 TSK_ExplicitInstantiationDefinition
11495 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11496 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011497 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011498 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011499 VTableUses.clear();
11500
Douglas Gregor78844032011-04-22 22:25:37 +000011501 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011502}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011503
Richard Smithb9d0b762012-07-27 04:22:15 +000011504void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11505 const CXXRecordDecl *RD) {
11506 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11507 E = RD->method_end(); I != E; ++I)
11508 if ((*I)->isVirtual() && !(*I)->isPure())
11509 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11510}
11511
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011512void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11513 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011514 // Mark all functions which will appear in RD's vtable as used.
11515 CXXFinalOverriderMap FinalOverriders;
11516 RD->getFinalOverriders(FinalOverriders);
11517 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11518 E = FinalOverriders.end();
11519 I != E; ++I) {
11520 for (OverridingMethods::const_iterator OI = I->second.begin(),
11521 OE = I->second.end();
11522 OI != OE; ++OI) {
11523 assert(OI->second.size() > 0 && "no final overrider");
11524 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011525
Richard Smithff817f72012-07-07 06:59:51 +000011526 // C++ [basic.def.odr]p2:
11527 // [...] A virtual member function is used if it is not pure. [...]
11528 if (!Overrider->isPure())
11529 MarkFunctionReferenced(Loc, Overrider);
11530 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011531 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011532
11533 // Only classes that have virtual bases need a VTT.
11534 if (RD->getNumVBases() == 0)
11535 return;
11536
11537 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11538 e = RD->bases_end(); i != e; ++i) {
11539 const CXXRecordDecl *Base =
11540 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011541 if (Base->getNumVBases() == 0)
11542 continue;
11543 MarkVirtualMembersReferenced(Loc, Base);
11544 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011545}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011546
11547/// SetIvarInitializers - This routine builds initialization ASTs for the
11548/// Objective-C implementation whose ivars need be initialized.
11549void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011550 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011551 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011552 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011553 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011554 CollectIvarsToConstructOrDestruct(OID, ivars);
11555 if (ivars.empty())
11556 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011557 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011558 for (unsigned i = 0; i < ivars.size(); i++) {
11559 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011560 if (Field->isInvalidDecl())
11561 continue;
11562
Sean Huntcbb67482011-01-08 20:30:50 +000011563 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011564 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11565 InitializationKind InitKind =
11566 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11567
11568 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011569 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011570 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011571 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011572 // Note, MemberInit could actually come back empty if no initialization
11573 // is required (e.g., because it would call a trivial default constructor)
11574 if (!MemberInit.get() || MemberInit.isInvalid())
11575 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011576
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011577 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011578 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11579 SourceLocation(),
11580 MemberInit.takeAs<Expr>(),
11581 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011582 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011583
11584 // Be sure that the destructor is accessible and is marked as referenced.
11585 if (const RecordType *RecordTy
11586 = Context.getBaseElementType(Field->getType())
11587 ->getAs<RecordType>()) {
11588 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011589 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011590 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011591 CheckDestructorAccess(Field->getLocation(), Destructor,
11592 PDiag(diag::err_access_dtor_ivar)
11593 << Context.getBaseElementType(Field->getType()));
11594 }
11595 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011596 }
11597 ObjCImplementation->setIvarInitializers(Context,
11598 AllToInit.data(), AllToInit.size());
11599 }
11600}
Sean Huntfe57eef2011-05-04 05:57:24 +000011601
Sean Huntebcbe1d2011-05-04 23:29:54 +000011602static
11603void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11604 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11605 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11606 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11607 Sema &S) {
11608 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11609 CE = Current.end();
11610 if (Ctor->isInvalidDecl())
11611 return;
11612
Richard Smitha8eaf002012-08-23 06:16:52 +000011613 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11614
11615 // Target may not be determinable yet, for instance if this is a dependent
11616 // call in an uninstantiated template.
11617 if (Target) {
11618 const FunctionDecl *FNTarget = 0;
11619 (void)Target->hasBody(FNTarget);
11620 Target = const_cast<CXXConstructorDecl*>(
11621 cast_or_null<CXXConstructorDecl>(FNTarget));
11622 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011623
11624 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11625 // Avoid dereferencing a null pointer here.
11626 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11627
11628 if (!Current.insert(Canonical))
11629 return;
11630
11631 // We know that beyond here, we aren't chaining into a cycle.
11632 if (!Target || !Target->isDelegatingConstructor() ||
11633 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11634 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11635 Valid.insert(*CI);
11636 Current.clear();
11637 // We've hit a cycle.
11638 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11639 Current.count(TCanonical)) {
11640 // If we haven't diagnosed this cycle yet, do so now.
11641 if (!Invalid.count(TCanonical)) {
11642 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011643 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011644 << Ctor;
11645
Richard Smitha8eaf002012-08-23 06:16:52 +000011646 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011647 if (TCanonical != Canonical)
11648 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11649
11650 CXXConstructorDecl *C = Target;
11651 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011652 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011653 (void)C->getTargetConstructor()->hasBody(FNTarget);
11654 assert(FNTarget && "Ctor cycle through bodiless function");
11655
Richard Smitha8eaf002012-08-23 06:16:52 +000011656 C = const_cast<CXXConstructorDecl*>(
11657 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011658 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11659 }
11660 }
11661
11662 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11663 Invalid.insert(*CI);
11664 Current.clear();
11665 } else {
11666 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11667 }
11668}
11669
11670
Sean Huntfe57eef2011-05-04 05:57:24 +000011671void Sema::CheckDelegatingCtorCycles() {
11672 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11673
Sean Huntebcbe1d2011-05-04 23:29:54 +000011674 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11675 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011676
Douglas Gregor0129b562011-07-27 21:57:17 +000011677 for (DelegatingCtorDeclsType::iterator
11678 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011679 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011680 I != E; ++I)
11681 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011682
11683 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11684 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011685}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011686
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011687namespace {
11688 /// \brief AST visitor that finds references to the 'this' expression.
11689 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11690 Sema &S;
11691
11692 public:
11693 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11694
11695 bool VisitCXXThisExpr(CXXThisExpr *E) {
11696 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11697 << E->isImplicit();
11698 return false;
11699 }
11700 };
11701}
11702
11703bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11704 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11705 if (!TSInfo)
11706 return false;
11707
11708 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011709 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011710 if (!ProtoTL)
11711 return false;
11712
11713 // C++11 [expr.prim.general]p3:
11714 // [The expression this] shall not appear before the optional
11715 // cv-qualifier-seq and it shall not appear within the declaration of a
11716 // static member function (although its type and value category are defined
11717 // within a static member function as they are within a non-static member
11718 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011719 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000011720 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011721 FindCXXThisExpr Finder(*this);
11722
11723 // If the return type came after the cv-qualifier-seq, check it now.
11724 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000011725 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011726 return true;
11727
11728 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011729 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11730 return true;
11731
11732 return checkThisInStaticMemberFunctionAttributes(Method);
11733}
11734
11735bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11736 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11737 if (!TSInfo)
11738 return false;
11739
11740 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011741 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011742 if (!ProtoTL)
11743 return false;
11744
David Blaikie39e6ab42013-02-18 22:06:02 +000011745 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011746 FindCXXThisExpr Finder(*this);
11747
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011748 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011749 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011750 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011751 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011752 case EST_DynamicNone:
11753 case EST_MSAny:
11754 case EST_None:
11755 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011756
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011757 case EST_ComputedNoexcept:
11758 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11759 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011760
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011761 case EST_Dynamic:
11762 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011763 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011764 E != EEnd; ++E) {
11765 if (!Finder.TraverseType(*E))
11766 return true;
11767 }
11768 break;
11769 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011770
11771 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011772}
11773
11774bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11775 FindCXXThisExpr Finder(*this);
11776
11777 // Check attributes.
11778 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11779 A != AEnd; ++A) {
11780 // FIXME: This should be emitted by tblgen.
11781 Expr *Arg = 0;
11782 ArrayRef<Expr *> Args;
11783 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11784 Arg = G->getArg();
11785 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11786 Arg = G->getArg();
11787 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11788 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11789 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11790 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11791 else if (ExclusiveLockFunctionAttr *ELF
11792 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11793 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11794 else if (SharedLockFunctionAttr *SLF
11795 = dyn_cast<SharedLockFunctionAttr>(*A))
11796 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11797 else if (ExclusiveTrylockFunctionAttr *ETLF
11798 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11799 Arg = ETLF->getSuccessValue();
11800 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11801 } else if (SharedTrylockFunctionAttr *STLF
11802 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11803 Arg = STLF->getSuccessValue();
11804 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11805 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11806 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11807 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11808 Arg = LR->getArg();
11809 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11810 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11811 else if (ExclusiveLocksRequiredAttr *ELR
11812 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11813 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11814 else if (SharedLocksRequiredAttr *SLR
11815 = dyn_cast<SharedLocksRequiredAttr>(*A))
11816 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11817
11818 if (Arg && !Finder.TraverseStmt(Arg))
11819 return true;
11820
11821 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11822 if (!Finder.TraverseStmt(Args[I]))
11823 return true;
11824 }
11825 }
11826
11827 return false;
11828}
11829
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011830void
11831Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11832 ArrayRef<ParsedType> DynamicExceptions,
11833 ArrayRef<SourceRange> DynamicExceptionRanges,
11834 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011835 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011836 FunctionProtoType::ExtProtoInfo &EPI) {
11837 Exceptions.clear();
11838 EPI.ExceptionSpecType = EST;
11839 if (EST == EST_Dynamic) {
11840 Exceptions.reserve(DynamicExceptions.size());
11841 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11842 // FIXME: Preserve type source info.
11843 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11844
11845 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11846 collectUnexpandedParameterPacks(ET, Unexpanded);
11847 if (!Unexpanded.empty()) {
11848 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11849 UPPC_ExceptionType,
11850 Unexpanded);
11851 continue;
11852 }
11853
11854 // Check that the type is valid for an exception spec, and
11855 // drop it if not.
11856 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11857 Exceptions.push_back(ET);
11858 }
11859 EPI.NumExceptions = Exceptions.size();
11860 EPI.Exceptions = Exceptions.data();
11861 return;
11862 }
11863
11864 if (EST == EST_ComputedNoexcept) {
11865 // If an error occurred, there's no expression here.
11866 if (NoexceptExpr) {
11867 assert((NoexceptExpr->isTypeDependent() ||
11868 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11869 Context.BoolTy) &&
11870 "Parser should have made sure that the expression is boolean");
11871 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11872 EPI.ExceptionSpecType = EST_BasicNoexcept;
11873 return;
11874 }
11875
11876 if (!NoexceptExpr->isValueDependent())
11877 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011878 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011879 /*AllowFold*/ false).take();
11880 EPI.NoexceptExpr = NoexceptExpr;
11881 }
11882 return;
11883 }
11884}
11885
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011886/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11887Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11888 // Implicitly declared functions (e.g. copy constructors) are
11889 // __host__ __device__
11890 if (D->isImplicit())
11891 return CFT_HostDevice;
11892
11893 if (D->hasAttr<CUDAGlobalAttr>())
11894 return CFT_Global;
11895
11896 if (D->hasAttr<CUDADeviceAttr>()) {
11897 if (D->hasAttr<CUDAHostAttr>())
11898 return CFT_HostDevice;
11899 else
11900 return CFT_Device;
11901 }
11902
11903 return CFT_Host;
11904}
11905
11906bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11907 CUDAFunctionTarget CalleeTarget) {
11908 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11909 // Callable from the device only."
11910 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11911 return true;
11912
11913 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11914 // Callable from the host only."
11915 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11916 // Callable from the host only."
11917 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11918 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11919 return true;
11920
11921 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11922 return true;
11923
11924 return false;
11925}