blob: 8b0ccd71460d86721e4212330fba16ac8731f4b8 [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.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000355 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000356 DeclaratorChunk &chunk = D.getTypeObject(i);
357 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000358 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
359 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000360 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000361 if (Param->hasUnparsedDefaultArg()) {
362 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000363 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
364 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
365 delete Toks;
366 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000367 } else if (Param->getDefaultArg()) {
368 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
369 << Param->getDefaultArg()->getSourceRange();
370 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000371 }
372 }
373 }
374 }
375}
376
Craig Topper1a6eac82012-09-21 04:33:26 +0000377/// MergeCXXFunctionDecl - Merge two declarations of the same C++
378/// function, once we already know that they have the same
379/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
380/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000381bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
382 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000383 bool Invalid = false;
384
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000386 // For non-template functions, default arguments can be added in
387 // later declarations of a function in the same
388 // scope. Declarations in different scopes have completely
389 // distinct sets of default arguments. That is, declarations in
390 // inner scopes do not acquire default arguments from
391 // declarations in outer scopes, and vice versa. In a given
392 // function declaration, all parameters subsequent to a
393 // parameter with a default argument shall have default
394 // arguments supplied in this or previous declarations. A
395 // default argument shall not be redefined by a later
396 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000397 //
398 // C++ [dcl.fct.default]p6:
399 // Except for member functions of class templates, the default arguments
400 // in a member function definition that appears outside of the class
401 // definition are added to the set of default arguments provided by the
402 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000403 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
404 ParmVarDecl *OldParam = Old->getParamDecl(p);
405 ParmVarDecl *NewParam = New->getParamDecl(p);
406
James Molloy9cda03f2012-03-13 08:55:35 +0000407 bool OldParamHasDfl = OldParam->hasDefaultArg();
408 bool NewParamHasDfl = NewParam->hasDefaultArg();
409
410 NamedDecl *ND = Old;
411 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
412 // Ignore default parameters of old decl if they are not in
413 // the same scope.
414 OldParamHasDfl = false;
415
416 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000417
Francois Pichet8d051e02011-04-10 03:03:52 +0000418 unsigned DiagDefaultParamID =
419 diag::err_param_default_argument_redefinition;
420
421 // MSVC accepts that default parameters be redefined for member functions
422 // of template class. The new default parameter's value is ignored.
423 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000424 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000425 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
426 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000427 // Merge the old default argument into the new parameter.
428 NewParam->setHasInheritedDefaultArg();
429 if (OldParam->hasUninstantiatedDefaultArg())
430 NewParam->setUninstantiatedDefaultArg(
431 OldParam->getUninstantiatedDefaultArg());
432 else
433 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000434 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000435 Invalid = false;
436 }
437 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000438
Francois Pichet8cf90492011-04-10 04:58:30 +0000439 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
440 // hint here. Alternatively, we could walk the type-source information
441 // for NewParam to find the last source location in the type... but it
442 // isn't worth the effort right now. This is the kind of test case that
443 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000444 // int f(int);
445 // void g(int (*fp)(int) = f);
446 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000447 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000448 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000449
450 // Look for the function declaration where the default argument was
451 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000452 for (FunctionDecl *Older = Old->getPreviousDecl();
453 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000454 if (!Older->getParamDecl(p)->hasDefaultArg())
455 break;
456
457 OldParam = Older->getParamDecl(p);
458 }
459
460 Diag(OldParam->getLocation(), diag::note_previous_definition)
461 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000462 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000463 // Merge the old default argument into the new parameter.
464 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000465 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000466 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000467 if (OldParam->hasUninstantiatedDefaultArg())
468 NewParam->setUninstantiatedDefaultArg(
469 OldParam->getUninstantiatedDefaultArg());
470 else
John McCall3d6c1782010-05-04 01:53:42 +0000471 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000472 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000473 if (New->getDescribedFunctionTemplate()) {
474 // Paragraph 4, quoted above, only applies to non-template functions.
475 Diag(NewParam->getLocation(),
476 diag::err_param_default_argument_template_redecl)
477 << NewParam->getDefaultArgRange();
478 Diag(Old->getLocation(), diag::note_template_prev_declaration)
479 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000480 } else if (New->getTemplateSpecializationKind()
481 != TSK_ImplicitInstantiation &&
482 New->getTemplateSpecializationKind() != TSK_Undeclared) {
483 // C++ [temp.expr.spec]p21:
484 // Default function arguments shall not be specified in a declaration
485 // or a definition for one of the following explicit specializations:
486 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000487 // - the explicit specialization of a member function template;
488 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000489 // template where the class template specialization to which the
490 // member function specialization belongs is implicitly
491 // instantiated.
492 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
493 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
494 << New->getDeclName()
495 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000496 } else if (New->getDeclContext()->isDependentContext()) {
497 // C++ [dcl.fct.default]p6 (DR217):
498 // Default arguments for a member function of a class template shall
499 // be specified on the initial declaration of the member function
500 // within the class template.
501 //
502 // Reading the tea leaves a bit in DR217 and its reference to DR205
503 // leads me to the conclusion that one cannot add default function
504 // arguments for an out-of-line definition of a member function of a
505 // dependent type.
506 int WhichKind = 2;
507 if (CXXRecordDecl *Record
508 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
509 if (Record->getDescribedClassTemplate())
510 WhichKind = 0;
511 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
512 WhichKind = 1;
513 else
514 WhichKind = 2;
515 }
516
517 Diag(NewParam->getLocation(),
518 diag::err_param_default_argument_member_template_redecl)
519 << WhichKind
520 << NewParam->getDefaultArgRange();
521 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000522 }
523 }
524
Richard Smithb8abff62012-11-28 03:45:24 +0000525 // DR1344: If a default argument is added outside a class definition and that
526 // default argument makes the function a special member function, the program
527 // is ill-formed. This can only happen for constructors.
528 if (isa<CXXConstructorDecl>(New) &&
529 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
530 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
531 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
532 if (NewSM != OldSM) {
533 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
534 assert(NewParam->hasDefaultArg());
535 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
536 << NewParam->getDefaultArgRange() << NewSM;
537 Diag(Old->getLocation(), diag::note_previous_declaration);
538 }
539 }
540
Richard Smithff234882012-02-20 23:28:05 +0000541 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000542 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000543 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000544 if (New->isConstexpr() != Old->isConstexpr()) {
545 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
546 << New << New->isConstexpr();
547 Diag(Old->getLocation(), diag::note_previous_declaration);
548 Invalid = true;
549 }
550
Douglas Gregore13ad832010-02-12 07:32:17 +0000551 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000552 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000553
Douglas Gregorcda9c672009-02-16 17:45:42 +0000554 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000555}
556
Sebastian Redl60618fa2011-03-12 11:50:43 +0000557/// \brief Merge the exception specifications of two variable declarations.
558///
559/// This is called when there's a redeclaration of a VarDecl. The function
560/// checks if the redeclaration might have an exception specification and
561/// validates compatibility and merges the specs if necessary.
562void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
563 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000564 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000565 return;
566
567 assert(Context.hasSameType(New->getType(), Old->getType()) &&
568 "Should only be called if types are otherwise the same.");
569
570 QualType NewType = New->getType();
571 QualType OldType = Old->getType();
572
573 // We're only interested in pointers and references to functions, as well
574 // as pointers to member functions.
575 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
576 NewType = R->getPointeeType();
577 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
578 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
579 NewType = P->getPointeeType();
580 OldType = OldType->getAs<PointerType>()->getPointeeType();
581 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
582 NewType = M->getPointeeType();
583 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
584 }
585
586 if (!NewType->isFunctionProtoType())
587 return;
588
589 // There's lots of special cases for functions. For function pointers, system
590 // libraries are hopefully not as broken so that we don't need these
591 // workarounds.
592 if (CheckEquivalentExceptionSpec(
593 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
594 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
595 New->setInvalidDecl();
596 }
597}
598
Chris Lattner3d1cee32008-04-08 05:04:30 +0000599/// CheckCXXDefaultArguments - Verify that the default arguments for a
600/// function declaration are well-formed according to C++
601/// [dcl.fct.default].
602void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
603 unsigned NumParams = FD->getNumParams();
604 unsigned p;
605
Douglas Gregorc6889e72012-02-14 22:28:59 +0000606 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
607 isa<CXXMethodDecl>(FD) &&
608 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
609
Chris Lattner3d1cee32008-04-08 05:04:30 +0000610 // Find first parameter with a default argument
611 for (p = 0; p < NumParams; ++p) {
612 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000613 if (Param->hasDefaultArg()) {
614 // C++11 [expr.prim.lambda]p5:
615 // [...] Default arguments (8.3.6) shall not be specified in the
616 // parameter-declaration-clause of a lambda-declarator.
617 //
618 // FIXME: Core issue 974 strikes this sentence, we only provide an
619 // extension warning.
620 if (IsLambda)
621 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
622 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000623 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000624 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000625 }
626
627 // C++ [dcl.fct.default]p4:
628 // In a given function declaration, all parameters
629 // subsequent to a parameter with a default argument shall
630 // have default arguments supplied in this or previous
631 // declarations. A default argument shall not be redefined
632 // by a later declaration (not even to the same value).
633 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000634 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000635 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000636 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000637 if (Param->isInvalidDecl())
638 /* We already complained about this parameter. */;
639 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000640 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000641 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000642 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000643 else
Mike Stump1eb44332009-09-09 15:08:12 +0000644 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000645 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Chris Lattner3d1cee32008-04-08 05:04:30 +0000647 LastMissingDefaultArg = p;
648 }
649 }
650
651 if (LastMissingDefaultArg > 0) {
652 // Some default arguments were missing. Clear out all of the
653 // default arguments up to (and including) the last missing
654 // default argument, so that we leave the function parameters
655 // in a semantically valid state.
656 for (p = 0; p <= LastMissingDefaultArg; ++p) {
657 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000658 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000659 Param->setDefaultArg(0);
660 }
661 }
662 }
663}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000664
Richard Smith9f569cc2011-10-01 02:31:28 +0000665// CheckConstexprParameterTypes - Check whether a function's parameter types
666// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000667// diagnostic and return false.
668static bool CheckConstexprParameterTypes(Sema &SemaRef,
669 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000670 unsigned ArgIndex = 0;
671 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
672 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
673 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
674 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
675 SourceLocation ParamLoc = PD->getLocation();
676 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000677 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000678 diag::err_constexpr_non_literal_param,
679 ArgIndex+1, PD->getSourceRange(),
680 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000681 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000682 }
Joao Matos17d35c32012-08-31 22:18:20 +0000683 return true;
684}
685
686/// \brief Get diagnostic %select index for tag kind for
687/// record diagnostic message.
688/// WARNING: Indexes apply to particular diagnostics only!
689///
690/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000691static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000692 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000693 case TTK_Struct: return 0;
694 case TTK_Interface: return 1;
695 case TTK_Class: return 2;
696 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000697 }
Joao Matos17d35c32012-08-31 22:18:20 +0000698}
699
700// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
701// the requirements of a constexpr function definition or a constexpr
702// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000703// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000704//
Richard Smith86c3ae42012-02-13 03:54:03 +0000705// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
706bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000707 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
708 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000709 // C++11 [dcl.constexpr]p4:
710 // The definition of a constexpr constructor shall satisfy the following
711 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000712 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000713 const CXXRecordDecl *RD = MD->getParent();
714 if (RD->getNumVBases()) {
715 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
716 << isa<CXXConstructorDecl>(NewFD)
717 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
718 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
719 E = RD->vbases_end(); I != E; ++I)
720 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000721 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000722 return false;
723 }
Richard Smith35340502012-01-13 04:54:00 +0000724 }
725
726 if (!isa<CXXConstructorDecl>(NewFD)) {
727 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000728 // The definition of a constexpr function shall satisfy the following
729 // constraints:
730 // - it shall not be virtual;
731 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
732 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000733 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000734
Richard Smith86c3ae42012-02-13 03:54:03 +0000735 // If it's not obvious why this function is virtual, find an overridden
736 // function which uses the 'virtual' keyword.
737 const CXXMethodDecl *WrittenVirtual = Method;
738 while (!WrittenVirtual->isVirtualAsWritten())
739 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
740 if (WrittenVirtual != Method)
741 Diag(WrittenVirtual->getLocation(),
742 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000743 return false;
744 }
745
746 // - its return type shall be a literal type;
747 QualType RT = NewFD->getResultType();
748 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000749 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000750 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000751 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000752 }
753
Richard Smith35340502012-01-13 04:54:00 +0000754 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000755 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000756 return false;
757
Richard Smith9f569cc2011-10-01 02:31:28 +0000758 return true;
759}
760
761/// Check the given declaration statement is legal within a constexpr function
762/// body. C++0x [dcl.constexpr]p3,p4.
763///
764/// \return true if the body is OK, false if we have diagnosed a problem.
765static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
766 DeclStmt *DS) {
767 // C++0x [dcl.constexpr]p3 and p4:
768 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
769 // contain only
770 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
771 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
772 switch ((*DclIt)->getKind()) {
773 case Decl::StaticAssert:
774 case Decl::Using:
775 case Decl::UsingShadow:
776 case Decl::UsingDirective:
777 case Decl::UnresolvedUsingTypename:
778 // - static_assert-declarations
779 // - using-declarations,
780 // - using-directives,
781 continue;
782
783 case Decl::Typedef:
784 case Decl::TypeAlias: {
785 // - typedef declarations and alias-declarations that do not define
786 // classes or enumerations,
787 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
788 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
789 // Don't allow variably-modified types in constexpr functions.
790 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
791 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
792 << TL.getSourceRange() << TL.getType()
793 << isa<CXXConstructorDecl>(Dcl);
794 return false;
795 }
796 continue;
797 }
798
799 case Decl::Enum:
800 case Decl::CXXRecord:
801 // As an extension, we allow the declaration (but not the definition) of
802 // classes and enumerations in all declarations, not just in typedef and
803 // alias declarations.
804 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
805 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
806 << isa<CXXConstructorDecl>(Dcl);
807 return false;
808 }
809 continue;
810
811 case Decl::Var:
812 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
813 << isa<CXXConstructorDecl>(Dcl);
814 return false;
815
816 default:
817 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
818 << isa<CXXConstructorDecl>(Dcl);
819 return false;
820 }
821 }
822
823 return true;
824}
825
826/// Check that the given field is initialized within a constexpr constructor.
827///
828/// \param Dcl The constexpr constructor being checked.
829/// \param Field The field being checked. This may be a member of an anonymous
830/// struct or union nested within the class being checked.
831/// \param Inits All declarations, including anonymous struct/union members and
832/// indirect members, for which any initialization was provided.
833/// \param Diagnosed Set to true if an error is produced.
834static void CheckConstexprCtorInitializer(Sema &SemaRef,
835 const FunctionDecl *Dcl,
836 FieldDecl *Field,
837 llvm::SmallSet<Decl*, 16> &Inits,
838 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000839 if (Field->isUnnamedBitfield())
840 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000841
842 if (Field->isAnonymousStructOrUnion() &&
843 Field->getType()->getAsCXXRecordDecl()->isEmpty())
844 return;
845
Richard Smith9f569cc2011-10-01 02:31:28 +0000846 if (!Inits.count(Field)) {
847 if (!Diagnosed) {
848 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
849 Diagnosed = true;
850 }
851 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
852 } else if (Field->isAnonymousStructOrUnion()) {
853 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
854 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
855 I != E; ++I)
856 // If an anonymous union contains an anonymous struct of which any member
857 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000858 if (!RD->isUnion() || Inits.count(*I))
859 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000860 }
861}
862
863/// Check the body for the given constexpr function declaration only contains
864/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
865///
866/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000867bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000868 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000869 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000870 // The definition of a constexpr function shall satisfy the following
871 // constraints: [...]
872 // - its function-body shall be = delete, = default, or a
873 // compound-statement
874 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000875 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000876 // In the definition of a constexpr constructor, [...]
877 // - its function-body shall not be a function-try-block;
878 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
879 << isa<CXXConstructorDecl>(Dcl);
880 return false;
881 }
882
883 // - its function-body shall be [...] a compound-statement that contains only
884 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
885
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000886 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smith9f569cc2011-10-01 02:31:28 +0000887 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
888 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
889 switch ((*BodyIt)->getStmtClass()) {
890 case Stmt::NullStmtClass:
891 // - null statements,
892 continue;
893
894 case Stmt::DeclStmtClass:
895 // - static_assert-declarations
896 // - using-declarations,
897 // - using-directives,
898 // - typedef declarations and alias-declarations that do not define
899 // classes or enumerations,
900 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
901 return false;
902 continue;
903
904 case Stmt::ReturnStmtClass:
905 // - and exactly one return statement;
906 if (isa<CXXConstructorDecl>(Dcl))
907 break;
908
909 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000910 continue;
911
912 default:
913 break;
914 }
915
916 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
917 << isa<CXXConstructorDecl>(Dcl);
918 return false;
919 }
920
921 if (const CXXConstructorDecl *Constructor
922 = dyn_cast<CXXConstructorDecl>(Dcl)) {
923 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000924 // DR1359:
925 // - every non-variant non-static data member and base class sub-object
926 // shall be initialized;
927 // - if the class is a non-empty union, or for each non-empty anonymous
928 // union member of a non-union class, exactly one non-static data member
929 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000930 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000931 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000932 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
933 return false;
934 }
Richard Smith6e433752011-10-10 16:38:04 +0000935 } else if (!Constructor->isDependentContext() &&
936 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000937 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
938
939 // Skip detailed checking if we have enough initializers, and we would
940 // allow at most one initializer per member.
941 bool AnyAnonStructUnionMembers = false;
942 unsigned Fields = 0;
943 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
944 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000945 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000946 AnyAnonStructUnionMembers = true;
947 break;
948 }
949 }
950 if (AnyAnonStructUnionMembers ||
951 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
952 // Check initialization of non-static data members. Base classes are
953 // always initialized so do not need to be checked. Dependent bases
954 // might not have initializers in the member initializer list.
955 llvm::SmallSet<Decl*, 16> Inits;
956 for (CXXConstructorDecl::init_const_iterator
957 I = Constructor->init_begin(), E = Constructor->init_end();
958 I != E; ++I) {
959 if (FieldDecl *FD = (*I)->getMember())
960 Inits.insert(FD);
961 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
962 Inits.insert(ID->chain_begin(), ID->chain_end());
963 }
964
965 bool Diagnosed = false;
966 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
967 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000968 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000969 if (Diagnosed)
970 return false;
971 }
972 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000973 } else {
974 if (ReturnStmts.empty()) {
975 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
976 return false;
977 }
978 if (ReturnStmts.size() > 1) {
979 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
980 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
981 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
982 return false;
983 }
984 }
985
Richard Smith5ba73e12012-02-04 00:33:54 +0000986 // C++11 [dcl.constexpr]p5:
987 // if no function argument values exist such that the function invocation
988 // substitution would produce a constant expression, the program is
989 // ill-formed; no diagnostic required.
990 // C++11 [dcl.constexpr]p3:
991 // - every constructor call and implicit conversion used in initializing the
992 // return value shall be one of those allowed in a constant expression.
993 // C++11 [dcl.constexpr]p4:
994 // - every constructor involved in initializing non-static data members and
995 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000996 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000997 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +0000998 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +0000999 << isa<CXXConstructorDecl>(Dcl);
1000 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1001 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001002 // Don't return false here: we allow this for compatibility in
1003 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001004 }
1005
Richard Smith9f569cc2011-10-01 02:31:28 +00001006 return true;
1007}
1008
Douglas Gregorb48fe382008-10-31 09:07:45 +00001009/// isCurrentClassName - Determine whether the identifier II is the
1010/// name of the class type currently being defined. In the case of
1011/// nested classes, this will only return true if II is the name of
1012/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001013bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1014 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001015 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001016
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001017 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001018 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001019 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001020 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1021 } else
1022 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1023
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001024 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001025 return &II == CurDecl->getIdentifier();
1026 else
1027 return false;
1028}
1029
Douglas Gregor229d47a2012-11-10 07:24:09 +00001030/// \brief Determine whether the given class is a base class of the given
1031/// class, including looking at dependent bases.
1032static bool findCircularInheritance(const CXXRecordDecl *Class,
1033 const CXXRecordDecl *Current) {
1034 SmallVector<const CXXRecordDecl*, 8> Queue;
1035
1036 Class = Class->getCanonicalDecl();
1037 while (true) {
1038 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1039 E = Current->bases_end();
1040 I != E; ++I) {
1041 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1042 if (!Base)
1043 continue;
1044
1045 Base = Base->getDefinition();
1046 if (!Base)
1047 continue;
1048
1049 if (Base->getCanonicalDecl() == Class)
1050 return true;
1051
1052 Queue.push_back(Base);
1053 }
1054
1055 if (Queue.empty())
1056 return false;
1057
1058 Current = Queue.back();
1059 Queue.pop_back();
1060 }
1061
1062 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001063}
1064
Mike Stump1eb44332009-09-09 15:08:12 +00001065/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001066///
1067/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1068/// and returns NULL otherwise.
1069CXXBaseSpecifier *
1070Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1071 SourceRange SpecifierRange,
1072 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001073 TypeSourceInfo *TInfo,
1074 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001075 QualType BaseType = TInfo->getType();
1076
Douglas Gregor2943aed2009-03-03 04:44:36 +00001077 // C++ [class.union]p1:
1078 // A union shall not have base classes.
1079 if (Class->isUnion()) {
1080 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1081 << SpecifierRange;
1082 return 0;
1083 }
1084
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001085 if (EllipsisLoc.isValid() &&
1086 !TInfo->getType()->containsUnexpandedParameterPack()) {
1087 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1088 << TInfo->getTypeLoc().getSourceRange();
1089 EllipsisLoc = SourceLocation();
1090 }
Douglas Gregord777e282012-11-10 01:18:17 +00001091
1092 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1093
1094 if (BaseType->isDependentType()) {
1095 // Make sure that we don't have circular inheritance among our dependent
1096 // bases. For non-dependent bases, the check for completeness below handles
1097 // this.
1098 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1099 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1100 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001101 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001102 Diag(BaseLoc, diag::err_circular_inheritance)
1103 << BaseType << Context.getTypeDeclType(Class);
1104
1105 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1106 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1107 << BaseType;
1108
1109 return 0;
1110 }
1111 }
1112
Mike Stump1eb44332009-09-09 15:08:12 +00001113 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001114 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001115 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001116 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001117
1118 // Base specifiers must be record types.
1119 if (!BaseType->isRecordType()) {
1120 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1121 return 0;
1122 }
1123
1124 // C++ [class.union]p1:
1125 // A union shall not be used as a base class.
1126 if (BaseType->isUnionType()) {
1127 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1128 return 0;
1129 }
1130
1131 // C++ [class.derived]p2:
1132 // The class-name in a base-specifier shall not be an incompletely
1133 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001134 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001135 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001136 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001137 return 0;
John McCall572fc622010-08-17 07:23:57 +00001138 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001139
Eli Friedman1d954f62009-08-15 21:55:26 +00001140 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001141 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001142 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001143 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001144 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001145 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1146 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001147
Anders Carlsson1d209272011-03-25 14:55:14 +00001148 // C++ [class]p3:
1149 // If a class is marked final and it appears as a base-type-specifier in
1150 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001151 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001152 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1153 << CXXBaseDecl->getDeclName();
1154 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1155 << CXXBaseDecl->getDeclName();
1156 return 0;
1157 }
1158
John McCall572fc622010-08-17 07:23:57 +00001159 if (BaseDecl->isInvalidDecl())
1160 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001161
1162 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001163 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001164 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001165 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001166}
1167
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001168/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1169/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001170/// example:
1171/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001172/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001173BaseResult
John McCalld226f652010-08-21 09:40:31 +00001174Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001175 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001176 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001177 ParsedType basetype, SourceLocation BaseLoc,
1178 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001179 if (!classdecl)
1180 return true;
1181
Douglas Gregor40808ce2009-03-09 23:48:35 +00001182 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001183 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001184 if (!Class)
1185 return true;
1186
Richard Smith05321402013-02-19 23:47:15 +00001187 // We do not support any C++11 attributes on base-specifiers yet.
1188 // Diagnose any attributes we see.
1189 if (!Attributes.empty()) {
1190 for (AttributeList *Attr = Attributes.getList(); Attr;
1191 Attr = Attr->getNext()) {
1192 if (Attr->isInvalid() ||
1193 Attr->getKind() == AttributeList::IgnoredAttribute)
1194 continue;
1195 Diag(Attr->getLoc(),
1196 Attr->getKind() == AttributeList::UnknownAttribute
1197 ? diag::warn_unknown_attribute_ignored
1198 : diag::err_base_specifier_attribute)
1199 << Attr->getName();
1200 }
1201 }
1202
Nick Lewycky56062202010-07-26 16:56:01 +00001203 TypeSourceInfo *TInfo = 0;
1204 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001205
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001206 if (EllipsisLoc.isInvalid() &&
1207 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001208 UPPC_BaseType))
1209 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001210
Douglas Gregor2943aed2009-03-03 04:44:36 +00001211 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001212 Virtual, Access, TInfo,
1213 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001214 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001215 else
1216 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Douglas Gregor2943aed2009-03-03 04:44:36 +00001218 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001219}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001220
Douglas Gregor2943aed2009-03-03 04:44:36 +00001221/// \brief Performs the actual work of attaching the given base class
1222/// specifiers to a C++ class.
1223bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1224 unsigned NumBases) {
1225 if (NumBases == 0)
1226 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001227
1228 // Used to keep track of which base types we have already seen, so
1229 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001230 // that the key is always the unqualified canonical type of the base
1231 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001232 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1233
1234 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001235 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001236 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001237 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001238 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001239 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001240 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001241
1242 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1243 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001244 // C++ [class.mi]p3:
1245 // A class shall not be specified as a direct base class of a
1246 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001247 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001248 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001249 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001250 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001251
1252 // Delete the duplicate base class specifier; we're going to
1253 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001254 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001255
1256 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001257 } else {
1258 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001259 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001260 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001261 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1262 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1263 if (Class->isInterface() &&
1264 (!RD->isInterface() ||
1265 KnownBase->getAccessSpecifier() != AS_public)) {
1266 // The Microsoft extension __interface does not permit bases that
1267 // are not themselves public interfaces.
1268 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1269 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1270 << RD->getSourceRange();
1271 Invalid = true;
1272 }
1273 if (RD->hasAttr<WeakAttr>())
1274 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1275 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001276 }
1277 }
1278
1279 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001280 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001281
1282 // Delete the remaining (good) base class specifiers, since their
1283 // data has been copied into the CXXRecordDecl.
1284 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001285 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001286
1287 return Invalid;
1288}
1289
1290/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1291/// class, after checking whether there are any duplicate base
1292/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001293void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001294 unsigned NumBases) {
1295 if (!ClassDecl || !Bases || !NumBases)
1296 return;
1297
1298 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001299 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001300 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001301}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001302
John McCall3cb0ebd2010-03-10 03:28:59 +00001303static CXXRecordDecl *GetClassForType(QualType T) {
1304 if (const RecordType *RT = T->getAs<RecordType>())
1305 return cast<CXXRecordDecl>(RT->getDecl());
1306 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1307 return ICT->getDecl();
1308 else
1309 return 0;
1310}
1311
Douglas Gregora8f32e02009-10-06 17:59:45 +00001312/// \brief Determine whether the type \p Derived is a C++ class that is
1313/// derived from the type \p Base.
1314bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001315 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001316 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001317
1318 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1319 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001320 return false;
1321
John McCall3cb0ebd2010-03-10 03:28:59 +00001322 CXXRecordDecl *BaseRD = GetClassForType(Base);
1323 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001324 return false;
1325
John McCall86ff3082010-02-04 22:26:26 +00001326 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1327 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001328}
1329
1330/// \brief Determine whether the type \p Derived is a C++ class that is
1331/// derived from the type \p Base.
1332bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001333 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001334 return false;
1335
John McCall3cb0ebd2010-03-10 03:28:59 +00001336 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1337 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001338 return false;
1339
John McCall3cb0ebd2010-03-10 03:28:59 +00001340 CXXRecordDecl *BaseRD = GetClassForType(Base);
1341 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001342 return false;
1343
Douglas Gregora8f32e02009-10-06 17:59:45 +00001344 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1345}
1346
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001347void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001348 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001349 assert(BasePathArray.empty() && "Base path array must be empty!");
1350 assert(Paths.isRecordingPaths() && "Must record paths!");
1351
1352 const CXXBasePath &Path = Paths.front();
1353
1354 // We first go backward and check if we have a virtual base.
1355 // FIXME: It would be better if CXXBasePath had the base specifier for
1356 // the nearest virtual base.
1357 unsigned Start = 0;
1358 for (unsigned I = Path.size(); I != 0; --I) {
1359 if (Path[I - 1].Base->isVirtual()) {
1360 Start = I - 1;
1361 break;
1362 }
1363 }
1364
1365 // Now add all bases.
1366 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001367 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001368}
1369
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001370/// \brief Determine whether the given base path includes a virtual
1371/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001372bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1373 for (CXXCastPath::const_iterator B = BasePath.begin(),
1374 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001375 B != BEnd; ++B)
1376 if ((*B)->isVirtual())
1377 return true;
1378
1379 return false;
1380}
1381
Douglas Gregora8f32e02009-10-06 17:59:45 +00001382/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1383/// conversion (where Derived and Base are class types) is
1384/// well-formed, meaning that the conversion is unambiguous (and
1385/// that all of the base classes are accessible). Returns true
1386/// and emits a diagnostic if the code is ill-formed, returns false
1387/// otherwise. Loc is the location where this routine should point to
1388/// if there is an error, and Range is the source range to highlight
1389/// if there is an error.
1390bool
1391Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001392 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001393 unsigned AmbigiousBaseConvID,
1394 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001395 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001396 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001397 // First, determine whether the path from Derived to Base is
1398 // ambiguous. This is slightly more expensive than checking whether
1399 // the Derived to Base conversion exists, because here we need to
1400 // explore multiple paths to determine if there is an ambiguity.
1401 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1402 /*DetectVirtual=*/false);
1403 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1404 assert(DerivationOkay &&
1405 "Can only be used with a derived-to-base conversion");
1406 (void)DerivationOkay;
1407
1408 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001409 if (InaccessibleBaseID) {
1410 // Check that the base class can be accessed.
1411 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1412 InaccessibleBaseID)) {
1413 case AR_inaccessible:
1414 return true;
1415 case AR_accessible:
1416 case AR_dependent:
1417 case AR_delayed:
1418 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001419 }
John McCall6b2accb2010-02-10 09:31:12 +00001420 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001421
1422 // Build a base path if necessary.
1423 if (BasePath)
1424 BuildBasePathArray(Paths, *BasePath);
1425 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001426 }
1427
1428 // We know that the derived-to-base conversion is ambiguous, and
1429 // we're going to produce a diagnostic. Perform the derived-to-base
1430 // search just one more time to compute all of the possible paths so
1431 // that we can print them out. This is more expensive than any of
1432 // the previous derived-to-base checks we've done, but at this point
1433 // performance isn't as much of an issue.
1434 Paths.clear();
1435 Paths.setRecordingPaths(true);
1436 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1437 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1438 (void)StillOkay;
1439
1440 // Build up a textual representation of the ambiguous paths, e.g.,
1441 // D -> B -> A, that will be used to illustrate the ambiguous
1442 // conversions in the diagnostic. We only print one of the paths
1443 // to each base class subobject.
1444 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1445
1446 Diag(Loc, AmbigiousBaseConvID)
1447 << Derived << Base << PathDisplayStr << Range << Name;
1448 return true;
1449}
1450
1451bool
1452Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001453 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001454 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001455 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001456 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001457 IgnoreAccess ? 0
1458 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001459 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001460 Loc, Range, DeclarationName(),
1461 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001462}
1463
1464
1465/// @brief Builds a string representing ambiguous paths from a
1466/// specific derived class to different subobjects of the same base
1467/// class.
1468///
1469/// This function builds a string that can be used in error messages
1470/// to show the different paths that one can take through the
1471/// inheritance hierarchy to go from the derived class to different
1472/// subobjects of a base class. The result looks something like this:
1473/// @code
1474/// struct D -> struct B -> struct A
1475/// struct D -> struct C -> struct A
1476/// @endcode
1477std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1478 std::string PathDisplayStr;
1479 std::set<unsigned> DisplayedPaths;
1480 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1481 Path != Paths.end(); ++Path) {
1482 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1483 // We haven't displayed a path to this particular base
1484 // class subobject yet.
1485 PathDisplayStr += "\n ";
1486 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1487 for (CXXBasePath::const_iterator Element = Path->begin();
1488 Element != Path->end(); ++Element)
1489 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1490 }
1491 }
1492
1493 return PathDisplayStr;
1494}
1495
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001496//===----------------------------------------------------------------------===//
1497// C++ class member Handling
1498//===----------------------------------------------------------------------===//
1499
Abramo Bagnara6206d532010-06-05 05:09:32 +00001500/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001501bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1502 SourceLocation ASLoc,
1503 SourceLocation ColonLoc,
1504 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001505 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001506 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001507 ASLoc, ColonLoc);
1508 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001509 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001510}
1511
Richard Smitha4b39652012-08-06 03:25:17 +00001512/// CheckOverrideControl - Check C++11 override control semantics.
1513void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001514 if (D->isInvalidDecl())
1515 return;
1516
Chris Lattner5f9e2722011-07-23 10:55:15 +00001517 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001518
Richard Smitha4b39652012-08-06 03:25:17 +00001519 // Do we know which functions this declaration might be overriding?
1520 bool OverridesAreKnown = !MD ||
1521 (!MD->getParent()->hasAnyDependentBases() &&
1522 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001523
Richard Smitha4b39652012-08-06 03:25:17 +00001524 if (!MD || !MD->isVirtual()) {
1525 if (OverridesAreKnown) {
1526 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1527 Diag(OA->getLocation(),
1528 diag::override_keyword_only_allowed_on_virtual_member_functions)
1529 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1530 D->dropAttr<OverrideAttr>();
1531 }
1532 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1533 Diag(FA->getLocation(),
1534 diag::override_keyword_only_allowed_on_virtual_member_functions)
1535 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1536 D->dropAttr<FinalAttr>();
1537 }
1538 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001539 return;
1540 }
Richard Smitha4b39652012-08-06 03:25:17 +00001541
1542 if (!OverridesAreKnown)
1543 return;
1544
1545 // C++11 [class.virtual]p5:
1546 // If a virtual function is marked with the virt-specifier override and
1547 // does not override a member function of a base class, the program is
1548 // ill-formed.
1549 bool HasOverriddenMethods =
1550 MD->begin_overridden_methods() != MD->end_overridden_methods();
1551 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1552 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1553 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001554}
1555
Richard Smitha4b39652012-08-06 03:25:17 +00001556/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001557/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001558/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001559bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1560 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001561 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001562 return false;
1563
1564 Diag(New->getLocation(), diag::err_final_function_overridden)
1565 << New->getDeclName();
1566 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1567 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001568}
1569
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001570static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001571 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1572 // FIXME: Destruction of ObjC lifetime types has side-effects.
1573 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1574 return !RD->isCompleteDefinition() ||
1575 !RD->hasTrivialDefaultConstructor() ||
1576 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001577 return false;
1578}
1579
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001580/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1581/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001582/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001583/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1584/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001585NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001586Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001587 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001588 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001589 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001590 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001591 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1592 DeclarationName Name = NameInfo.getName();
1593 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001594
1595 // For anonymous bitfields, the location should point to the type.
1596 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001597 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001598
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001599 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001600
John McCall4bde1e12010-06-04 08:34:12 +00001601 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001602 assert(!DS.isFriendSpecified());
1603
Richard Smith1ab0d902011-06-25 02:28:38 +00001604 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001605
John McCalle402e722012-09-25 07:32:39 +00001606 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1607 // The Microsoft extension __interface only permits public member functions
1608 // and prohibits constructors, destructors, operators, non-public member
1609 // functions, static methods and data members.
1610 unsigned InvalidDecl;
1611 bool ShowDeclName = true;
1612 if (!isFunc)
1613 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1614 else if (AS != AS_public)
1615 InvalidDecl = 2;
1616 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1617 InvalidDecl = 3;
1618 else switch (Name.getNameKind()) {
1619 case DeclarationName::CXXConstructorName:
1620 InvalidDecl = 4;
1621 ShowDeclName = false;
1622 break;
1623
1624 case DeclarationName::CXXDestructorName:
1625 InvalidDecl = 5;
1626 ShowDeclName = false;
1627 break;
1628
1629 case DeclarationName::CXXOperatorName:
1630 case DeclarationName::CXXConversionFunctionName:
1631 InvalidDecl = 6;
1632 break;
1633
1634 default:
1635 InvalidDecl = 0;
1636 break;
1637 }
1638
1639 if (InvalidDecl) {
1640 if (ShowDeclName)
1641 Diag(Loc, diag::err_invalid_member_in_interface)
1642 << (InvalidDecl-1) << Name;
1643 else
1644 Diag(Loc, diag::err_invalid_member_in_interface)
1645 << (InvalidDecl-1) << "";
1646 return 0;
1647 }
1648 }
1649
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001650 // C++ 9.2p6: A member shall not be declared to have automatic storage
1651 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001652 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1653 // data members and cannot be applied to names declared const or static,
1654 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001655 switch (DS.getStorageClassSpec()) {
1656 case DeclSpec::SCS_unspecified:
1657 case DeclSpec::SCS_typedef:
1658 case DeclSpec::SCS_static:
1659 // FALL THROUGH.
1660 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001661 case DeclSpec::SCS_mutable:
1662 if (isFunc) {
1663 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001664 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001665 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001666 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Sebastian Redla11f42f2008-11-17 23:24:37 +00001668 // FIXME: It would be nicer if the keyword was ignored only for this
1669 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001670 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001671 }
1672 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001673 default:
1674 if (DS.getStorageClassSpecLoc().isValid())
1675 Diag(DS.getStorageClassSpecLoc(),
1676 diag::err_storageclass_invalid_for_member);
1677 else
1678 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1679 D.getMutableDeclSpec().ClearStorageClassSpecs();
1680 }
1681
Sebastian Redl669d5d72008-11-14 23:42:31 +00001682 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1683 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001684 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001685
David Blaikie1d87fba2013-01-30 01:22:18 +00001686 if (DS.isConstexprSpecified() && isInstField) {
1687 SemaDiagnosticBuilder B =
1688 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1689 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1690 if (InitStyle == ICIS_NoInit) {
1691 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1692 D.getMutableDeclSpec().ClearConstexprSpec();
1693 const char *PrevSpec;
1694 unsigned DiagID;
1695 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1696 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001697 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001698 assert(!Failed && "Making a constexpr member const shouldn't fail");
1699 } else {
1700 B << 1;
1701 const char *PrevSpec;
1702 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001703 if (D.getMutableDeclSpec().SetStorageClassSpec(
1704 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001705 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001706 "This is the only DeclSpec that should fail to be applied");
1707 B << 1;
1708 } else {
1709 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1710 isInstField = false;
1711 }
1712 }
1713 }
1714
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001715 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001716 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001717 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001718
1719 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001720 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001721 Diag(Loc, diag::err_bad_variable_name)
1722 << Name;
1723 return 0;
1724 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001725
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001726 IdentifierInfo *II = Name.getAsIdentifierInfo();
1727
Douglas Gregorf2503652011-09-21 14:40:46 +00001728 // Member field could not be with "template" keyword.
1729 // So TemplateParameterLists should be empty in this case.
1730 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001731 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001732 if (TemplateParams->size()) {
1733 // There is no such thing as a member field template.
1734 Diag(D.getIdentifierLoc(), diag::err_template_member)
1735 << II
1736 << SourceRange(TemplateParams->getTemplateLoc(),
1737 TemplateParams->getRAngleLoc());
1738 } else {
1739 // There is an extraneous 'template<>' for this member.
1740 Diag(TemplateParams->getTemplateLoc(),
1741 diag::err_template_member_noparams)
1742 << II
1743 << SourceRange(TemplateParams->getTemplateLoc(),
1744 TemplateParams->getRAngleLoc());
1745 }
1746 return 0;
1747 }
1748
Douglas Gregor922fff22010-10-13 22:19:53 +00001749 if (SS.isSet() && !SS.isInvalid()) {
1750 // The user provided a superfluous scope specifier inside a class
1751 // definition:
1752 //
1753 // class X {
1754 // int X::member;
1755 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001756 if (DeclContext *DC = computeDeclContext(SS, false))
1757 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001758 else
1759 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1760 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001761
Douglas Gregor922fff22010-10-13 22:19:53 +00001762 SS.clear();
1763 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001764
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001765 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001766 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001767 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001768 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001769 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001770
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001771 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001772 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001773 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001774 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001775
1776 // Non-instance-fields can't have a bitfield.
1777 if (BitWidth) {
1778 if (Member->isInvalidDecl()) {
1779 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001780 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001781 // C++ 9.6p3: A bit-field shall not be a static member.
1782 // "static member 'A' cannot be a bit-field"
1783 Diag(Loc, diag::err_static_not_bitfield)
1784 << Name << BitWidth->getSourceRange();
1785 } else if (isa<TypedefDecl>(Member)) {
1786 // "typedef member 'x' cannot be a bit-field"
1787 Diag(Loc, diag::err_typedef_not_bitfield)
1788 << Name << BitWidth->getSourceRange();
1789 } else {
1790 // A function typedef ("typedef int f(); f a;").
1791 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1792 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001793 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001794 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001795 }
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Chris Lattner8b963ef2009-03-05 23:01:03 +00001797 BitWidth = 0;
1798 Member->setInvalidDecl();
1799 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001800
1801 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Douglas Gregor37b372b2009-08-20 22:52:58 +00001803 // If we have declared a member function template, set the access of the
1804 // templated declaration as well.
1805 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1806 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001807 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001808
Richard Smitha4b39652012-08-06 03:25:17 +00001809 if (VS.isOverrideSpecified())
1810 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1811 if (VS.isFinalSpecified())
1812 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001813
Douglas Gregorf5251602011-03-08 17:10:18 +00001814 if (VS.getLastLocation().isValid()) {
1815 // Update the end location of a method that has a virt-specifiers.
1816 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1817 MD->setRangeEnd(VS.getLastLocation());
1818 }
Richard Smitha4b39652012-08-06 03:25:17 +00001819
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001820 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001821
Douglas Gregor10bd3682008-11-17 22:58:34 +00001822 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001823
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001824 if (isInstField) {
1825 FieldDecl *FD = cast<FieldDecl>(Member);
1826 FieldCollector->Add(FD);
1827
1828 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1829 FD->getLocation())
1830 != DiagnosticsEngine::Ignored) {
1831 // Remember all explicit private FieldDecls that have a name, no side
1832 // effects and are not part of a dependent type declaration.
1833 if (!FD->isImplicit() && FD->getDeclName() &&
1834 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001835 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001836 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001837 !InitializationHasSideEffects(*FD))
1838 UnusedPrivateFields.insert(FD);
1839 }
1840 }
1841
John McCalld226f652010-08-21 09:40:31 +00001842 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001843}
1844
Hans Wennborg471f9852012-09-18 15:58:06 +00001845namespace {
1846 class UninitializedFieldVisitor
1847 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1848 Sema &S;
1849 ValueDecl *VD;
1850 public:
1851 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1852 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001853 S(S) {
1854 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1855 this->VD = IFD->getAnonField();
1856 else
1857 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001858 }
1859
1860 void HandleExpr(Expr *E) {
1861 if (!E) return;
1862
1863 // Expressions like x(x) sometimes lack the surrounding expressions
1864 // but need to be checked anyways.
1865 HandleValue(E);
1866 Visit(E);
1867 }
1868
1869 void HandleValue(Expr *E) {
1870 E = E->IgnoreParens();
1871
1872 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1873 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001874 return;
1875
1876 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1877 // or union.
1878 MemberExpr *FieldME = ME;
1879
Hans Wennborg471f9852012-09-18 15:58:06 +00001880 Expr *Base = E;
1881 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001882 ME = cast<MemberExpr>(Base);
1883
1884 if (isa<VarDecl>(ME->getMemberDecl()))
1885 return;
1886
1887 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1888 if (!FD->isAnonymousStructOrUnion())
1889 FieldME = ME;
1890
Hans Wennborg471f9852012-09-18 15:58:06 +00001891 Base = ME->getBase();
1892 }
1893
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001894 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00001895 unsigned diag = VD->getType()->isReferenceType()
1896 ? diag::warn_reference_field_is_uninit
1897 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001898 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001899 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001900 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00001901 }
1902
1903 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1904 HandleValue(CO->getTrueExpr());
1905 HandleValue(CO->getFalseExpr());
1906 return;
1907 }
1908
1909 if (BinaryConditionalOperator *BCO =
1910 dyn_cast<BinaryConditionalOperator>(E)) {
1911 HandleValue(BCO->getCommon());
1912 HandleValue(BCO->getFalseExpr());
1913 return;
1914 }
1915
1916 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1917 switch (BO->getOpcode()) {
1918 default:
1919 return;
1920 case(BO_PtrMemD):
1921 case(BO_PtrMemI):
1922 HandleValue(BO->getLHS());
1923 return;
1924 case(BO_Comma):
1925 HandleValue(BO->getRHS());
1926 return;
1927 }
1928 }
1929 }
1930
1931 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1932 if (E->getCastKind() == CK_LValueToRValue)
1933 HandleValue(E->getSubExpr());
1934
1935 Inherited::VisitImplicitCastExpr(E);
1936 }
1937
1938 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1939 Expr *Callee = E->getCallee();
1940 if (isa<MemberExpr>(Callee))
1941 HandleValue(Callee);
1942
1943 Inherited::VisitCXXMemberCallExpr(E);
1944 }
1945 };
1946 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1947 ValueDecl *VD) {
1948 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1949 }
1950} // namespace
1951
Richard Smith7a614d82011-06-11 17:19:42 +00001952/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001953/// in-class initializer for a non-static C++ class member, and after
1954/// instantiating an in-class initializer in a class template. Such actions
1955/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001956void
Richard Smithca523302012-06-10 03:12:00 +00001957Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001958 Expr *InitExpr) {
1959 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001960 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1961 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001962
1963 if (!InitExpr) {
1964 FD->setInvalidDecl();
1965 FD->removeInClassInitializer();
1966 return;
1967 }
1968
Peter Collingbournefef21892011-10-23 18:59:44 +00001969 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1970 FD->setInvalidDecl();
1971 FD->removeInClassInitializer();
1972 return;
1973 }
1974
Hans Wennborg471f9852012-09-18 15:58:06 +00001975 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1976 != DiagnosticsEngine::Ignored) {
1977 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1978 }
1979
Richard Smith7a614d82011-06-11 17:19:42 +00001980 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00001981 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001982 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001983 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001984 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1985 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001986 Expr **Inits = &InitExpr;
1987 unsigned NumInits = 1;
1988 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00001989 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00001990 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00001991 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00001992 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1993 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001994 if (Init.isInvalid()) {
1995 FD->setInvalidDecl();
1996 return;
1997 }
Richard Smith7a614d82011-06-11 17:19:42 +00001998 }
1999
Richard Smith41956372013-01-14 22:39:08 +00002000 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002001 // The initialization of each base and member constitutes a
2002 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002003 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002004 if (Init.isInvalid()) {
2005 FD->setInvalidDecl();
2006 return;
2007 }
2008
2009 InitExpr = Init.release();
2010
2011 FD->setInClassInitializer(InitExpr);
2012}
2013
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002014/// \brief Find the direct and/or virtual base specifiers that
2015/// correspond to the given base type, for use in base initialization
2016/// within a constructor.
2017static bool FindBaseInitializer(Sema &SemaRef,
2018 CXXRecordDecl *ClassDecl,
2019 QualType BaseType,
2020 const CXXBaseSpecifier *&DirectBaseSpec,
2021 const CXXBaseSpecifier *&VirtualBaseSpec) {
2022 // First, check for a direct base class.
2023 DirectBaseSpec = 0;
2024 for (CXXRecordDecl::base_class_const_iterator Base
2025 = ClassDecl->bases_begin();
2026 Base != ClassDecl->bases_end(); ++Base) {
2027 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2028 // We found a direct base of this type. That's what we're
2029 // initializing.
2030 DirectBaseSpec = &*Base;
2031 break;
2032 }
2033 }
2034
2035 // Check for a virtual base class.
2036 // FIXME: We might be able to short-circuit this if we know in advance that
2037 // there are no virtual bases.
2038 VirtualBaseSpec = 0;
2039 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2040 // We haven't found a base yet; search the class hierarchy for a
2041 // virtual base class.
2042 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2043 /*DetectVirtual=*/false);
2044 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2045 BaseType, Paths)) {
2046 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2047 Path != Paths.end(); ++Path) {
2048 if (Path->back().Base->isVirtual()) {
2049 VirtualBaseSpec = Path->back().Base;
2050 break;
2051 }
2052 }
2053 }
2054 }
2055
2056 return DirectBaseSpec || VirtualBaseSpec;
2057}
2058
Sebastian Redl6df65482011-09-24 17:48:25 +00002059/// \brief Handle a C++ member initializer using braced-init-list syntax.
2060MemInitResult
2061Sema::ActOnMemInitializer(Decl *ConstructorD,
2062 Scope *S,
2063 CXXScopeSpec &SS,
2064 IdentifierInfo *MemberOrBase,
2065 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002066 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002067 SourceLocation IdLoc,
2068 Expr *InitList,
2069 SourceLocation EllipsisLoc) {
2070 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002071 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002072 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002073}
2074
2075/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002076MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002077Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002078 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002079 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002080 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002081 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002082 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002083 SourceLocation IdLoc,
2084 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002085 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002086 SourceLocation RParenLoc,
2087 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002088 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2089 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002090 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002091 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002092 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002093}
2094
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002095namespace {
2096
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002097// Callback to only accept typo corrections that can be a valid C++ member
2098// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002099class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2100 public:
2101 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2102 : ClassDecl(ClassDecl) {}
2103
2104 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2105 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2106 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2107 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2108 else
2109 return isa<TypeDecl>(ND);
2110 }
2111 return false;
2112 }
2113
2114 private:
2115 CXXRecordDecl *ClassDecl;
2116};
2117
2118}
2119
Sebastian Redl6df65482011-09-24 17:48:25 +00002120/// \brief Handle a C++ member initializer.
2121MemInitResult
2122Sema::BuildMemInitializer(Decl *ConstructorD,
2123 Scope *S,
2124 CXXScopeSpec &SS,
2125 IdentifierInfo *MemberOrBase,
2126 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002127 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002128 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002129 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002130 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002131 if (!ConstructorD)
2132 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002133
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002134 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002135
2136 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002137 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002138 if (!Constructor) {
2139 // The user wrote a constructor initializer on a function that is
2140 // not a C++ constructor. Ignore the error for now, because we may
2141 // have more member initializers coming; we'll diagnose it just
2142 // once in ActOnMemInitializers.
2143 return true;
2144 }
2145
2146 CXXRecordDecl *ClassDecl = Constructor->getParent();
2147
2148 // C++ [class.base.init]p2:
2149 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002150 // constructor's class and, if not found in that scope, are looked
2151 // up in the scope containing the constructor's definition.
2152 // [Note: if the constructor's class contains a member with the
2153 // same name as a direct or virtual base class of the class, a
2154 // mem-initializer-id naming the member or base class and composed
2155 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002156 // mem-initializer-id for the hidden base class may be specified
2157 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002158 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002159 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002160 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002161 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002162 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002163 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002164 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2165 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002166 if (EllipsisLoc.isValid())
2167 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002168 << MemberOrBase
2169 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002170
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002171 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002172 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002173 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002174 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002175 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002176 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002177 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002178
2179 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002180 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002181 } else if (DS.getTypeSpecType() == TST_decltype) {
2182 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002183 } else {
2184 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2185 LookupParsedName(R, S, &SS);
2186
2187 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2188 if (!TyD) {
2189 if (R.isAmbiguous()) return true;
2190
John McCallfd225442010-04-09 19:01:14 +00002191 // We don't want access-control diagnostics here.
2192 R.suppressDiagnostics();
2193
Douglas Gregor7a886e12010-01-19 06:46:48 +00002194 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2195 bool NotUnknownSpecialization = false;
2196 DeclContext *DC = computeDeclContext(SS, false);
2197 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2198 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2199
2200 if (!NotUnknownSpecialization) {
2201 // When the scope specifier can refer to a member of an unknown
2202 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002203 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2204 SS.getWithLocInContext(Context),
2205 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002206 if (BaseType.isNull())
2207 return true;
2208
Douglas Gregor7a886e12010-01-19 06:46:48 +00002209 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002210 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002211 }
2212 }
2213
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002214 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002215 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002216 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002217 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002218 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002219 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002220 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2221 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002222 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002223 // We have found a non-static data member with a similar
2224 // name to what was typed; complain and initialize that
2225 // member.
2226 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2227 << MemberOrBase << true << CorrectedQuotedStr
2228 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2229 Diag(Member->getLocation(), diag::note_previous_decl)
2230 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002231
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002232 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002233 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002234 const CXXBaseSpecifier *DirectBaseSpec;
2235 const CXXBaseSpecifier *VirtualBaseSpec;
2236 if (FindBaseInitializer(*this, ClassDecl,
2237 Context.getTypeDeclType(Type),
2238 DirectBaseSpec, VirtualBaseSpec)) {
2239 // We have found a direct or virtual base class with a
2240 // similar name to what was typed; complain and initialize
2241 // that base class.
2242 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002243 << MemberOrBase << false << CorrectedQuotedStr
2244 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002245
2246 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2247 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002248 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002249 diag::note_base_class_specified_here)
2250 << BaseSpec->getType()
2251 << BaseSpec->getSourceRange();
2252
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002253 TyD = Type;
2254 }
2255 }
2256 }
2257
Douglas Gregor7a886e12010-01-19 06:46:48 +00002258 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002259 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002260 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002261 return true;
2262 }
John McCall2b194412009-12-21 10:41:20 +00002263 }
2264
Douglas Gregor7a886e12010-01-19 06:46:48 +00002265 if (BaseType.isNull()) {
2266 BaseType = Context.getTypeDeclType(TyD);
2267 if (SS.isSet()) {
2268 NestedNameSpecifier *Qualifier =
2269 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002270
Douglas Gregor7a886e12010-01-19 06:46:48 +00002271 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002272 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002273 }
John McCall2b194412009-12-21 10:41:20 +00002274 }
2275 }
Mike Stump1eb44332009-09-09 15:08:12 +00002276
John McCalla93c9342009-12-07 02:54:59 +00002277 if (!TInfo)
2278 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002279
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002280 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002281}
2282
Chandler Carruth81c64772011-09-03 01:14:15 +00002283/// Checks a member initializer expression for cases where reference (or
2284/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002285static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2286 Expr *Init,
2287 SourceLocation IdLoc) {
2288 QualType MemberTy = Member->getType();
2289
2290 // We only handle pointers and references currently.
2291 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2292 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2293 return;
2294
2295 const bool IsPointer = MemberTy->isPointerType();
2296 if (IsPointer) {
2297 if (const UnaryOperator *Op
2298 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2299 // The only case we're worried about with pointers requires taking the
2300 // address.
2301 if (Op->getOpcode() != UO_AddrOf)
2302 return;
2303
2304 Init = Op->getSubExpr();
2305 } else {
2306 // We only handle address-of expression initializers for pointers.
2307 return;
2308 }
2309 }
2310
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002311 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2312 // Taking the address of a temporary will be diagnosed as a hard error.
2313 if (IsPointer)
2314 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002315
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002316 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2317 << Member << Init->getSourceRange();
2318 } else if (const DeclRefExpr *DRE
2319 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2320 // We only warn when referring to a non-reference parameter declaration.
2321 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2322 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002323 return;
2324
2325 S.Diag(Init->getExprLoc(),
2326 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2327 : diag::warn_bind_ref_member_to_parameter)
2328 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002329 } else {
2330 // Other initializers are fine.
2331 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002332 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002333
2334 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2335 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002336}
2337
John McCallf312b1e2010-08-26 23:41:50 +00002338MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002339Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002340 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002341 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2342 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2343 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002344 "Member must be a FieldDecl or IndirectFieldDecl");
2345
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002346 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002347 return true;
2348
Douglas Gregor464b2f02010-11-05 22:21:31 +00002349 if (Member->isInvalidDecl())
2350 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002351
John McCallb4190042009-11-04 23:02:40 +00002352 // Diagnose value-uses of fields to initialize themselves, e.g.
2353 // foo(foo)
2354 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002355 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002356 Expr **Args;
2357 unsigned NumArgs;
2358 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2359 Args = ParenList->getExprs();
2360 NumArgs = ParenList->getNumExprs();
Richard Smithc83c2302012-12-19 01:39:02 +00002361 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002362 Args = InitList->getInits();
2363 NumArgs = InitList->getNumInits();
Richard Smithc83c2302012-12-19 01:39:02 +00002364 } else {
2365 // Template instantiation doesn't reconstruct ParenListExprs for us.
2366 Args = &Init;
2367 NumArgs = 1;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002368 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002369
Richard Trieude5e75c2012-06-14 23:11:34 +00002370 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2371 != DiagnosticsEngine::Ignored)
2372 for (unsigned i = 0; i < NumArgs; ++i)
2373 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002374 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002375 // initializing the i'th field, throw a warning if any of the >= i'th
2376 // fields are used, as they are not yet initialized.
2377 // Right now we are only handling the case where the i'th field uses
2378 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002379 // Also need to take into account that some fields may be initialized by
2380 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002381 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002382
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002383 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002384
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002385 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002386 // Can't check initialization for a member of dependent type or when
2387 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002388 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002389 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002390 bool InitList = false;
2391 if (isa<InitListExpr>(Init)) {
2392 InitList = true;
2393 Args = &Init;
2394 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002395
2396 if (isStdInitializerList(Member->getType(), 0)) {
2397 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2398 << /*at end of ctor*/1 << InitRange;
2399 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002400 }
2401
Chandler Carruth894aed92010-12-06 09:23:57 +00002402 // Initialize the member.
2403 InitializedEntity MemberEntity =
2404 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2405 : InitializedEntity::InitializeMember(IndirectMember, 0);
2406 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002407 InitList ? InitializationKind::CreateDirectList(IdLoc)
2408 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2409 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002410
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002411 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2412 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002413 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002414 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002415 if (MemberInit.isInvalid())
2416 return true;
2417
Richard Smith41956372013-01-14 22:39:08 +00002418 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002419 // The initialization of each base and member constitutes a
2420 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002421 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002422 if (MemberInit.isInvalid())
2423 return true;
2424
Richard Smithc83c2302012-12-19 01:39:02 +00002425 Init = MemberInit.get();
2426 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002427 }
2428
Chandler Carruth894aed92010-12-06 09:23:57 +00002429 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002430 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2431 InitRange.getBegin(), Init,
2432 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002433 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002434 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2435 InitRange.getBegin(), Init,
2436 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002437 }
Eli Friedman59c04372009-07-29 19:44:27 +00002438}
2439
John McCallf312b1e2010-08-26 23:41:50 +00002440MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002441Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002442 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002443 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002444 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002445 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002446 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002447 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002448
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002449 bool InitList = true;
2450 Expr **Args = &Init;
2451 unsigned NumArgs = 1;
2452 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2453 InitList = false;
2454 Args = ParenList->getExprs();
2455 NumArgs = ParenList->getNumExprs();
2456 }
2457
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002458 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002459 // Initialize the object.
2460 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2461 QualType(ClassDecl->getTypeForDecl(), 0));
2462 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002463 InitList ? InitializationKind::CreateDirectList(NameLoc)
2464 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2465 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002466 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2467 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002468 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002469 0);
Sean Hunt41717662011-02-26 19:13:13 +00002470 if (DelegationInit.isInvalid())
2471 return true;
2472
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002473 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2474 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002475
Richard Smith41956372013-01-14 22:39:08 +00002476 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002477 // The initialization of each base and member constitutes a
2478 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002479 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2480 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002481 if (DelegationInit.isInvalid())
2482 return true;
2483
Eli Friedmand21016f2012-05-19 23:35:23 +00002484 // If we are in a dependent context, template instantiation will
2485 // perform this type-checking again. Just save the arguments that we
2486 // received in a ParenListExpr.
2487 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2488 // of the information that we have about the base
2489 // initializer. However, deconstructing the ASTs is a dicey process,
2490 // and this approach is far more likely to get the corner cases right.
2491 if (CurContext->isDependentContext())
2492 DelegationInit = Owned(Init);
2493
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002494 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002495 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002496 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002497}
2498
2499MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002500Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002501 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002502 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002503 SourceLocation BaseLoc
2504 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002505
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002506 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2507 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2508 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2509
2510 // C++ [class.base.init]p2:
2511 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002512 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002513 // of that class, the mem-initializer is ill-formed. A
2514 // mem-initializer-list can initialize a base class using any
2515 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002516 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002517
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002518 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002519 if (EllipsisLoc.isValid()) {
2520 // This is a pack expansion.
2521 if (!BaseType->containsUnexpandedParameterPack()) {
2522 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002523 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002524
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002525 EllipsisLoc = SourceLocation();
2526 }
2527 } else {
2528 // Check for any unexpanded parameter packs.
2529 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2530 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002531
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002532 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002533 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002534 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002535
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002536 // Check for direct and virtual base classes.
2537 const CXXBaseSpecifier *DirectBaseSpec = 0;
2538 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2539 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002540 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2541 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002542 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002543
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002544 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2545 VirtualBaseSpec);
2546
2547 // C++ [base.class.init]p2:
2548 // Unless the mem-initializer-id names a nonstatic data member of the
2549 // constructor's class or a direct or virtual base of that class, the
2550 // mem-initializer is ill-formed.
2551 if (!DirectBaseSpec && !VirtualBaseSpec) {
2552 // If the class has any dependent bases, then it's possible that
2553 // one of those types will resolve to the same type as
2554 // BaseType. Therefore, just treat this as a dependent base
2555 // class initialization. FIXME: Should we try to check the
2556 // initialization anyway? It seems odd.
2557 if (ClassDecl->hasAnyDependentBases())
2558 Dependent = true;
2559 else
2560 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2561 << BaseType << Context.getTypeDeclType(ClassDecl)
2562 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2563 }
2564 }
2565
2566 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002567 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002568
Sebastian Redl6df65482011-09-24 17:48:25 +00002569 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2570 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002571 InitRange.getBegin(), Init,
2572 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002573 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002574
2575 // C++ [base.class.init]p2:
2576 // If a mem-initializer-id is ambiguous because it designates both
2577 // a direct non-virtual base class and an inherited virtual base
2578 // class, the mem-initializer is ill-formed.
2579 if (DirectBaseSpec && VirtualBaseSpec)
2580 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002581 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002582
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002583 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002584 if (!BaseSpec)
2585 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2586
2587 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002588 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002589 Expr **Args = &Init;
2590 unsigned NumArgs = 1;
2591 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002592 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002593 Args = ParenList->getExprs();
2594 NumArgs = ParenList->getNumExprs();
2595 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002596
2597 InitializedEntity BaseEntity =
2598 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2599 InitializationKind Kind =
2600 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2601 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2602 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002603 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2604 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002605 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002606 if (BaseInit.isInvalid())
2607 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002608
Richard Smith41956372013-01-14 22:39:08 +00002609 // C++11 [class.base.init]p7:
2610 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002611 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002612 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002613 if (BaseInit.isInvalid())
2614 return true;
2615
2616 // If we are in a dependent context, template instantiation will
2617 // perform this type-checking again. Just save the arguments that we
2618 // received in a ParenListExpr.
2619 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2620 // of the information that we have about the base
2621 // initializer. However, deconstructing the ASTs is a dicey process,
2622 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002623 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002624 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002625
Sean Huntcbb67482011-01-08 20:30:50 +00002626 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002627 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002628 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002629 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002630 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002631}
2632
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002633// Create a static_cast\<T&&>(expr).
2634static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2635 QualType ExprType = E->getType();
2636 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2637 SourceLocation ExprLoc = E->getLocStart();
2638 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2639 TargetType, ExprLoc);
2640
2641 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2642 SourceRange(ExprLoc, ExprLoc),
2643 E->getSourceRange()).take();
2644}
2645
Anders Carlssone5ef7402010-04-23 03:10:23 +00002646/// ImplicitInitializerKind - How an implicit base or member initializer should
2647/// initialize its base or member.
2648enum ImplicitInitializerKind {
2649 IIK_Default,
2650 IIK_Copy,
2651 IIK_Move
2652};
2653
Anders Carlssondefefd22010-04-23 02:00:02 +00002654static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002655BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002656 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002657 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002658 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002659 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002660 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002661 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2662 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002663
John McCall60d7b3a2010-08-24 06:29:42 +00002664 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002665
2666 switch (ImplicitInitKind) {
2667 case IIK_Default: {
2668 InitializationKind InitKind
2669 = InitializationKind::CreateDefault(Constructor->getLocation());
2670 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002671 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002672 break;
2673 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002674
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002675 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002676 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002677 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002678 ParmVarDecl *Param = Constructor->getParamDecl(0);
2679 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002680
Anders Carlssone5ef7402010-04-23 03:10:23 +00002681 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002682 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002683 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002684 Constructor->getLocation(), ParamType,
2685 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002686
Eli Friedman5f2987c2012-02-02 03:46:19 +00002687 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2688
Anders Carlssonc7957502010-04-24 22:02:54 +00002689 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002690 QualType ArgTy =
2691 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2692 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002693
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002694 if (Moving) {
2695 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2696 }
2697
John McCallf871d0c2010-08-07 06:22:56 +00002698 CXXCastPath BasePath;
2699 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002700 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2701 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002702 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002703 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002704
Anders Carlssone5ef7402010-04-23 03:10:23 +00002705 InitializationKind InitKind
2706 = InitializationKind::CreateDirect(Constructor->getLocation(),
2707 SourceLocation(), SourceLocation());
2708 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2709 &CopyCtorArg, 1);
2710 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002711 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002712 break;
2713 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002714 }
John McCall9ae2f072010-08-23 23:25:46 +00002715
Douglas Gregor53c374f2010-12-07 00:41:46 +00002716 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002717 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002718 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002719
Anders Carlssondefefd22010-04-23 02:00:02 +00002720 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002721 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002722 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2723 SourceLocation()),
2724 BaseSpec->isVirtual(),
2725 SourceLocation(),
2726 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002727 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002728 SourceLocation());
2729
Anders Carlssondefefd22010-04-23 02:00:02 +00002730 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002731}
2732
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002733static bool RefersToRValueRef(Expr *MemRef) {
2734 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2735 return Referenced->getType()->isRValueReferenceType();
2736}
2737
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002738static bool
2739BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002740 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002741 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002742 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002743 if (Field->isInvalidDecl())
2744 return true;
2745
Chandler Carruthf186b542010-06-29 23:50:44 +00002746 SourceLocation Loc = Constructor->getLocation();
2747
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002748 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2749 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002750 ParmVarDecl *Param = Constructor->getParamDecl(0);
2751 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002752
2753 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002754 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2755 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002756
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002757 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002758 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002759 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002760 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002761
Eli Friedman5f2987c2012-02-02 03:46:19 +00002762 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2763
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002764 if (Moving) {
2765 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2766 }
2767
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002768 // Build a reference to this field within the parameter.
2769 CXXScopeSpec SS;
2770 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2771 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002772 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2773 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002774 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002775 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002776 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002777 ParamType, Loc,
2778 /*IsArrow=*/false,
2779 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002780 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002781 /*FirstQualifierInScope=*/0,
2782 MemberLookup,
2783 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002784 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002785 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002786
2787 // C++11 [class.copy]p15:
2788 // - if a member m has rvalue reference type T&&, it is direct-initialized
2789 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002790 if (RefersToRValueRef(CtorArg.get())) {
2791 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002792 }
2793
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002794 // When the field we are copying is an array, create index variables for
2795 // each dimension of the array. We use these index variables to subscript
2796 // the source array, and other clients (e.g., CodeGen) will perform the
2797 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002798 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002799 QualType BaseType = Field->getType();
2800 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002801 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002802 while (const ConstantArrayType *Array
2803 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002804 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002805 // Create the iteration variable for this array index.
2806 IdentifierInfo *IterationVarName = 0;
2807 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002808 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002809 llvm::raw_svector_ostream OS(Str);
2810 OS << "__i" << IndexVariables.size();
2811 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2812 }
2813 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002814 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002815 IterationVarName, SizeType,
2816 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002817 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002818 IndexVariables.push_back(IterationVar);
2819
2820 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002821 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002822 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002823 assert(!IterationVarRef.isInvalid() &&
2824 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002825 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2826 assert(!IterationVarRef.isInvalid() &&
2827 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002828
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002829 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002830 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002831 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002832 Loc);
2833 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002834 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002835
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002836 BaseType = Array->getElementType();
2837 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002838
2839 // The array subscript expression is an lvalue, which is wrong for moving.
2840 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002841 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002842
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002843 // Construct the entity that we will be initializing. For an array, this
2844 // will be first element in the array, which may require several levels
2845 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002846 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002847 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002848 if (Indirect)
2849 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2850 else
2851 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002852 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2853 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2854 0,
2855 Entities.back()));
2856
2857 // Direct-initialize to use the copy constructor.
2858 InitializationKind InitKind =
2859 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2860
Sebastian Redl74e611a2011-09-04 18:14:28 +00002861 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002862 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002863 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002864
John McCall60d7b3a2010-08-24 06:29:42 +00002865 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002866 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002867 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002868 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002869 if (MemberInit.isInvalid())
2870 return true;
2871
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002872 if (Indirect) {
2873 assert(IndexVariables.size() == 0 &&
2874 "Indirect field improperly initialized");
2875 CXXMemberInit
2876 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2877 Loc, Loc,
2878 MemberInit.takeAs<Expr>(),
2879 Loc);
2880 } else
2881 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2882 Loc, MemberInit.takeAs<Expr>(),
2883 Loc,
2884 IndexVariables.data(),
2885 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002886 return false;
2887 }
2888
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002889 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2890
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002891 QualType FieldBaseElementType =
2892 SemaRef.Context.getBaseElementType(Field->getType());
2893
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002894 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002895 InitializedEntity InitEntity
2896 = Indirect? InitializedEntity::InitializeMember(Indirect)
2897 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002898 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002899 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002900
2901 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002902 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002903 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002904
Douglas Gregor53c374f2010-12-07 00:41:46 +00002905 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002906 if (MemberInit.isInvalid())
2907 return true;
2908
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002909 if (Indirect)
2910 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2911 Indirect, Loc,
2912 Loc,
2913 MemberInit.get(),
2914 Loc);
2915 else
2916 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2917 Field, Loc, Loc,
2918 MemberInit.get(),
2919 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002920 return false;
2921 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002922
Sean Hunt1f2f3842011-05-17 00:19:05 +00002923 if (!Field->getParent()->isUnion()) {
2924 if (FieldBaseElementType->isReferenceType()) {
2925 SemaRef.Diag(Constructor->getLocation(),
2926 diag::err_uninitialized_member_in_ctor)
2927 << (int)Constructor->isImplicit()
2928 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2929 << 0 << Field->getDeclName();
2930 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2931 return true;
2932 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002933
Sean Hunt1f2f3842011-05-17 00:19:05 +00002934 if (FieldBaseElementType.isConstQualified()) {
2935 SemaRef.Diag(Constructor->getLocation(),
2936 diag::err_uninitialized_member_in_ctor)
2937 << (int)Constructor->isImplicit()
2938 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2939 << 1 << Field->getDeclName();
2940 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2941 return true;
2942 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002943 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002944
David Blaikie4e4d0842012-03-11 07:00:24 +00002945 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002946 FieldBaseElementType->isObjCRetainableType() &&
2947 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2948 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002949 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002950 // Default-initialize Objective-C pointers to NULL.
2951 CXXMemberInit
2952 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2953 Loc, Loc,
2954 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2955 Loc);
2956 return false;
2957 }
2958
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002959 // Nothing to initialize.
2960 CXXMemberInit = 0;
2961 return false;
2962}
John McCallf1860e52010-05-20 23:23:51 +00002963
2964namespace {
2965struct BaseAndFieldInfo {
2966 Sema &S;
2967 CXXConstructorDecl *Ctor;
2968 bool AnyErrorsInInits;
2969 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002970 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002971 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002972
2973 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2974 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002975 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2976 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002977 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002978 else if (Generated && Ctor->isMoveConstructor())
2979 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002980 else
2981 IIK = IIK_Default;
2982 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002983
2984 bool isImplicitCopyOrMove() const {
2985 switch (IIK) {
2986 case IIK_Copy:
2987 case IIK_Move:
2988 return true;
2989
2990 case IIK_Default:
2991 return false;
2992 }
David Blaikie30263482012-01-20 21:50:17 +00002993
2994 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002995 }
Richard Smith0b8220a2012-08-07 21:30:42 +00002996
2997 bool addFieldInitializer(CXXCtorInitializer *Init) {
2998 AllToInit.push_back(Init);
2999
3000 // Check whether this initializer makes the field "used".
3001 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
3002 S.UnusedPrivateFields.remove(Init->getAnyMember());
3003
3004 return false;
3005 }
John McCallf1860e52010-05-20 23:23:51 +00003006};
3007}
3008
Richard Smitha4950662011-09-19 13:34:43 +00003009/// \brief Determine whether the given indirect field declaration is somewhere
3010/// within an anonymous union.
3011static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3012 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3013 CEnd = F->chain_end();
3014 C != CEnd; ++C)
3015 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3016 if (Record->isUnion())
3017 return true;
3018
3019 return false;
3020}
3021
Douglas Gregorddb21472011-11-02 23:04:16 +00003022/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3023/// array type.
3024static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3025 if (T->isIncompleteArrayType())
3026 return true;
3027
3028 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3029 if (!ArrayT->getSize())
3030 return true;
3031
3032 T = ArrayT->getElementType();
3033 }
3034
3035 return false;
3036}
3037
Richard Smith7a614d82011-06-11 17:19:42 +00003038static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003039 FieldDecl *Field,
3040 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003041
Chandler Carruthe861c602010-06-30 02:59:29 +00003042 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003043 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3044 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003045
Richard Smith0b8220a2012-08-07 21:30:42 +00003046 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003047 // has a brace-or-equal-initializer, the entity is initialized as specified
3048 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003049 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003050 CXXCtorInitializer *Init;
3051 if (Indirect)
3052 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3053 SourceLocation(),
3054 SourceLocation(), 0,
3055 SourceLocation());
3056 else
3057 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3058 SourceLocation(),
3059 SourceLocation(), 0,
3060 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003061 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003062 }
3063
Richard Smithc115f632011-09-18 11:14:50 +00003064 // Don't build an implicit initializer for union members if none was
3065 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003066 if (Field->getParent()->isUnion() ||
3067 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003068 return false;
3069
Douglas Gregorddb21472011-11-02 23:04:16 +00003070 // Don't initialize incomplete or zero-length arrays.
3071 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3072 return false;
3073
John McCallf1860e52010-05-20 23:23:51 +00003074 // Don't try to build an implicit initializer if there were semantic
3075 // errors in any of the initializers (and therefore we might be
3076 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003077 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003078 return false;
3079
Sean Huntcbb67482011-01-08 20:30:50 +00003080 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003081 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3082 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003083 return true;
John McCallf1860e52010-05-20 23:23:51 +00003084
Richard Smith0b8220a2012-08-07 21:30:42 +00003085 if (!Init)
3086 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003087
Richard Smith0b8220a2012-08-07 21:30:42 +00003088 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003089}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003090
3091bool
3092Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3093 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003094 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003095 Constructor->setNumCtorInitializers(1);
3096 CXXCtorInitializer **initializer =
3097 new (Context) CXXCtorInitializer*[1];
3098 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3099 Constructor->setCtorInitializers(initializer);
3100
Sean Huntb76af9c2011-05-03 23:05:34 +00003101 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003102 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003103 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3104 }
3105
Sean Huntc1598702011-05-05 00:05:47 +00003106 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003107
Sean Hunt059ce0d2011-05-01 07:04:31 +00003108 return false;
3109}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003110
David Blaikie93c86172013-01-17 05:26:25 +00003111bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3112 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003113 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003114 // Just store the initializers as written, they will be checked during
3115 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003116 if (!Initializers.empty()) {
3117 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003118 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003119 new (Context) CXXCtorInitializer*[Initializers.size()];
3120 memcpy(baseOrMemberInitializers, Initializers.data(),
3121 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003122 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003123 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003124
3125 // Let template instantiation know whether we had errors.
3126 if (AnyErrors)
3127 Constructor->setInvalidDecl();
3128
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003129 return false;
3130 }
3131
John McCallf1860e52010-05-20 23:23:51 +00003132 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003133
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003134 // We need to build the initializer AST according to order of construction
3135 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003136 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003137 if (!ClassDecl)
3138 return true;
3139
Eli Friedman80c30da2009-11-09 19:20:36 +00003140 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003141
David Blaikie93c86172013-01-17 05:26:25 +00003142 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003143 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003144
3145 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003146 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003147 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003148 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003149 }
3150
Anders Carlsson711f34a2010-04-21 19:52:01 +00003151 // Keep track of the direct virtual bases.
3152 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3153 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3154 E = ClassDecl->bases_end(); I != E; ++I) {
3155 if (I->isVirtual())
3156 DirectVBases.insert(I);
3157 }
3158
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003159 // Push virtual bases before others.
3160 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3161 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3162
Sean Huntcbb67482011-01-08 20:30:50 +00003163 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003164 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3165 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003166 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003167 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003168 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003169 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003170 VBase, IsInheritedVirtualBase,
3171 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003172 HadError = true;
3173 continue;
3174 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003175
John McCallf1860e52010-05-20 23:23:51 +00003176 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003177 }
3178 }
Mike Stump1eb44332009-09-09 15:08:12 +00003179
John McCallf1860e52010-05-20 23:23:51 +00003180 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003181 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3182 E = ClassDecl->bases_end(); Base != E; ++Base) {
3183 // Virtuals are in the virtual base list and already constructed.
3184 if (Base->isVirtual())
3185 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003186
Sean Huntcbb67482011-01-08 20:30:50 +00003187 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003188 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3189 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003190 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003191 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003192 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003193 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003194 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003195 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003196 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003197 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003198
John McCallf1860e52010-05-20 23:23:51 +00003199 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003200 }
3201 }
Mike Stump1eb44332009-09-09 15:08:12 +00003202
John McCallf1860e52010-05-20 23:23:51 +00003203 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003204 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3205 MemEnd = ClassDecl->decls_end();
3206 Mem != MemEnd; ++Mem) {
3207 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003208 // C++ [class.bit]p2:
3209 // A declaration for a bit-field that omits the identifier declares an
3210 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3211 // initialized.
3212 if (F->isUnnamedBitfield())
3213 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003214
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003215 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003216 // handle anonymous struct/union fields based on their individual
3217 // indirect fields.
3218 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3219 continue;
3220
3221 if (CollectFieldInitializer(*this, Info, F))
3222 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003223 continue;
3224 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003225
3226 // Beyond this point, we only consider default initialization.
3227 if (Info.IIK != IIK_Default)
3228 continue;
3229
3230 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3231 if (F->getType()->isIncompleteArrayType()) {
3232 assert(ClassDecl->hasFlexibleArrayMember() &&
3233 "Incomplete array type is not valid");
3234 continue;
3235 }
3236
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003237 // Initialize each field of an anonymous struct individually.
3238 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3239 HadError = true;
3240
3241 continue;
3242 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003243 }
Mike Stump1eb44332009-09-09 15:08:12 +00003244
David Blaikie93c86172013-01-17 05:26:25 +00003245 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003246 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003247 Constructor->setNumCtorInitializers(NumInitializers);
3248 CXXCtorInitializer **baseOrMemberInitializers =
3249 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003250 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003251 NumInitializers * sizeof(CXXCtorInitializer*));
3252 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003253
John McCallef027fe2010-03-16 21:39:52 +00003254 // Constructors implicitly reference the base and member
3255 // destructors.
3256 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3257 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003258 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003259
3260 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003261}
3262
David Blaikieee000bb2013-01-17 08:49:22 +00003263static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003264 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003265 const RecordDecl *RD = RT->getDecl();
3266 if (RD->isAnonymousStructOrUnion()) {
3267 for (RecordDecl::field_iterator Field = RD->field_begin(),
3268 E = RD->field_end(); Field != E; ++Field)
3269 PopulateKeysForFields(*Field, IdealInits);
3270 return;
3271 }
Eli Friedman6347f422009-07-21 19:28:10 +00003272 }
David Blaikieee000bb2013-01-17 08:49:22 +00003273 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003274}
3275
Anders Carlssonea356fb2010-04-02 05:42:15 +00003276static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003277 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003278}
3279
Anders Carlssonea356fb2010-04-02 05:42:15 +00003280static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003281 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003282 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003283 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003284
David Blaikieee000bb2013-01-17 08:49:22 +00003285 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003286}
3287
David Blaikie93c86172013-01-17 05:26:25 +00003288static void DiagnoseBaseOrMemInitializerOrder(
3289 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3290 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003291 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003292 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003293
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003294 // Don't check initializers order unless the warning is enabled at the
3295 // location of at least one initializer.
3296 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003297 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003298 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003299 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3300 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003301 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003302 ShouldCheckOrder = true;
3303 break;
3304 }
3305 }
3306 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003307 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003308
John McCalld6ca8da2010-04-10 07:37:23 +00003309 // Build the list of bases and members in the order that they'll
3310 // actually be initialized. The explicit initializers should be in
3311 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003312 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003313
Anders Carlsson071d6102010-04-02 03:38:04 +00003314 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3315
John McCalld6ca8da2010-04-10 07:37:23 +00003316 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003317 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003318 ClassDecl->vbases_begin(),
3319 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003320 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003321
John McCalld6ca8da2010-04-10 07:37:23 +00003322 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003323 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003324 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003325 if (Base->isVirtual())
3326 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003327 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003328 }
Mike Stump1eb44332009-09-09 15:08:12 +00003329
John McCalld6ca8da2010-04-10 07:37:23 +00003330 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003331 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003332 E = ClassDecl->field_end(); Field != E; ++Field) {
3333 if (Field->isUnnamedBitfield())
3334 continue;
3335
David Blaikieee000bb2013-01-17 08:49:22 +00003336 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003337 }
3338
John McCalld6ca8da2010-04-10 07:37:23 +00003339 unsigned NumIdealInits = IdealInitKeys.size();
3340 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003341
Sean Huntcbb67482011-01-08 20:30:50 +00003342 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003343 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003344 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003345 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003346
3347 // Scan forward to try to find this initializer in the idealized
3348 // initializers list.
3349 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3350 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003351 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003352
3353 // If we didn't find this initializer, it must be because we
3354 // scanned past it on a previous iteration. That can only
3355 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003356 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003357 Sema::SemaDiagnosticBuilder D =
3358 SemaRef.Diag(PrevInit->getSourceLocation(),
3359 diag::warn_initializer_out_of_order);
3360
Francois Pichet00eb3f92010-12-04 09:14:42 +00003361 if (PrevInit->isAnyMemberInitializer())
3362 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003363 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003364 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003365
Francois Pichet00eb3f92010-12-04 09:14:42 +00003366 if (Init->isAnyMemberInitializer())
3367 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003368 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003369 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003370
3371 // Move back to the initializer's location in the ideal list.
3372 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3373 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003374 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003375
3376 assert(IdealIndex != NumIdealInits &&
3377 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003378 }
John McCalld6ca8da2010-04-10 07:37:23 +00003379
3380 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003381 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003382}
3383
John McCall3c3ccdb2010-04-10 09:28:51 +00003384namespace {
3385bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003386 CXXCtorInitializer *Init,
3387 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003388 if (!PrevInit) {
3389 PrevInit = Init;
3390 return false;
3391 }
3392
3393 if (FieldDecl *Field = Init->getMember())
3394 S.Diag(Init->getSourceLocation(),
3395 diag::err_multiple_mem_initialization)
3396 << Field->getDeclName()
3397 << Init->getSourceRange();
3398 else {
John McCallf4c73712011-01-19 06:33:43 +00003399 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003400 assert(BaseClass && "neither field nor base");
3401 S.Diag(Init->getSourceLocation(),
3402 diag::err_multiple_base_initialization)
3403 << QualType(BaseClass, 0)
3404 << Init->getSourceRange();
3405 }
3406 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3407 << 0 << PrevInit->getSourceRange();
3408
3409 return true;
3410}
3411
Sean Huntcbb67482011-01-08 20:30:50 +00003412typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003413typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3414
3415bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003416 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003417 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003418 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003419 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003420 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003421
3422 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003423 if (Parent->isUnion()) {
3424 UnionEntry &En = Unions[Parent];
3425 if (En.first && En.first != Child) {
3426 S.Diag(Init->getSourceLocation(),
3427 diag::err_multiple_mem_union_initialization)
3428 << Field->getDeclName()
3429 << Init->getSourceRange();
3430 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3431 << 0 << En.second->getSourceRange();
3432 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003433 }
3434 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003435 En.first = Child;
3436 En.second = Init;
3437 }
David Blaikie6fe29652011-11-17 06:01:57 +00003438 if (!Parent->isAnonymousStructOrUnion())
3439 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003440 }
3441
3442 Child = Parent;
3443 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003444 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003445
3446 return false;
3447}
3448}
3449
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003450/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003451void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003452 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003453 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003454 bool AnyErrors) {
3455 if (!ConstructorDecl)
3456 return;
3457
3458 AdjustDeclIfTemplate(ConstructorDecl);
3459
3460 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003461 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003462
3463 if (!Constructor) {
3464 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3465 return;
3466 }
3467
John McCall3c3ccdb2010-04-10 09:28:51 +00003468 // Mapping for the duplicate initializers check.
3469 // For member initializers, this is keyed with a FieldDecl*.
3470 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003471 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003472
3473 // Mapping for the inconsistent anonymous-union initializers check.
3474 RedundantUnionMap MemberUnions;
3475
Anders Carlssonea356fb2010-04-02 05:42:15 +00003476 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003477 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003478 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003479
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003480 // Set the source order index.
3481 Init->setSourceOrder(i);
3482
Francois Pichet00eb3f92010-12-04 09:14:42 +00003483 if (Init->isAnyMemberInitializer()) {
3484 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003485 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3486 CheckRedundantUnionInit(*this, Init, MemberUnions))
3487 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003488 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003489 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3490 if (CheckRedundantInit(*this, Init, Members[Key]))
3491 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003492 } else {
3493 assert(Init->isDelegatingInitializer());
3494 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003495 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003496 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003497 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003498 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003499 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003500 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003501 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003502 // Return immediately as the initializer is set.
3503 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003504 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003505 }
3506
Anders Carlssonea356fb2010-04-02 05:42:15 +00003507 if (HadError)
3508 return;
3509
David Blaikie93c86172013-01-17 05:26:25 +00003510 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003511
David Blaikie93c86172013-01-17 05:26:25 +00003512 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003513}
3514
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003515void
John McCallef027fe2010-03-16 21:39:52 +00003516Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3517 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003518 // Ignore dependent contexts. Also ignore unions, since their members never
3519 // have destructors implicitly called.
3520 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003521 return;
John McCall58e6f342010-03-16 05:22:47 +00003522
3523 // FIXME: all the access-control diagnostics are positioned on the
3524 // field/base declaration. That's probably good; that said, the
3525 // user might reasonably want to know why the destructor is being
3526 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003527
Anders Carlsson9f853df2009-11-17 04:44:12 +00003528 // Non-static data members.
3529 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3530 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003531 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003532 if (Field->isInvalidDecl())
3533 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003534
3535 // Don't destroy incomplete or zero-length arrays.
3536 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3537 continue;
3538
Anders Carlsson9f853df2009-11-17 04:44:12 +00003539 QualType FieldType = Context.getBaseElementType(Field->getType());
3540
3541 const RecordType* RT = FieldType->getAs<RecordType>();
3542 if (!RT)
3543 continue;
3544
3545 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003546 if (FieldClassDecl->isInvalidDecl())
3547 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003548 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003549 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003550 // The destructor for an implicit anonymous union member is never invoked.
3551 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3552 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003553
Douglas Gregordb89f282010-07-01 22:47:18 +00003554 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003555 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003556 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003557 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003558 << Field->getDeclName()
3559 << FieldType);
3560
Eli Friedman5f2987c2012-02-02 03:46:19 +00003561 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003562 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003563 }
3564
John McCall58e6f342010-03-16 05:22:47 +00003565 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3566
Anders Carlsson9f853df2009-11-17 04:44:12 +00003567 // Bases.
3568 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3569 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003570 // Bases are always records in a well-formed non-dependent class.
3571 const RecordType *RT = Base->getType()->getAs<RecordType>();
3572
3573 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003574 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003575 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003576
John McCall58e6f342010-03-16 05:22:47 +00003577 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003578 // If our base class is invalid, we probably can't get its dtor anyway.
3579 if (BaseClassDecl->isInvalidDecl())
3580 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003581 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003582 continue;
John McCall58e6f342010-03-16 05:22:47 +00003583
Douglas Gregordb89f282010-07-01 22:47:18 +00003584 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003585 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003586
3587 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003588 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003589 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003590 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003591 << Base->getSourceRange(),
3592 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003593
Eli Friedman5f2987c2012-02-02 03:46:19 +00003594 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003595 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003596 }
3597
3598 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003599 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3600 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003601
3602 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003603 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003604
3605 // Ignore direct virtual bases.
3606 if (DirectVirtualBases.count(RT))
3607 continue;
3608
John McCall58e6f342010-03-16 05:22:47 +00003609 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003610 // If our base class is invalid, we probably can't get its dtor anyway.
3611 if (BaseClassDecl->isInvalidDecl())
3612 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003613 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003614 continue;
John McCall58e6f342010-03-16 05:22:47 +00003615
Douglas Gregordb89f282010-07-01 22:47:18 +00003616 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003617 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003618 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003619 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003620 << VBase->getType(),
3621 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003622
Eli Friedman5f2987c2012-02-02 03:46:19 +00003623 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003624 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003625 }
3626}
3627
John McCalld226f652010-08-21 09:40:31 +00003628void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003629 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003630 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003631
Mike Stump1eb44332009-09-09 15:08:12 +00003632 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003633 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003634 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003635}
3636
Mike Stump1eb44332009-09-09 15:08:12 +00003637bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003638 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003639 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3640 unsigned DiagID;
3641 AbstractDiagSelID SelID;
3642
3643 public:
3644 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3645 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3646
3647 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003648 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003649 if (SelID == -1)
3650 S.Diag(Loc, DiagID) << T;
3651 else
3652 S.Diag(Loc, DiagID) << SelID << T;
3653 }
3654 } Diagnoser(DiagID, SelID);
3655
3656 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003657}
3658
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003659bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003660 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003661 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003662 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003663
Anders Carlsson11f21a02009-03-23 19:10:31 +00003664 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003665 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003666
Ted Kremenek6217b802009-07-29 21:53:49 +00003667 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003668 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003669 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003670 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003671
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003672 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003673 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003674 }
Mike Stump1eb44332009-09-09 15:08:12 +00003675
Ted Kremenek6217b802009-07-29 21:53:49 +00003676 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003677 if (!RT)
3678 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003679
John McCall86ff3082010-02-04 22:26:26 +00003680 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003681
John McCall94c3b562010-08-18 09:41:07 +00003682 // We can't answer whether something is abstract until it has a
3683 // definition. If it's currently being defined, we'll walk back
3684 // over all the declarations when we have a full definition.
3685 const CXXRecordDecl *Def = RD->getDefinition();
3686 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003687 return false;
3688
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003689 if (!RD->isAbstract())
3690 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003691
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003692 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003693 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003694
John McCall94c3b562010-08-18 09:41:07 +00003695 return true;
3696}
3697
3698void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3699 // Check if we've already emitted the list of pure virtual functions
3700 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003701 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003702 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003703
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003704 CXXFinalOverriderMap FinalOverriders;
3705 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003706
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003707 // Keep a set of seen pure methods so we won't diagnose the same method
3708 // more than once.
3709 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3710
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003711 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3712 MEnd = FinalOverriders.end();
3713 M != MEnd;
3714 ++M) {
3715 for (OverridingMethods::iterator SO = M->second.begin(),
3716 SOEnd = M->second.end();
3717 SO != SOEnd; ++SO) {
3718 // C++ [class.abstract]p4:
3719 // A class is abstract if it contains or inherits at least one
3720 // pure virtual function for which the final overrider is pure
3721 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003722
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003723 //
3724 if (SO->second.size() != 1)
3725 continue;
3726
3727 if (!SO->second.front().Method->isPure())
3728 continue;
3729
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003730 if (!SeenPureMethods.insert(SO->second.front().Method))
3731 continue;
3732
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003733 Diag(SO->second.front().Method->getLocation(),
3734 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003735 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003736 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003737 }
3738
3739 if (!PureVirtualClassDiagSet)
3740 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3741 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003742}
3743
Anders Carlsson8211eff2009-03-24 01:19:16 +00003744namespace {
John McCall94c3b562010-08-18 09:41:07 +00003745struct AbstractUsageInfo {
3746 Sema &S;
3747 CXXRecordDecl *Record;
3748 CanQualType AbstractType;
3749 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003750
John McCall94c3b562010-08-18 09:41:07 +00003751 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3752 : S(S), Record(Record),
3753 AbstractType(S.Context.getCanonicalType(
3754 S.Context.getTypeDeclType(Record))),
3755 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003756
John McCall94c3b562010-08-18 09:41:07 +00003757 void DiagnoseAbstractType() {
3758 if (Invalid) return;
3759 S.DiagnoseAbstractType(Record);
3760 Invalid = true;
3761 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003762
John McCall94c3b562010-08-18 09:41:07 +00003763 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3764};
3765
3766struct CheckAbstractUsage {
3767 AbstractUsageInfo &Info;
3768 const NamedDecl *Ctx;
3769
3770 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3771 : Info(Info), Ctx(Ctx) {}
3772
3773 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3774 switch (TL.getTypeLocClass()) {
3775#define ABSTRACT_TYPELOC(CLASS, PARENT)
3776#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003777 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003778#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003779 }
John McCall94c3b562010-08-18 09:41:07 +00003780 }
Mike Stump1eb44332009-09-09 15:08:12 +00003781
John McCall94c3b562010-08-18 09:41:07 +00003782 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3783 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3784 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003785 if (!TL.getArg(I))
3786 continue;
3787
John McCall94c3b562010-08-18 09:41:07 +00003788 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3789 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003790 }
John McCall94c3b562010-08-18 09:41:07 +00003791 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003792
John McCall94c3b562010-08-18 09:41:07 +00003793 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3794 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3795 }
Mike Stump1eb44332009-09-09 15:08:12 +00003796
John McCall94c3b562010-08-18 09:41:07 +00003797 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3798 // Visit the type parameters from a permissive context.
3799 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3800 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3801 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3802 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3803 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3804 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003805 }
John McCall94c3b562010-08-18 09:41:07 +00003806 }
Mike Stump1eb44332009-09-09 15:08:12 +00003807
John McCall94c3b562010-08-18 09:41:07 +00003808 // Visit pointee types from a permissive context.
3809#define CheckPolymorphic(Type) \
3810 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3811 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3812 }
3813 CheckPolymorphic(PointerTypeLoc)
3814 CheckPolymorphic(ReferenceTypeLoc)
3815 CheckPolymorphic(MemberPointerTypeLoc)
3816 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003817 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003818
John McCall94c3b562010-08-18 09:41:07 +00003819 /// Handle all the types we haven't given a more specific
3820 /// implementation for above.
3821 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3822 // Every other kind of type that we haven't called out already
3823 // that has an inner type is either (1) sugar or (2) contains that
3824 // inner type in some way as a subobject.
3825 if (TypeLoc Next = TL.getNextTypeLoc())
3826 return Visit(Next, Sel);
3827
3828 // If there's no inner type and we're in a permissive context,
3829 // don't diagnose.
3830 if (Sel == Sema::AbstractNone) return;
3831
3832 // Check whether the type matches the abstract type.
3833 QualType T = TL.getType();
3834 if (T->isArrayType()) {
3835 Sel = Sema::AbstractArrayType;
3836 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003837 }
John McCall94c3b562010-08-18 09:41:07 +00003838 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3839 if (CT != Info.AbstractType) return;
3840
3841 // It matched; do some magic.
3842 if (Sel == Sema::AbstractArrayType) {
3843 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3844 << T << TL.getSourceRange();
3845 } else {
3846 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3847 << Sel << T << TL.getSourceRange();
3848 }
3849 Info.DiagnoseAbstractType();
3850 }
3851};
3852
3853void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3854 Sema::AbstractDiagSelID Sel) {
3855 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3856}
3857
3858}
3859
3860/// Check for invalid uses of an abstract type in a method declaration.
3861static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3862 CXXMethodDecl *MD) {
3863 // No need to do the check on definitions, which require that
3864 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003865 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003866 return;
3867
3868 // For safety's sake, just ignore it if we don't have type source
3869 // information. This should never happen for non-implicit methods,
3870 // but...
3871 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3872 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3873}
3874
3875/// Check for invalid uses of an abstract type within a class definition.
3876static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3877 CXXRecordDecl *RD) {
3878 for (CXXRecordDecl::decl_iterator
3879 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3880 Decl *D = *I;
3881 if (D->isImplicit()) continue;
3882
3883 // Methods and method templates.
3884 if (isa<CXXMethodDecl>(D)) {
3885 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3886 } else if (isa<FunctionTemplateDecl>(D)) {
3887 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3888 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3889
3890 // Fields and static variables.
3891 } else if (isa<FieldDecl>(D)) {
3892 FieldDecl *FD = cast<FieldDecl>(D);
3893 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3894 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3895 } else if (isa<VarDecl>(D)) {
3896 VarDecl *VD = cast<VarDecl>(D);
3897 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3898 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3899
3900 // Nested classes and class templates.
3901 } else if (isa<CXXRecordDecl>(D)) {
3902 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3903 } else if (isa<ClassTemplateDecl>(D)) {
3904 CheckAbstractClassUsage(Info,
3905 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3906 }
3907 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003908}
3909
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003910/// \brief Perform semantic checks on a class definition that has been
3911/// completing, introducing implicitly-declared members, checking for
3912/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003913void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003914 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003915 return;
3916
John McCall94c3b562010-08-18 09:41:07 +00003917 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3918 AbstractUsageInfo Info(*this, Record);
3919 CheckAbstractClassUsage(Info, Record);
3920 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003921
3922 // If this is not an aggregate type and has no user-declared constructor,
3923 // complain about any non-static data members of reference or const scalar
3924 // type, since they will never get initializers.
3925 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003926 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3927 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003928 bool Complained = false;
3929 for (RecordDecl::field_iterator F = Record->field_begin(),
3930 FEnd = Record->field_end();
3931 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003932 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003933 continue;
3934
Douglas Gregor325e5932010-04-15 00:00:53 +00003935 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003936 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003937 if (!Complained) {
3938 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3939 << Record->getTagKind() << Record;
3940 Complained = true;
3941 }
3942
3943 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3944 << F->getType()->isReferenceType()
3945 << F->getDeclName();
3946 }
3947 }
3948 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003949
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003950 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003951 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003952
3953 if (Record->getIdentifier()) {
3954 // C++ [class.mem]p13:
3955 // If T is the name of a class, then each of the following shall have a
3956 // name different from T:
3957 // - every member of every anonymous union that is a member of class T.
3958 //
3959 // C++ [class.mem]p14:
3960 // In addition, if class T has a user-declared constructor (12.1), every
3961 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00003962 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3963 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3964 ++I) {
3965 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00003966 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3967 isa<IndirectFieldDecl>(D)) {
3968 Diag(D->getLocation(), diag::err_member_name_of_class)
3969 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003970 break;
3971 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003972 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003973 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003974
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003975 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003976 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003977 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003978 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003979 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3980 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3981 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003982
David Blaikieb6b5b972012-09-21 03:21:07 +00003983 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
3984 Diag(Record->getLocation(), diag::warn_abstract_final_class);
3985 DiagnoseAbstractType(Record);
3986 }
3987
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003988 if (!Record->isDependentType()) {
3989 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3990 MEnd = Record->method_end();
3991 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00003992 // See if a method overloads virtual methods in a base
3993 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00003994 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003995 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00003996
3997 // Check whether the explicitly-defaulted special members are valid.
3998 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
3999 CheckExplicitlyDefaultedSpecialMember(*M);
4000
4001 // For an explicitly defaulted or deleted special member, we defer
4002 // determining triviality until the class is complete. That time is now!
4003 if (!M->isImplicit() && !M->isUserProvided()) {
4004 CXXSpecialMember CSM = getSpecialMember(*M);
4005 if (CSM != CXXInvalid) {
4006 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4007
4008 // Inform the class that we've finished declaring this member.
4009 Record->finishedDefaultedOrDeletedMember(*M);
4010 }
4011 }
4012 }
4013 }
4014
4015 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4016 // function that is not a constructor declares that member function to be
4017 // const. [...] The class of which that function is a member shall be
4018 // a literal type.
4019 //
4020 // If the class has virtual bases, any constexpr members will already have
4021 // been diagnosed by the checks performed on the member declaration, so
4022 // suppress this (less useful) diagnostic.
4023 //
4024 // We delay this until we know whether an explicitly-defaulted (or deleted)
4025 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004026 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004027 !Record->isLiteral() && !Record->getNumVBases()) {
4028 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4029 MEnd = Record->method_end();
4030 M != MEnd; ++M) {
4031 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4032 switch (Record->getTemplateSpecializationKind()) {
4033 case TSK_ImplicitInstantiation:
4034 case TSK_ExplicitInstantiationDeclaration:
4035 case TSK_ExplicitInstantiationDefinition:
4036 // If a template instantiates to a non-literal type, but its members
4037 // instantiate to constexpr functions, the template is technically
4038 // ill-formed, but we allow it for sanity.
4039 continue;
4040
4041 case TSK_Undeclared:
4042 case TSK_ExplicitSpecialization:
4043 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4044 diag::err_constexpr_method_non_literal);
4045 break;
4046 }
4047
4048 // Only produce one error per class.
4049 break;
4050 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004051 }
4052 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004053
4054 // Declare inherited constructors. We do this eagerly here because:
4055 // - The standard requires an eager diagnostic for conflicting inherited
4056 // constructors from different classes.
4057 // - The lazy declaration of the other implicit constructors is so as to not
4058 // waste space and performance on classes that are not meant to be
4059 // instantiated (e.g. meta-functions). This doesn't apply to classes that
4060 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004061 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004062}
4063
Richard Smith7756afa2012-06-10 05:43:50 +00004064/// Is the special member function which would be selected to perform the
4065/// specified operation on the specified class type a constexpr constructor?
4066static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4067 Sema::CXXSpecialMember CSM,
4068 bool ConstArg) {
4069 Sema::SpecialMemberOverloadResult *SMOR =
4070 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4071 false, false, false, false);
4072 if (!SMOR || !SMOR->getMethod())
4073 // A constructor we wouldn't select can't be "involved in initializing"
4074 // anything.
4075 return true;
4076 return SMOR->getMethod()->isConstexpr();
4077}
4078
4079/// Determine whether the specified special member function would be constexpr
4080/// if it were implicitly defined.
4081static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4082 Sema::CXXSpecialMember CSM,
4083 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004084 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004085 return false;
4086
4087 // C++11 [dcl.constexpr]p4:
4088 // In the definition of a constexpr constructor [...]
4089 switch (CSM) {
4090 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004091 // Since default constructor lookup is essentially trivial (and cannot
4092 // involve, for instance, template instantiation), we compute whether a
4093 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4094 //
4095 // This is important for performance; we need to know whether the default
4096 // constructor is constexpr to determine whether the type is a literal type.
4097 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4098
Richard Smith7756afa2012-06-10 05:43:50 +00004099 case Sema::CXXCopyConstructor:
4100 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004101 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004102 break;
4103
4104 case Sema::CXXCopyAssignment:
4105 case Sema::CXXMoveAssignment:
4106 case Sema::CXXDestructor:
4107 case Sema::CXXInvalid:
4108 return false;
4109 }
4110
4111 // -- if the class is a non-empty union, or for each non-empty anonymous
4112 // union member of a non-union class, exactly one non-static data member
4113 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004114 //
4115 // If we squint, this is guaranteed, since exactly one non-static data member
4116 // will be initialized (if the constructor isn't deleted), we just don't know
4117 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004118 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004119 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004120
4121 // -- the class shall not have any virtual base classes;
4122 if (ClassDecl->getNumVBases())
4123 return false;
4124
4125 // -- every constructor involved in initializing [...] base class
4126 // sub-objects shall be a constexpr constructor;
4127 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4128 BEnd = ClassDecl->bases_end();
4129 B != BEnd; ++B) {
4130 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4131 if (!BaseType) continue;
4132
4133 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4134 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4135 return false;
4136 }
4137
4138 // -- every constructor involved in initializing non-static data members
4139 // [...] shall be a constexpr constructor;
4140 // -- every non-static data member and base class sub-object shall be
4141 // initialized
4142 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4143 FEnd = ClassDecl->field_end();
4144 F != FEnd; ++F) {
4145 if (F->isInvalidDecl())
4146 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004147 if (const RecordType *RecordTy =
4148 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004149 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4150 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4151 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004152 }
4153 }
4154
4155 // All OK, it's constexpr!
4156 return true;
4157}
4158
Richard Smithb9d0b762012-07-27 04:22:15 +00004159static Sema::ImplicitExceptionSpecification
4160computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4161 switch (S.getSpecialMember(MD)) {
4162 case Sema::CXXDefaultConstructor:
4163 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4164 case Sema::CXXCopyConstructor:
4165 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4166 case Sema::CXXCopyAssignment:
4167 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4168 case Sema::CXXMoveConstructor:
4169 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4170 case Sema::CXXMoveAssignment:
4171 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4172 case Sema::CXXDestructor:
4173 return S.ComputeDefaultedDtorExceptionSpec(MD);
4174 case Sema::CXXInvalid:
4175 break;
4176 }
4177 llvm_unreachable("only special members have implicit exception specs");
4178}
4179
Richard Smithdd25e802012-07-30 23:48:14 +00004180static void
4181updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4182 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4183 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4184 ExceptSpec.getEPI(EPI);
4185 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4186 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4187 FPT->getNumArgs(), EPI));
4188 FD->setType(QualType(NewFPT, 0));
4189}
4190
Richard Smithb9d0b762012-07-27 04:22:15 +00004191void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4192 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4193 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4194 return;
4195
Richard Smithdd25e802012-07-30 23:48:14 +00004196 // Evaluate the exception specification.
4197 ImplicitExceptionSpecification ExceptSpec =
4198 computeImplicitExceptionSpec(*this, Loc, MD);
4199
4200 // Update the type of the special member to use it.
4201 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4202
4203 // A user-provided destructor can be defined outside the class. When that
4204 // happens, be sure to update the exception specification on both
4205 // declarations.
4206 const FunctionProtoType *CanonicalFPT =
4207 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4208 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4209 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4210 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004211}
4212
Richard Smith3003e1d2012-05-15 04:39:51 +00004213void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4214 CXXRecordDecl *RD = MD->getParent();
4215 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004216
Richard Smith3003e1d2012-05-15 04:39:51 +00004217 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4218 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004219
4220 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004221 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004222 bool First = MD == MD->getCanonicalDecl();
4223
4224 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004225
4226 // C++11 [dcl.fct.def.default]p1:
4227 // A function that is explicitly defaulted shall
4228 // -- be a special member function (checked elsewhere),
4229 // -- have the same type (except for ref-qualifiers, and except that a
4230 // copy operation can take a non-const reference) as an implicit
4231 // declaration, and
4232 // -- not have default arguments.
4233 unsigned ExpectedParams = 1;
4234 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4235 ExpectedParams = 0;
4236 if (MD->getNumParams() != ExpectedParams) {
4237 // This also checks for default arguments: a copy or move constructor with a
4238 // default argument is classified as a default constructor, and assignment
4239 // operations and destructors can't have default arguments.
4240 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4241 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004242 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004243 } else if (MD->isVariadic()) {
4244 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4245 << CSM << MD->getSourceRange();
4246 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004247 }
4248
Richard Smith3003e1d2012-05-15 04:39:51 +00004249 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004250
Richard Smith7756afa2012-06-10 05:43:50 +00004251 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004252 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004253 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004254 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004255 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004256
Richard Smith3003e1d2012-05-15 04:39:51 +00004257 QualType ReturnType = Context.VoidTy;
4258 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4259 // Check for return type matching.
4260 ReturnType = Type->getResultType();
4261 QualType ExpectedReturnType =
4262 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4263 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4264 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4265 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4266 HadError = true;
4267 }
4268
4269 // A defaulted special member cannot have cv-qualifiers.
4270 if (Type->getTypeQuals()) {
4271 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4272 << (CSM == CXXMoveAssignment);
4273 HadError = true;
4274 }
4275 }
4276
4277 // Check for parameter type matching.
4278 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004279 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004280 if (ExpectedParams && ArgType->isReferenceType()) {
4281 // Argument must be reference to possibly-const T.
4282 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004283 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004284
4285 if (ReferentType.isVolatileQualified()) {
4286 Diag(MD->getLocation(),
4287 diag::err_defaulted_special_member_volatile_param) << CSM;
4288 HadError = true;
4289 }
4290
Richard Smith7756afa2012-06-10 05:43:50 +00004291 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004292 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4293 Diag(MD->getLocation(),
4294 diag::err_defaulted_special_member_copy_const_param)
4295 << (CSM == CXXCopyAssignment);
4296 // FIXME: Explain why this special member can't be const.
4297 } else {
4298 Diag(MD->getLocation(),
4299 diag::err_defaulted_special_member_move_const_param)
4300 << (CSM == CXXMoveAssignment);
4301 }
4302 HadError = true;
4303 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004304 } else if (ExpectedParams) {
4305 // A copy assignment operator can take its argument by value, but a
4306 // defaulted one cannot.
4307 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004308 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004309 HadError = true;
4310 }
Sean Huntbe631222011-05-17 20:44:43 +00004311
Richard Smith61802452011-12-22 02:22:31 +00004312 // C++11 [dcl.fct.def.default]p2:
4313 // An explicitly-defaulted function may be declared constexpr only if it
4314 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004315 // Do not apply this rule to members of class templates, since core issue 1358
4316 // makes such functions always instantiate to constexpr functions. For
4317 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004318 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4319 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004320 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4321 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4322 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004323 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004324 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004325 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004326
Richard Smith61802452011-12-22 02:22:31 +00004327 // and may have an explicit exception-specification only if it is compatible
4328 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004329 if (Type->hasExceptionSpec()) {
4330 // Delay the check if this is the first declaration of the special member,
4331 // since we may not have parsed some necessary in-class initializers yet.
4332 if (First)
4333 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4334 else
4335 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4336 }
Richard Smith61802452011-12-22 02:22:31 +00004337
4338 // If a function is explicitly defaulted on its first declaration,
4339 if (First) {
4340 // -- it is implicitly considered to be constexpr if the implicit
4341 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004342 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004343
Richard Smith3003e1d2012-05-15 04:39:51 +00004344 // -- it is implicitly considered to have the same exception-specification
4345 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004346 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4347 EPI.ExceptionSpecType = EST_Unevaluated;
4348 EPI.ExceptionSpecDecl = MD;
4349 MD->setType(Context.getFunctionType(ReturnType, &ArgType,
4350 ExpectedParams, EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004351 }
4352
Richard Smith3003e1d2012-05-15 04:39:51 +00004353 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004354 if (First) {
4355 MD->setDeletedAsWritten();
4356 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004357 // C++11 [dcl.fct.def.default]p4:
4358 // [For a] user-provided explicitly-defaulted function [...] if such a
4359 // function is implicitly defined as deleted, the program is ill-formed.
4360 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4361 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004362 }
4363 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004364
Richard Smith3003e1d2012-05-15 04:39:51 +00004365 if (HadError)
4366 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004367}
4368
Richard Smith1d28caf2012-12-11 01:14:52 +00004369/// Check whether the exception specification provided for an
4370/// explicitly-defaulted special member matches the exception specification
4371/// that would have been generated for an implicit special member, per
4372/// C++11 [dcl.fct.def.default]p2.
4373void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4374 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4375 // Compute the implicit exception specification.
4376 FunctionProtoType::ExtProtoInfo EPI;
4377 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4378 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4379 Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4380
4381 // Ensure that it matches.
4382 CheckEquivalentExceptionSpec(
4383 PDiag(diag::err_incorrect_defaulted_exception_spec)
4384 << getSpecialMember(MD), PDiag(),
4385 ImplicitType, SourceLocation(),
4386 SpecifiedType, MD->getLocation());
4387}
4388
4389void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4390 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4391 I != N; ++I)
4392 CheckExplicitlyDefaultedMemberExceptionSpec(
4393 DelayedDefaultedMemberExceptionSpecs[I].first,
4394 DelayedDefaultedMemberExceptionSpecs[I].second);
4395
4396 DelayedDefaultedMemberExceptionSpecs.clear();
4397}
4398
Richard Smith7d5088a2012-02-18 02:02:13 +00004399namespace {
4400struct SpecialMemberDeletionInfo {
4401 Sema &S;
4402 CXXMethodDecl *MD;
4403 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004404 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004405
4406 // Properties of the special member, computed for convenience.
4407 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4408 SourceLocation Loc;
4409
4410 bool AllFieldsAreConst;
4411
4412 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004413 Sema::CXXSpecialMember CSM, bool Diagnose)
4414 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004415 IsConstructor(false), IsAssignment(false), IsMove(false),
4416 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4417 AllFieldsAreConst(true) {
4418 switch (CSM) {
4419 case Sema::CXXDefaultConstructor:
4420 case Sema::CXXCopyConstructor:
4421 IsConstructor = true;
4422 break;
4423 case Sema::CXXMoveConstructor:
4424 IsConstructor = true;
4425 IsMove = true;
4426 break;
4427 case Sema::CXXCopyAssignment:
4428 IsAssignment = true;
4429 break;
4430 case Sema::CXXMoveAssignment:
4431 IsAssignment = true;
4432 IsMove = true;
4433 break;
4434 case Sema::CXXDestructor:
4435 break;
4436 case Sema::CXXInvalid:
4437 llvm_unreachable("invalid special member kind");
4438 }
4439
4440 if (MD->getNumParams()) {
4441 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4442 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4443 }
4444 }
4445
4446 bool inUnion() const { return MD->getParent()->isUnion(); }
4447
4448 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004449 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4450 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004451 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004452 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4453 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4454 Quals = 0;
4455 return S.LookupSpecialMember(Class, CSM,
4456 ConstArg || (Quals & Qualifiers::Const),
4457 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004458 MD->getRefQualifier() == RQ_RValue,
4459 TQ & Qualifiers::Const,
4460 TQ & Qualifiers::Volatile);
4461 }
4462
Richard Smith6c4c36c2012-03-30 20:53:28 +00004463 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004464
Richard Smith6c4c36c2012-03-30 20:53:28 +00004465 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004466 bool shouldDeleteForField(FieldDecl *FD);
4467 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004468
Richard Smith517bb842012-07-18 03:51:16 +00004469 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4470 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004471 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4472 Sema::SpecialMemberOverloadResult *SMOR,
4473 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004474
4475 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004476};
4477}
4478
John McCall12d8d802012-04-09 20:53:23 +00004479/// Is the given special member inaccessible when used on the given
4480/// sub-object.
4481bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4482 CXXMethodDecl *target) {
4483 /// If we're operating on a base class, the object type is the
4484 /// type of this special member.
4485 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004486 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004487 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4488 objectTy = S.Context.getTypeDeclType(MD->getParent());
4489 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4490
4491 // If we're operating on a field, the object type is the type of the field.
4492 } else {
4493 objectTy = S.Context.getTypeDeclType(target->getParent());
4494 }
4495
4496 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4497}
4498
Richard Smith6c4c36c2012-03-30 20:53:28 +00004499/// Check whether we should delete a special member due to the implicit
4500/// definition containing a call to a special member of a subobject.
4501bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4502 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4503 bool IsDtorCallInCtor) {
4504 CXXMethodDecl *Decl = SMOR->getMethod();
4505 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4506
4507 int DiagKind = -1;
4508
4509 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4510 DiagKind = !Decl ? 0 : 1;
4511 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4512 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004513 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004514 DiagKind = 3;
4515 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4516 !Decl->isTrivial()) {
4517 // A member of a union must have a trivial corresponding special member.
4518 // As a weird special case, a destructor call from a union's constructor
4519 // must be accessible and non-deleted, but need not be trivial. Such a
4520 // destructor is never actually called, but is semantically checked as
4521 // if it were.
4522 DiagKind = 4;
4523 }
4524
4525 if (DiagKind == -1)
4526 return false;
4527
4528 if (Diagnose) {
4529 if (Field) {
4530 S.Diag(Field->getLocation(),
4531 diag::note_deleted_special_member_class_subobject)
4532 << CSM << MD->getParent() << /*IsField*/true
4533 << Field << DiagKind << IsDtorCallInCtor;
4534 } else {
4535 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4536 S.Diag(Base->getLocStart(),
4537 diag::note_deleted_special_member_class_subobject)
4538 << CSM << MD->getParent() << /*IsField*/false
4539 << Base->getType() << DiagKind << IsDtorCallInCtor;
4540 }
4541
4542 if (DiagKind == 1)
4543 S.NoteDeletedFunction(Decl);
4544 // FIXME: Explain inaccessibility if DiagKind == 3.
4545 }
4546
4547 return true;
4548}
4549
Richard Smith9a561d52012-02-26 09:11:52 +00004550/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004551/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004552bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004553 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004554 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004555
4556 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004557 // -- any direct or virtual base class, or non-static data member with no
4558 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004559 // either M has no default constructor or overload resolution as applied
4560 // to M's default constructor results in an ambiguity or in a function
4561 // that is deleted or inaccessible
4562 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4563 // -- a direct or virtual base class B that cannot be copied/moved because
4564 // overload resolution, as applied to B's corresponding special member,
4565 // results in an ambiguity or a function that is deleted or inaccessible
4566 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004567 // C++11 [class.dtor]p5:
4568 // -- any direct or virtual base class [...] has a type with a destructor
4569 // that is deleted or inaccessible
4570 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004571 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004572 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004573 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004574
Richard Smith6c4c36c2012-03-30 20:53:28 +00004575 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4576 // -- any direct or virtual base class or non-static data member has a
4577 // type with a destructor that is deleted or inaccessible
4578 if (IsConstructor) {
4579 Sema::SpecialMemberOverloadResult *SMOR =
4580 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4581 false, false, false, false, false);
4582 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4583 return true;
4584 }
4585
Richard Smith9a561d52012-02-26 09:11:52 +00004586 return false;
4587}
4588
4589/// Check whether we should delete a special member function due to the class
4590/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004591bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004592 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004593 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004594}
4595
4596/// Check whether we should delete a special member function due to the class
4597/// having a particular non-static data member.
4598bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4599 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4600 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4601
4602 if (CSM == Sema::CXXDefaultConstructor) {
4603 // For a default constructor, all references must be initialized in-class
4604 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004605 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4606 if (Diagnose)
4607 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4608 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004609 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004610 }
Richard Smith79363f52012-02-27 06:07:25 +00004611 // C++11 [class.ctor]p5: any non-variant non-static data member of
4612 // const-qualified type (or array thereof) with no
4613 // brace-or-equal-initializer does not have a user-provided default
4614 // constructor.
4615 if (!inUnion() && FieldType.isConstQualified() &&
4616 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004617 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4618 if (Diagnose)
4619 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004620 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004621 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004622 }
4623
4624 if (inUnion() && !FieldType.isConstQualified())
4625 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004626 } else if (CSM == Sema::CXXCopyConstructor) {
4627 // For a copy constructor, data members must not be of rvalue reference
4628 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004629 if (FieldType->isRValueReferenceType()) {
4630 if (Diagnose)
4631 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4632 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004633 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004634 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004635 } else if (IsAssignment) {
4636 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004637 if (FieldType->isReferenceType()) {
4638 if (Diagnose)
4639 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4640 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004641 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004642 }
4643 if (!FieldRecord && FieldType.isConstQualified()) {
4644 // C++11 [class.copy]p23:
4645 // -- a non-static data member of const non-class type (or array thereof)
4646 if (Diagnose)
4647 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004648 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004649 return true;
4650 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004651 }
4652
4653 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004654 // Some additional restrictions exist on the variant members.
4655 if (!inUnion() && FieldRecord->isUnion() &&
4656 FieldRecord->isAnonymousStructOrUnion()) {
4657 bool AllVariantFieldsAreConst = true;
4658
Richard Smithdf8dc862012-03-29 19:00:10 +00004659 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004660 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4661 UE = FieldRecord->field_end();
4662 UI != UE; ++UI) {
4663 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004664
4665 if (!UnionFieldType.isConstQualified())
4666 AllVariantFieldsAreConst = false;
4667
Richard Smith9a561d52012-02-26 09:11:52 +00004668 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4669 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004670 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4671 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004672 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004673 }
4674
4675 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004676 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004677 FieldRecord->field_begin() != FieldRecord->field_end()) {
4678 if (Diagnose)
4679 S.Diag(FieldRecord->getLocation(),
4680 diag::note_deleted_default_ctor_all_const)
4681 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004682 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004683 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004684
Richard Smithdf8dc862012-03-29 19:00:10 +00004685 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004686 // This is technically non-conformant, but sanity demands it.
4687 return false;
4688 }
4689
Richard Smith517bb842012-07-18 03:51:16 +00004690 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4691 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004692 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004693 }
4694
4695 return false;
4696}
4697
4698/// C++11 [class.ctor] p5:
4699/// A defaulted default constructor for a class X is defined as deleted if
4700/// X is a union and all of its variant members are of const-qualified type.
4701bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004702 // This is a silly definition, because it gives an empty union a deleted
4703 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004704 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4705 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4706 if (Diagnose)
4707 S.Diag(MD->getParent()->getLocation(),
4708 diag::note_deleted_default_ctor_all_const)
4709 << MD->getParent() << /*not anonymous union*/0;
4710 return true;
4711 }
4712 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004713}
4714
4715/// Determine whether a defaulted special member function should be defined as
4716/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4717/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004718bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4719 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004720 if (MD->isInvalidDecl())
4721 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004722 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004723 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004724 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004725 return false;
4726
Richard Smith7d5088a2012-02-18 02:02:13 +00004727 // C++11 [expr.lambda.prim]p19:
4728 // The closure type associated with a lambda-expression has a
4729 // deleted (8.4.3) default constructor and a deleted copy
4730 // assignment operator.
4731 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004732 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4733 if (Diagnose)
4734 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004735 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004736 }
4737
Richard Smith5bdaac52012-04-02 20:59:25 +00004738 // For an anonymous struct or union, the copy and assignment special members
4739 // will never be used, so skip the check. For an anonymous union declared at
4740 // namespace scope, the constructor and destructor are used.
4741 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4742 RD->isAnonymousStructOrUnion())
4743 return false;
4744
Richard Smith6c4c36c2012-03-30 20:53:28 +00004745 // C++11 [class.copy]p7, p18:
4746 // If the class definition declares a move constructor or move assignment
4747 // operator, an implicitly declared copy constructor or copy assignment
4748 // operator is defined as deleted.
4749 if (MD->isImplicit() &&
4750 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4751 CXXMethodDecl *UserDeclaredMove = 0;
4752
4753 // In Microsoft mode, a user-declared move only causes the deletion of the
4754 // corresponding copy operation, not both copy operations.
4755 if (RD->hasUserDeclaredMoveConstructor() &&
4756 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4757 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004758
4759 // Find any user-declared move constructor.
4760 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4761 E = RD->ctor_end(); I != E; ++I) {
4762 if (I->isMoveConstructor()) {
4763 UserDeclaredMove = *I;
4764 break;
4765 }
4766 }
Richard Smith1c931be2012-04-02 18:40:40 +00004767 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004768 } else if (RD->hasUserDeclaredMoveAssignment() &&
4769 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4770 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004771
4772 // Find any user-declared move assignment operator.
4773 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4774 E = RD->method_end(); I != E; ++I) {
4775 if (I->isMoveAssignmentOperator()) {
4776 UserDeclaredMove = *I;
4777 break;
4778 }
4779 }
Richard Smith1c931be2012-04-02 18:40:40 +00004780 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004781 }
4782
4783 if (UserDeclaredMove) {
4784 Diag(UserDeclaredMove->getLocation(),
4785 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004786 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004787 << UserDeclaredMove->isMoveAssignmentOperator();
4788 return true;
4789 }
4790 }
Sean Hunte16da072011-10-10 06:18:57 +00004791
Richard Smith5bdaac52012-04-02 20:59:25 +00004792 // Do access control from the special member function
4793 ContextRAII MethodContext(*this, MD);
4794
Richard Smith9a561d52012-02-26 09:11:52 +00004795 // C++11 [class.dtor]p5:
4796 // -- for a virtual destructor, lookup of the non-array deallocation function
4797 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004798 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004799 FunctionDecl *OperatorDelete = 0;
4800 DeclarationName Name =
4801 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4802 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004803 OperatorDelete, false)) {
4804 if (Diagnose)
4805 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004806 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004807 }
Richard Smith9a561d52012-02-26 09:11:52 +00004808 }
4809
Richard Smith6c4c36c2012-03-30 20:53:28 +00004810 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004811
Sean Huntcdee3fe2011-05-11 22:34:38 +00004812 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004813 BE = RD->bases_end(); BI != BE; ++BI)
4814 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004815 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004816 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004817
4818 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004819 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004820 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004821 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004822
4823 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004824 FE = RD->field_end(); FI != FE; ++FI)
4825 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004826 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004827 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004828
Richard Smith7d5088a2012-02-18 02:02:13 +00004829 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004830 return true;
4831
4832 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004833}
4834
Richard Smithac713512012-12-08 02:53:02 +00004835/// Perform lookup for a special member of the specified kind, and determine
4836/// whether it is trivial. If the triviality can be determined without the
4837/// lookup, skip it. This is intended for use when determining whether a
4838/// special member of a containing object is trivial, and thus does not ever
4839/// perform overload resolution for default constructors.
4840///
4841/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4842/// member that was most likely to be intended to be trivial, if any.
4843static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4844 Sema::CXXSpecialMember CSM, unsigned Quals,
4845 CXXMethodDecl **Selected) {
4846 if (Selected)
4847 *Selected = 0;
4848
4849 switch (CSM) {
4850 case Sema::CXXInvalid:
4851 llvm_unreachable("not a special member");
4852
4853 case Sema::CXXDefaultConstructor:
4854 // C++11 [class.ctor]p5:
4855 // A default constructor is trivial if:
4856 // - all the [direct subobjects] have trivial default constructors
4857 //
4858 // Note, no overload resolution is performed in this case.
4859 if (RD->hasTrivialDefaultConstructor())
4860 return true;
4861
4862 if (Selected) {
4863 // If there's a default constructor which could have been trivial, dig it
4864 // out. Otherwise, if there's any user-provided default constructor, point
4865 // to that as an example of why there's not a trivial one.
4866 CXXConstructorDecl *DefCtor = 0;
4867 if (RD->needsImplicitDefaultConstructor())
4868 S.DeclareImplicitDefaultConstructor(RD);
4869 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4870 CE = RD->ctor_end(); CI != CE; ++CI) {
4871 if (!CI->isDefaultConstructor())
4872 continue;
4873 DefCtor = *CI;
4874 if (!DefCtor->isUserProvided())
4875 break;
4876 }
4877
4878 *Selected = DefCtor;
4879 }
4880
4881 return false;
4882
4883 case Sema::CXXDestructor:
4884 // C++11 [class.dtor]p5:
4885 // A destructor is trivial if:
4886 // - all the direct [subobjects] have trivial destructors
4887 if (RD->hasTrivialDestructor())
4888 return true;
4889
4890 if (Selected) {
4891 if (RD->needsImplicitDestructor())
4892 S.DeclareImplicitDestructor(RD);
4893 *Selected = RD->getDestructor();
4894 }
4895
4896 return false;
4897
4898 case Sema::CXXCopyConstructor:
4899 // C++11 [class.copy]p12:
4900 // A copy constructor is trivial if:
4901 // - the constructor selected to copy each direct [subobject] is trivial
4902 if (RD->hasTrivialCopyConstructor()) {
4903 if (Quals == Qualifiers::Const)
4904 // We must either select the trivial copy constructor or reach an
4905 // ambiguity; no need to actually perform overload resolution.
4906 return true;
4907 } else if (!Selected) {
4908 return false;
4909 }
4910 // In C++98, we are not supposed to perform overload resolution here, but we
4911 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4912 // cases like B as having a non-trivial copy constructor:
4913 // struct A { template<typename T> A(T&); };
4914 // struct B { mutable A a; };
4915 goto NeedOverloadResolution;
4916
4917 case Sema::CXXCopyAssignment:
4918 // C++11 [class.copy]p25:
4919 // A copy assignment operator is trivial if:
4920 // - the assignment operator selected to copy each direct [subobject] is
4921 // trivial
4922 if (RD->hasTrivialCopyAssignment()) {
4923 if (Quals == Qualifiers::Const)
4924 return true;
4925 } else if (!Selected) {
4926 return false;
4927 }
4928 // In C++98, we are not supposed to perform overload resolution here, but we
4929 // treat that as a language defect.
4930 goto NeedOverloadResolution;
4931
4932 case Sema::CXXMoveConstructor:
4933 case Sema::CXXMoveAssignment:
4934 NeedOverloadResolution:
4935 Sema::SpecialMemberOverloadResult *SMOR =
4936 S.LookupSpecialMember(RD, CSM,
4937 Quals & Qualifiers::Const,
4938 Quals & Qualifiers::Volatile,
4939 /*RValueThis*/false, /*ConstThis*/false,
4940 /*VolatileThis*/false);
4941
4942 // The standard doesn't describe how to behave if the lookup is ambiguous.
4943 // We treat it as not making the member non-trivial, just like the standard
4944 // mandates for the default constructor. This should rarely matter, because
4945 // the member will also be deleted.
4946 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4947 return true;
4948
4949 if (!SMOR->getMethod()) {
4950 assert(SMOR->getKind() ==
4951 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
4952 return false;
4953 }
4954
4955 // We deliberately don't check if we found a deleted special member. We're
4956 // not supposed to!
4957 if (Selected)
4958 *Selected = SMOR->getMethod();
4959 return SMOR->getMethod()->isTrivial();
4960 }
4961
4962 llvm_unreachable("unknown special method kind");
4963}
4964
Benjamin Kramera574c892013-02-15 12:30:38 +00004965static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00004966 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
4967 CI != CE; ++CI)
4968 if (!CI->isImplicit())
4969 return *CI;
4970
4971 // Look for constructor templates.
4972 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
4973 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
4974 if (CXXConstructorDecl *CD =
4975 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
4976 return CD;
4977 }
4978
4979 return 0;
4980}
4981
4982/// The kind of subobject we are checking for triviality. The values of this
4983/// enumeration are used in diagnostics.
4984enum TrivialSubobjectKind {
4985 /// The subobject is a base class.
4986 TSK_BaseClass,
4987 /// The subobject is a non-static data member.
4988 TSK_Field,
4989 /// The object is actually the complete object.
4990 TSK_CompleteObject
4991};
4992
4993/// Check whether the special member selected for a given type would be trivial.
4994static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
4995 QualType SubType,
4996 Sema::CXXSpecialMember CSM,
4997 TrivialSubobjectKind Kind,
4998 bool Diagnose) {
4999 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5000 if (!SubRD)
5001 return true;
5002
5003 CXXMethodDecl *Selected;
5004 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5005 Diagnose ? &Selected : 0))
5006 return true;
5007
5008 if (Diagnose) {
5009 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5010 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5011 << Kind << SubType.getUnqualifiedType();
5012 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5013 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5014 } else if (!Selected)
5015 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5016 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5017 else if (Selected->isUserProvided()) {
5018 if (Kind == TSK_CompleteObject)
5019 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5020 << Kind << SubType.getUnqualifiedType() << CSM;
5021 else {
5022 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5023 << Kind << SubType.getUnqualifiedType() << CSM;
5024 S.Diag(Selected->getLocation(), diag::note_declared_at);
5025 }
5026 } else {
5027 if (Kind != TSK_CompleteObject)
5028 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5029 << Kind << SubType.getUnqualifiedType() << CSM;
5030
5031 // Explain why the defaulted or deleted special member isn't trivial.
5032 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5033 }
5034 }
5035
5036 return false;
5037}
5038
5039/// Check whether the members of a class type allow a special member to be
5040/// trivial.
5041static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5042 Sema::CXXSpecialMember CSM,
5043 bool ConstArg, bool Diagnose) {
5044 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5045 FE = RD->field_end(); FI != FE; ++FI) {
5046 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5047 continue;
5048
5049 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5050
5051 // Pretend anonymous struct or union members are members of this class.
5052 if (FI->isAnonymousStructOrUnion()) {
5053 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5054 CSM, ConstArg, Diagnose))
5055 return false;
5056 continue;
5057 }
5058
5059 // C++11 [class.ctor]p5:
5060 // A default constructor is trivial if [...]
5061 // -- no non-static data member of its class has a
5062 // brace-or-equal-initializer
5063 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5064 if (Diagnose)
5065 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5066 return false;
5067 }
5068
5069 // Objective C ARC 4.3.5:
5070 // [...] nontrivally ownership-qualified types are [...] not trivially
5071 // default constructible, copy constructible, move constructible, copy
5072 // assignable, move assignable, or destructible [...]
5073 if (S.getLangOpts().ObjCAutoRefCount &&
5074 FieldType.hasNonTrivialObjCLifetime()) {
5075 if (Diagnose)
5076 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5077 << RD << FieldType.getObjCLifetime();
5078 return false;
5079 }
5080
5081 if (ConstArg && !FI->isMutable())
5082 FieldType.addConst();
5083 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5084 TSK_Field, Diagnose))
5085 return false;
5086 }
5087
5088 return true;
5089}
5090
5091/// Diagnose why the specified class does not have a trivial special member of
5092/// the given kind.
5093void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5094 QualType Ty = Context.getRecordType(RD);
5095 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5096 Ty.addConst();
5097
5098 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5099 TSK_CompleteObject, /*Diagnose*/true);
5100}
5101
5102/// Determine whether a defaulted or deleted special member function is trivial,
5103/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5104/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5105bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5106 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005107 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5108
5109 CXXRecordDecl *RD = MD->getParent();
5110
5111 bool ConstArg = false;
5112 ParmVarDecl *Param0 = MD->getNumParams() ? MD->getParamDecl(0) : 0;
5113
5114 // C++11 [class.copy]p12, p25:
5115 // A [special member] is trivial if its declared parameter type is the same
5116 // as if it had been implicitly declared [...]
5117 switch (CSM) {
5118 case CXXDefaultConstructor:
5119 case CXXDestructor:
5120 // Trivial default constructors and destructors cannot have parameters.
5121 break;
5122
5123 case CXXCopyConstructor:
5124 case CXXCopyAssignment: {
5125 // Trivial copy operations always have const, non-volatile parameter types.
5126 ConstArg = true;
5127 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5128 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5129 if (Diagnose)
5130 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5131 << Param0->getSourceRange() << Param0->getType()
5132 << Context.getLValueReferenceType(
5133 Context.getRecordType(RD).withConst());
5134 return false;
5135 }
5136 break;
5137 }
5138
5139 case CXXMoveConstructor:
5140 case CXXMoveAssignment: {
5141 // Trivial move operations always have non-cv-qualified parameters.
5142 const RValueReferenceType *RT =
5143 Param0->getType()->getAs<RValueReferenceType>();
5144 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5145 if (Diagnose)
5146 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5147 << Param0->getSourceRange() << Param0->getType()
5148 << Context.getRValueReferenceType(Context.getRecordType(RD));
5149 return false;
5150 }
5151 break;
5152 }
5153
5154 case CXXInvalid:
5155 llvm_unreachable("not a special member");
5156 }
5157
5158 // FIXME: We require that the parameter-declaration-clause is equivalent to
5159 // that of an implicit declaration, not just that the declared parameter type
5160 // matches, in order to prevent absuridities like a function simultaneously
5161 // being a trivial copy constructor and a non-trivial default constructor.
5162 // This issue has not yet been assigned a core issue number.
5163 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5164 if (Diagnose)
5165 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5166 diag::note_nontrivial_default_arg)
5167 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5168 return false;
5169 }
5170 if (MD->isVariadic()) {
5171 if (Diagnose)
5172 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5173 return false;
5174 }
5175
5176 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5177 // A copy/move [constructor or assignment operator] is trivial if
5178 // -- the [member] selected to copy/move each direct base class subobject
5179 // is trivial
5180 //
5181 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5182 // A [default constructor or destructor] is trivial if
5183 // -- all the direct base classes have trivial [default constructors or
5184 // destructors]
5185 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5186 BE = RD->bases_end(); BI != BE; ++BI)
5187 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5188 ConstArg ? BI->getType().withConst()
5189 : BI->getType(),
5190 CSM, TSK_BaseClass, Diagnose))
5191 return false;
5192
5193 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5194 // A copy/move [constructor or assignment operator] for a class X is
5195 // trivial if
5196 // -- for each non-static data member of X that is of class type (or array
5197 // thereof), the constructor selected to copy/move that member is
5198 // trivial
5199 //
5200 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5201 // A [default constructor or destructor] is trivial if
5202 // -- for all of the non-static data members of its class that are of class
5203 // type (or array thereof), each such class has a trivial [default
5204 // constructor or destructor]
5205 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5206 return false;
5207
5208 // C++11 [class.dtor]p5:
5209 // A destructor is trivial if [...]
5210 // -- the destructor is not virtual
5211 if (CSM == CXXDestructor && MD->isVirtual()) {
5212 if (Diagnose)
5213 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5214 return false;
5215 }
5216
5217 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5218 // A [special member] for class X is trivial if [...]
5219 // -- class X has no virtual functions and no virtual base classes
5220 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5221 if (!Diagnose)
5222 return false;
5223
5224 if (RD->getNumVBases()) {
5225 // Check for virtual bases. We already know that the corresponding
5226 // member in all bases is trivial, so vbases must all be direct.
5227 CXXBaseSpecifier &BS = *RD->vbases_begin();
5228 assert(BS.isVirtual());
5229 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5230 return false;
5231 }
5232
5233 // Must have a virtual method.
5234 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5235 ME = RD->method_end(); MI != ME; ++MI) {
5236 if (MI->isVirtual()) {
5237 SourceLocation MLoc = MI->getLocStart();
5238 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5239 return false;
5240 }
5241 }
5242
5243 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5244 }
5245
5246 // Looks like it's trivial!
5247 return true;
5248}
5249
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005250/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005251namespace {
5252 struct FindHiddenVirtualMethodData {
5253 Sema *S;
5254 CXXMethodDecl *Method;
5255 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005256 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005257 };
5258}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005259
David Blaikie5f750682012-10-19 00:53:08 +00005260/// \brief Check whether any most overriden method from MD in Methods
5261static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5262 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5263 if (MD->size_overridden_methods() == 0)
5264 return Methods.count(MD->getCanonicalDecl());
5265 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5266 E = MD->end_overridden_methods();
5267 I != E; ++I)
5268 if (CheckMostOverridenMethods(*I, Methods))
5269 return true;
5270 return false;
5271}
5272
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005273/// \brief Member lookup function that determines whether a given C++
5274/// method overloads virtual methods in a base class without overriding any,
5275/// to be used with CXXRecordDecl::lookupInBases().
5276static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5277 CXXBasePath &Path,
5278 void *UserData) {
5279 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5280
5281 FindHiddenVirtualMethodData &Data
5282 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5283
5284 DeclarationName Name = Data.Method->getDeclName();
5285 assert(Name.getNameKind() == DeclarationName::Identifier);
5286
5287 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005288 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005289 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005290 !Path.Decls.empty();
5291 Path.Decls = Path.Decls.slice(1)) {
5292 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005293 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005294 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005295 foundSameNameMethod = true;
5296 // Interested only in hidden virtual methods.
5297 if (!MD->isVirtual())
5298 continue;
5299 // If the method we are checking overrides a method from its base
5300 // don't warn about the other overloaded methods.
5301 if (!Data.S->IsOverload(Data.Method, MD, false))
5302 return true;
5303 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005304 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005305 overloadedMethods.push_back(MD);
5306 }
5307 }
5308
5309 if (foundSameNameMethod)
5310 Data.OverloadedMethods.append(overloadedMethods.begin(),
5311 overloadedMethods.end());
5312 return foundSameNameMethod;
5313}
5314
David Blaikie5f750682012-10-19 00:53:08 +00005315/// \brief Add the most overriden methods from MD to Methods
5316static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5317 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5318 if (MD->size_overridden_methods() == 0)
5319 Methods.insert(MD->getCanonicalDecl());
5320 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5321 E = MD->end_overridden_methods();
5322 I != E; ++I)
5323 AddMostOverridenMethods(*I, Methods);
5324}
5325
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005326/// \brief See if a method overloads virtual methods in a base class without
5327/// overriding any.
5328void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5329 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005330 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005331 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005332 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005333 return;
5334
5335 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5336 /*bool RecordPaths=*/false,
5337 /*bool DetectVirtual=*/false);
5338 FindHiddenVirtualMethodData Data;
5339 Data.Method = MD;
5340 Data.S = this;
5341
5342 // Keep the base methods that were overriden or introduced in the subclass
5343 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005344 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5345 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5346 NamedDecl *ND = *I;
5347 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005348 ND = shad->getTargetDecl();
5349 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5350 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005351 }
5352
5353 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5354 !Data.OverloadedMethods.empty()) {
5355 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5356 << MD << (Data.OverloadedMethods.size() > 1);
5357
5358 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5359 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5360 Diag(overloadedMD->getLocation(),
5361 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5362 }
5363 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005364}
5365
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005366void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005367 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005368 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005369 SourceLocation RBrac,
5370 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005371 if (!TagDecl)
5372 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005373
Douglas Gregor42af25f2009-05-11 19:58:34 +00005374 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005375
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005376 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5377 if (l->getKind() != AttributeList::AT_Visibility)
5378 continue;
5379 l->setInvalid();
5380 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5381 l->getName();
5382 }
5383
David Blaikie77b6de02011-09-22 02:58:26 +00005384 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005385 // strict aliasing violation!
5386 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005387 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005388
Douglas Gregor23c94db2010-07-02 17:43:08 +00005389 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005390 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005391}
5392
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005393/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5394/// special functions, such as the default constructor, copy
5395/// constructor, or destructor, to the given C++ class (C++
5396/// [special]p1). This routine can only be executed just before the
5397/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005398void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005399 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005400 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005401
Richard Smithbc2a35d2012-12-08 08:32:28 +00005402 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005403 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005404
Richard Smithbc2a35d2012-12-08 08:32:28 +00005405 // If the properties or semantics of the copy constructor couldn't be
5406 // determined while the class was being declared, force a declaration
5407 // of it now.
5408 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5409 DeclareImplicitCopyConstructor(ClassDecl);
5410 }
5411
Richard Smith80ad52f2013-01-02 11:42:31 +00005412 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005413 ++ASTContext::NumImplicitMoveConstructors;
5414
Richard Smithbc2a35d2012-12-08 08:32:28 +00005415 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5416 DeclareImplicitMoveConstructor(ClassDecl);
5417 }
5418
Douglas Gregora376d102010-07-02 21:50:04 +00005419 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5420 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005421
5422 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005423 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005424 // it shows up in the right place in the vtable and that we diagnose
5425 // problems with the implicit exception specification.
5426 if (ClassDecl->isDynamicClass() ||
5427 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005428 DeclareImplicitCopyAssignment(ClassDecl);
5429 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005430
Richard Smith80ad52f2013-01-02 11:42:31 +00005431 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005432 ++ASTContext::NumImplicitMoveAssignmentOperators;
5433
5434 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005435 if (ClassDecl->isDynamicClass() ||
5436 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005437 DeclareImplicitMoveAssignment(ClassDecl);
5438 }
5439
Douglas Gregor4923aa22010-07-02 20:37:36 +00005440 if (!ClassDecl->hasUserDeclaredDestructor()) {
5441 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005442
5443 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005444 // have to declare the destructor immediately. This ensures that, e.g., it
5445 // shows up in the right place in the vtable and that we diagnose problems
5446 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005447 if (ClassDecl->isDynamicClass() ||
5448 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005449 DeclareImplicitDestructor(ClassDecl);
5450 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005451}
5452
Francois Pichet8387e2a2011-04-22 22:18:13 +00005453void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5454 if (!D)
5455 return;
5456
5457 int NumParamList = D->getNumTemplateParameterLists();
5458 for (int i = 0; i < NumParamList; i++) {
5459 TemplateParameterList* Params = D->getTemplateParameterList(i);
5460 for (TemplateParameterList::iterator Param = Params->begin(),
5461 ParamEnd = Params->end();
5462 Param != ParamEnd; ++Param) {
5463 NamedDecl *Named = cast<NamedDecl>(*Param);
5464 if (Named->getDeclName()) {
5465 S->AddDecl(Named);
5466 IdResolver.AddDecl(Named);
5467 }
5468 }
5469 }
5470}
5471
John McCalld226f652010-08-21 09:40:31 +00005472void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005473 if (!D)
5474 return;
5475
5476 TemplateParameterList *Params = 0;
5477 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5478 Params = Template->getTemplateParameters();
5479 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5480 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5481 Params = PartialSpec->getTemplateParameters();
5482 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005483 return;
5484
Douglas Gregor6569d682009-05-27 23:11:45 +00005485 for (TemplateParameterList::iterator Param = Params->begin(),
5486 ParamEnd = Params->end();
5487 Param != ParamEnd; ++Param) {
5488 NamedDecl *Named = cast<NamedDecl>(*Param);
5489 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005490 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005491 IdResolver.AddDecl(Named);
5492 }
5493 }
5494}
5495
John McCalld226f652010-08-21 09:40:31 +00005496void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005497 if (!RecordD) return;
5498 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005499 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005500 PushDeclContext(S, Record);
5501}
5502
John McCalld226f652010-08-21 09:40:31 +00005503void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005504 if (!RecordD) return;
5505 PopDeclContext();
5506}
5507
Douglas Gregor72b505b2008-12-16 21:30:33 +00005508/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5509/// parsing a top-level (non-nested) C++ class, and we are now
5510/// parsing those parts of the given Method declaration that could
5511/// not be parsed earlier (C++ [class.mem]p2), such as default
5512/// arguments. This action should enter the scope of the given
5513/// Method declaration as if we had just parsed the qualified method
5514/// name. However, it should not bring the parameters into scope;
5515/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005516void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005517}
5518
5519/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5520/// C++ method declaration. We're (re-)introducing the given
5521/// function parameter into scope for use in parsing later parts of
5522/// the method declaration. For example, we could see an
5523/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005524void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005525 if (!ParamD)
5526 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005527
John McCalld226f652010-08-21 09:40:31 +00005528 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005529
5530 // If this parameter has an unparsed default argument, clear it out
5531 // to make way for the parsed default argument.
5532 if (Param->hasUnparsedDefaultArg())
5533 Param->setDefaultArg(0);
5534
John McCalld226f652010-08-21 09:40:31 +00005535 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005536 if (Param->getDeclName())
5537 IdResolver.AddDecl(Param);
5538}
5539
5540/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5541/// processing the delayed method declaration for Method. The method
5542/// declaration is now considered finished. There may be a separate
5543/// ActOnStartOfFunctionDef action later (not necessarily
5544/// immediately!) for this method, if it was also defined inside the
5545/// class body.
John McCalld226f652010-08-21 09:40:31 +00005546void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005547 if (!MethodD)
5548 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005549
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005550 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005551
John McCalld226f652010-08-21 09:40:31 +00005552 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005553
5554 // Now that we have our default arguments, check the constructor
5555 // again. It could produce additional diagnostics or affect whether
5556 // the class has implicitly-declared destructors, among other
5557 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005558 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5559 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005560
5561 // Check the default arguments, which we may have added.
5562 if (!Method->isInvalidDecl())
5563 CheckCXXDefaultArguments(Method);
5564}
5565
Douglas Gregor42a552f2008-11-05 20:51:48 +00005566/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005567/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005568/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005569/// emit diagnostics and set the invalid bit to true. In any case, the type
5570/// will be updated to reflect a well-formed type for the constructor and
5571/// returned.
5572QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005573 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005574 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005575
5576 // C++ [class.ctor]p3:
5577 // A constructor shall not be virtual (10.3) or static (9.4). A
5578 // constructor can be invoked for a const, volatile or const
5579 // volatile object. A constructor shall not be declared const,
5580 // volatile, or const volatile (9.3.2).
5581 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005582 if (!D.isInvalidType())
5583 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5584 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5585 << SourceRange(D.getIdentifierLoc());
5586 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005587 }
John McCalld931b082010-08-26 03:08:43 +00005588 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005589 if (!D.isInvalidType())
5590 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5591 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5592 << SourceRange(D.getIdentifierLoc());
5593 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005594 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005595 }
Mike Stump1eb44332009-09-09 15:08:12 +00005596
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005597 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005598 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005599 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005600 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5601 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005602 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005603 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5604 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005605 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005606 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5607 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005608 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005609 }
Mike Stump1eb44332009-09-09 15:08:12 +00005610
Douglas Gregorc938c162011-01-26 05:01:58 +00005611 // C++0x [class.ctor]p4:
5612 // A constructor shall not be declared with a ref-qualifier.
5613 if (FTI.hasRefQualifier()) {
5614 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5615 << FTI.RefQualifierIsLValueRef
5616 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5617 D.setInvalidType();
5618 }
5619
Douglas Gregor42a552f2008-11-05 20:51:48 +00005620 // Rebuild the function type "R" without any type qualifiers (in
5621 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005622 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005623 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005624 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5625 return R;
5626
5627 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5628 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005629 EPI.RefQualifier = RQ_None;
5630
Chris Lattner65401802009-04-25 08:28:21 +00005631 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005632 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005633}
5634
Douglas Gregor72b505b2008-12-16 21:30:33 +00005635/// CheckConstructor - Checks a fully-formed constructor for
5636/// well-formedness, issuing any diagnostics required. Returns true if
5637/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005638void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005639 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005640 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5641 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005642 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005643
5644 // C++ [class.copy]p3:
5645 // A declaration of a constructor for a class X is ill-formed if
5646 // its first parameter is of type (optionally cv-qualified) X and
5647 // either there are no other parameters or else all other
5648 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005649 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005650 ((Constructor->getNumParams() == 1) ||
5651 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005652 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5653 Constructor->getTemplateSpecializationKind()
5654 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005655 QualType ParamType = Constructor->getParamDecl(0)->getType();
5656 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5657 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005658 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005659 const char *ConstRef
5660 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5661 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005662 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005663 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005664
5665 // FIXME: Rather that making the constructor invalid, we should endeavor
5666 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005667 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005668 }
5669 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005670}
5671
John McCall15442822010-08-04 01:04:25 +00005672/// CheckDestructor - Checks a fully-formed destructor definition for
5673/// well-formedness, issuing any diagnostics required. Returns true
5674/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005675bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005676 CXXRecordDecl *RD = Destructor->getParent();
5677
5678 if (Destructor->isVirtual()) {
5679 SourceLocation Loc;
5680
5681 if (!Destructor->isImplicit())
5682 Loc = Destructor->getLocation();
5683 else
5684 Loc = RD->getLocation();
5685
5686 // If we have a virtual destructor, look up the deallocation function
5687 FunctionDecl *OperatorDelete = 0;
5688 DeclarationName Name =
5689 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005690 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005691 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005692
Eli Friedman5f2987c2012-02-02 03:46:19 +00005693 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005694
5695 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005696 }
Anders Carlsson37909802009-11-30 21:24:50 +00005697
5698 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005699}
5700
Mike Stump1eb44332009-09-09 15:08:12 +00005701static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005702FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5703 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5704 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005705 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005706}
5707
Douglas Gregor42a552f2008-11-05 20:51:48 +00005708/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5709/// the well-formednes of the destructor declarator @p D with type @p
5710/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005711/// emit diagnostics and set the declarator to invalid. Even if this happens,
5712/// will be updated to reflect a well-formed type for the destructor and
5713/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005714QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005715 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005716 // C++ [class.dtor]p1:
5717 // [...] A typedef-name that names a class is a class-name
5718 // (7.1.3); however, a typedef-name that names a class shall not
5719 // be used as the identifier in the declarator for a destructor
5720 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005721 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005722 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005723 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005724 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005725 else if (const TemplateSpecializationType *TST =
5726 DeclaratorType->getAs<TemplateSpecializationType>())
5727 if (TST->isTypeAlias())
5728 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5729 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005730
5731 // C++ [class.dtor]p2:
5732 // A destructor is used to destroy objects of its class type. A
5733 // destructor takes no parameters, and no return type can be
5734 // specified for it (not even void). The address of a destructor
5735 // shall not be taken. A destructor shall not be static. A
5736 // destructor can be invoked for a const, volatile or const
5737 // volatile object. A destructor shall not be declared const,
5738 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005739 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005740 if (!D.isInvalidType())
5741 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5742 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005743 << SourceRange(D.getIdentifierLoc())
5744 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5745
John McCalld931b082010-08-26 03:08:43 +00005746 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005747 }
Chris Lattner65401802009-04-25 08:28:21 +00005748 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005749 // Destructors don't have return types, but the parser will
5750 // happily parse something like:
5751 //
5752 // class X {
5753 // float ~X();
5754 // };
5755 //
5756 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005757 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5758 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5759 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005760 }
Mike Stump1eb44332009-09-09 15:08:12 +00005761
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005762 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005763 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005764 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005765 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5766 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005767 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005768 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5769 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005770 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005771 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5772 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005773 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005774 }
5775
Douglas Gregorc938c162011-01-26 05:01:58 +00005776 // C++0x [class.dtor]p2:
5777 // A destructor shall not be declared with a ref-qualifier.
5778 if (FTI.hasRefQualifier()) {
5779 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5780 << FTI.RefQualifierIsLValueRef
5781 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5782 D.setInvalidType();
5783 }
5784
Douglas Gregor42a552f2008-11-05 20:51:48 +00005785 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005786 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005787 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5788
5789 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005790 FTI.freeArgs();
5791 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005792 }
5793
Mike Stump1eb44332009-09-09 15:08:12 +00005794 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005795 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005796 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005797 D.setInvalidType();
5798 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005799
5800 // Rebuild the function type "R" without any type qualifiers or
5801 // parameters (in case any of the errors above fired) and with
5802 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005803 // types.
John McCalle23cf432010-12-14 08:05:40 +00005804 if (!D.isInvalidType())
5805 return R;
5806
Douglas Gregord92ec472010-07-01 05:10:53 +00005807 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005808 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5809 EPI.Variadic = false;
5810 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005811 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005812 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005813}
5814
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005815/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5816/// well-formednes of the conversion function declarator @p D with
5817/// type @p R. If there are any errors in the declarator, this routine
5818/// will emit diagnostics and return true. Otherwise, it will return
5819/// false. Either way, the type @p R will be updated to reflect a
5820/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005821void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005822 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005823 // C++ [class.conv.fct]p1:
5824 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005825 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005826 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005827 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005828 if (!D.isInvalidType())
5829 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5830 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5831 << SourceRange(D.getIdentifierLoc());
5832 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005833 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005834 }
John McCalla3f81372010-04-13 00:04:31 +00005835
5836 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5837
Chris Lattner6e475012009-04-25 08:35:12 +00005838 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005839 // Conversion functions don't have return types, but the parser will
5840 // happily parse something like:
5841 //
5842 // class X {
5843 // float operator bool();
5844 // };
5845 //
5846 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005847 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5848 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5849 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005850 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005851 }
5852
John McCalla3f81372010-04-13 00:04:31 +00005853 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5854
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005855 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005856 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005857 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5858
5859 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005860 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005861 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005862 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005863 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005864 D.setInvalidType();
5865 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005866
John McCalla3f81372010-04-13 00:04:31 +00005867 // Diagnose "&operator bool()" and other such nonsense. This
5868 // is actually a gcc extension which we don't support.
5869 if (Proto->getResultType() != ConvType) {
5870 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5871 << Proto->getResultType();
5872 D.setInvalidType();
5873 ConvType = Proto->getResultType();
5874 }
5875
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005876 // C++ [class.conv.fct]p4:
5877 // The conversion-type-id shall not represent a function type nor
5878 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005879 if (ConvType->isArrayType()) {
5880 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5881 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005882 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005883 } else if (ConvType->isFunctionType()) {
5884 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5885 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005886 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005887 }
5888
5889 // Rebuild the function type "R" without any parameters (in case any
5890 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005891 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005892 if (D.isInvalidType())
5893 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005894
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005895 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005896 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005897 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005898 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005899 diag::warn_cxx98_compat_explicit_conversion_functions :
5900 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005901 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005902}
5903
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005904/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5905/// the declaration of the given C++ conversion function. This routine
5906/// is responsible for recording the conversion function in the C++
5907/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005908Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005909 assert(Conversion && "Expected to receive a conversion function declaration");
5910
Douglas Gregor9d350972008-12-12 08:25:50 +00005911 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005912
5913 // Make sure we aren't redeclaring the conversion function.
5914 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005915
5916 // C++ [class.conv.fct]p1:
5917 // [...] A conversion function is never used to convert a
5918 // (possibly cv-qualified) object to the (possibly cv-qualified)
5919 // same object type (or a reference to it), to a (possibly
5920 // cv-qualified) base class of that type (or a reference to it),
5921 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005922 // FIXME: Suppress this warning if the conversion function ends up being a
5923 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005924 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005925 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005926 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005927 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005928 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5929 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005930 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005931 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005932 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5933 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005934 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005935 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005936 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005937 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005938 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005939 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005940 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005941 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005942 }
5943
Douglas Gregore80622f2010-09-29 04:25:11 +00005944 if (FunctionTemplateDecl *ConversionTemplate
5945 = Conversion->getDescribedFunctionTemplate())
5946 return ConversionTemplate;
5947
John McCalld226f652010-08-21 09:40:31 +00005948 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005949}
5950
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005951//===----------------------------------------------------------------------===//
5952// Namespace Handling
5953//===----------------------------------------------------------------------===//
5954
Richard Smithd1a55a62012-10-04 22:13:39 +00005955/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
5956/// reopened.
5957static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
5958 SourceLocation Loc,
5959 IdentifierInfo *II, bool *IsInline,
5960 NamespaceDecl *PrevNS) {
5961 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00005962
Richard Smithc969e6a2012-10-05 01:46:25 +00005963 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
5964 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
5965 // inline namespaces, with the intention of bringing names into namespace std.
5966 //
5967 // We support this just well enough to get that case working; this is not
5968 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00005969 if (*IsInline && II && II->getName().startswith("__atomic") &&
5970 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00005971 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00005972 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
5973 NS = NS->getPreviousDecl())
5974 NS->setInline(*IsInline);
5975 // Patch up the lookup table for the containing namespace. This isn't really
5976 // correct, but it's good enough for this particular case.
5977 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
5978 E = PrevNS->decls_end(); I != E; ++I)
5979 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
5980 PrevNS->getParent()->makeDeclVisibleInContext(ND);
5981 return;
5982 }
5983
5984 if (PrevNS->isInline())
5985 // The user probably just forgot the 'inline', so suggest that it
5986 // be added back.
5987 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5988 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
5989 else
5990 S.Diag(Loc, diag::err_inline_namespace_mismatch)
5991 << IsInline;
5992
5993 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
5994 *IsInline = PrevNS->isInline();
5995}
John McCallea318642010-08-26 09:15:37 +00005996
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005997/// ActOnStartNamespaceDef - This is called at the start of a namespace
5998/// definition.
John McCalld226f652010-08-21 09:40:31 +00005999Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006000 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006001 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006002 SourceLocation IdentLoc,
6003 IdentifierInfo *II,
6004 SourceLocation LBrace,
6005 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006006 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6007 // For anonymous namespace, take the location of the left brace.
6008 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006009 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006010 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006011 bool IsStd = false;
6012 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006013 Scope *DeclRegionScope = NamespcScope->getParent();
6014
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006015 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006016 if (II) {
6017 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006018 // The identifier in an original-namespace-definition shall not
6019 // have been previously defined in the declarative region in
6020 // which the original-namespace-definition appears. The
6021 // identifier in an original-namespace-definition is the name of
6022 // the namespace. Subsequently in that declarative region, it is
6023 // treated as an original-namespace-name.
6024 //
6025 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006026 // look through using directives, just look for any ordinary names.
6027
6028 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006029 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6030 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006031 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006032 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6033 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6034 ++I) {
6035 if ((*I)->getIdentifierNamespace() & IDNS) {
6036 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006037 break;
6038 }
6039 }
6040
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006041 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6042
6043 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006044 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006045 if (IsInline != PrevNS->isInline())
6046 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6047 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006048 } else if (PrevDecl) {
6049 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006050 Diag(Loc, diag::err_redefinition_different_kind)
6051 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006052 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006053 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006054 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006055 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006056 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006057 // This is the first "real" definition of the namespace "std", so update
6058 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006059 PrevNS = getStdNamespace();
6060 IsStd = true;
6061 AddToKnown = !IsInline;
6062 } else {
6063 // We've seen this namespace for the first time.
6064 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006065 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006066 } else {
John McCall9aeed322009-10-01 00:25:31 +00006067 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006068
6069 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006070 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006071 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006072 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006073 } else {
6074 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006075 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006076 }
6077
Richard Smithd1a55a62012-10-04 22:13:39 +00006078 if (PrevNS && IsInline != PrevNS->isInline())
6079 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6080 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006081 }
6082
6083 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6084 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006085 if (IsInvalid)
6086 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006087
6088 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006089
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006090 // FIXME: Should we be merging attributes?
6091 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006092 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006093
6094 if (IsStd)
6095 StdNamespace = Namespc;
6096 if (AddToKnown)
6097 KnownNamespaces[Namespc] = false;
6098
6099 if (II) {
6100 PushOnScopeChains(Namespc, DeclRegionScope);
6101 } else {
6102 // Link the anonymous namespace into its parent.
6103 DeclContext *Parent = CurContext->getRedeclContext();
6104 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6105 TU->setAnonymousNamespace(Namespc);
6106 } else {
6107 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006108 }
John McCall9aeed322009-10-01 00:25:31 +00006109
Douglas Gregora4181472010-03-24 00:46:35 +00006110 CurContext->addDecl(Namespc);
6111
John McCall9aeed322009-10-01 00:25:31 +00006112 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6113 // behaves as if it were replaced by
6114 // namespace unique { /* empty body */ }
6115 // using namespace unique;
6116 // namespace unique { namespace-body }
6117 // where all occurrences of 'unique' in a translation unit are
6118 // replaced by the same identifier and this identifier differs
6119 // from all other identifiers in the entire program.
6120
6121 // We just create the namespace with an empty name and then add an
6122 // implicit using declaration, just like the standard suggests.
6123 //
6124 // CodeGen enforces the "universally unique" aspect by giving all
6125 // declarations semantically contained within an anonymous
6126 // namespace internal linkage.
6127
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006128 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006129 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006130 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006131 /* 'using' */ LBrace,
6132 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006133 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006134 /* identifier */ SourceLocation(),
6135 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006136 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006137 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006138 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006139 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006140 }
6141
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006142 ActOnDocumentableDecl(Namespc);
6143
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006144 // Although we could have an invalid decl (i.e. the namespace name is a
6145 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006146 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6147 // for the namespace has the declarations that showed up in that particular
6148 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006149 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006150 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006151}
6152
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006153/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6154/// is a namespace alias, returns the namespace it points to.
6155static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6156 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6157 return AD->getNamespace();
6158 return dyn_cast_or_null<NamespaceDecl>(D);
6159}
6160
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006161/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6162/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006163void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006164 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6165 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006166 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006167 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006168 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006169 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006170}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006171
John McCall384aff82010-08-25 07:42:41 +00006172CXXRecordDecl *Sema::getStdBadAlloc() const {
6173 return cast_or_null<CXXRecordDecl>(
6174 StdBadAlloc.get(Context.getExternalSource()));
6175}
6176
6177NamespaceDecl *Sema::getStdNamespace() const {
6178 return cast_or_null<NamespaceDecl>(
6179 StdNamespace.get(Context.getExternalSource()));
6180}
6181
Douglas Gregor66992202010-06-29 17:53:46 +00006182/// \brief Retrieve the special "std" namespace, which may require us to
6183/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006184NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006185 if (!StdNamespace) {
6186 // The "std" namespace has not yet been defined, so build one implicitly.
6187 StdNamespace = NamespaceDecl::Create(Context,
6188 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006189 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006190 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006191 &PP.getIdentifierTable().get("std"),
6192 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006193 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006194 }
6195
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006196 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006197}
6198
Sebastian Redl395e04d2012-01-17 22:49:33 +00006199bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006200 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006201 "Looking for std::initializer_list outside of C++.");
6202
6203 // We're looking for implicit instantiations of
6204 // template <typename E> class std::initializer_list.
6205
6206 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6207 return false;
6208
Sebastian Redl84760e32012-01-17 22:49:58 +00006209 ClassTemplateDecl *Template = 0;
6210 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006211
Sebastian Redl84760e32012-01-17 22:49:58 +00006212 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006213
Sebastian Redl84760e32012-01-17 22:49:58 +00006214 ClassTemplateSpecializationDecl *Specialization =
6215 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6216 if (!Specialization)
6217 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006218
Sebastian Redl84760e32012-01-17 22:49:58 +00006219 Template = Specialization->getSpecializedTemplate();
6220 Arguments = Specialization->getTemplateArgs().data();
6221 } else if (const TemplateSpecializationType *TST =
6222 Ty->getAs<TemplateSpecializationType>()) {
6223 Template = dyn_cast_or_null<ClassTemplateDecl>(
6224 TST->getTemplateName().getAsTemplateDecl());
6225 Arguments = TST->getArgs();
6226 }
6227 if (!Template)
6228 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006229
6230 if (!StdInitializerList) {
6231 // Haven't recognized std::initializer_list yet, maybe this is it.
6232 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6233 if (TemplateClass->getIdentifier() !=
6234 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006235 !getStdNamespace()->InEnclosingNamespaceSetOf(
6236 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006237 return false;
6238 // This is a template called std::initializer_list, but is it the right
6239 // template?
6240 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006241 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006242 return false;
6243 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6244 return false;
6245
6246 // It's the right template.
6247 StdInitializerList = Template;
6248 }
6249
6250 if (Template != StdInitializerList)
6251 return false;
6252
6253 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006254 if (Element)
6255 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006256 return true;
6257}
6258
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006259static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6260 NamespaceDecl *Std = S.getStdNamespace();
6261 if (!Std) {
6262 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6263 return 0;
6264 }
6265
6266 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6267 Loc, Sema::LookupOrdinaryName);
6268 if (!S.LookupQualifiedName(Result, Std)) {
6269 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6270 return 0;
6271 }
6272 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6273 if (!Template) {
6274 Result.suppressDiagnostics();
6275 // We found something weird. Complain about the first thing we found.
6276 NamedDecl *Found = *Result.begin();
6277 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6278 return 0;
6279 }
6280
6281 // We found some template called std::initializer_list. Now verify that it's
6282 // correct.
6283 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006284 if (Params->getMinRequiredArguments() != 1 ||
6285 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006286 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6287 return 0;
6288 }
6289
6290 return Template;
6291}
6292
6293QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6294 if (!StdInitializerList) {
6295 StdInitializerList = LookupStdInitializerList(*this, Loc);
6296 if (!StdInitializerList)
6297 return QualType();
6298 }
6299
6300 TemplateArgumentListInfo Args(Loc, Loc);
6301 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6302 Context.getTrivialTypeSourceInfo(Element,
6303 Loc)));
6304 return Context.getCanonicalType(
6305 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6306}
6307
Sebastian Redl98d36062012-01-17 22:50:14 +00006308bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6309 // C++ [dcl.init.list]p2:
6310 // A constructor is an initializer-list constructor if its first parameter
6311 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6312 // std::initializer_list<E> for some type E, and either there are no other
6313 // parameters or else all other parameters have default arguments.
6314 if (Ctor->getNumParams() < 1 ||
6315 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6316 return false;
6317
6318 QualType ArgType = Ctor->getParamDecl(0)->getType();
6319 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6320 ArgType = RT->getPointeeType().getUnqualifiedType();
6321
6322 return isStdInitializerList(ArgType, 0);
6323}
6324
Douglas Gregor9172aa62011-03-26 22:25:30 +00006325/// \brief Determine whether a using statement is in a context where it will be
6326/// apply in all contexts.
6327static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6328 switch (CurContext->getDeclKind()) {
6329 case Decl::TranslationUnit:
6330 return true;
6331 case Decl::LinkageSpec:
6332 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6333 default:
6334 return false;
6335 }
6336}
6337
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006338namespace {
6339
6340// Callback to only accept typo corrections that are namespaces.
6341class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6342 public:
6343 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6344 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6345 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6346 }
6347 return false;
6348 }
6349};
6350
6351}
6352
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006353static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6354 CXXScopeSpec &SS,
6355 SourceLocation IdentLoc,
6356 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006357 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006358 R.clear();
6359 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006360 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006361 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006362 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6363 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006364 if (DeclContext *DC = S.computeDeclContext(SS, false))
6365 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6366 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006367 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6368 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006369 else
6370 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6371 << Ident << CorrectedQuotedStr
6372 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006373
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006374 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6375 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006376
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006377 R.addDecl(Corrected.getCorrectionDecl());
6378 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006379 }
6380 return false;
6381}
6382
John McCalld226f652010-08-21 09:40:31 +00006383Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006384 SourceLocation UsingLoc,
6385 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006386 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006387 SourceLocation IdentLoc,
6388 IdentifierInfo *NamespcName,
6389 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006390 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6391 assert(NamespcName && "Invalid NamespcName.");
6392 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006393
6394 // This can only happen along a recovery path.
6395 while (S->getFlags() & Scope::TemplateParamScope)
6396 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006397 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006398
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006399 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006400 NestedNameSpecifier *Qualifier = 0;
6401 if (SS.isSet())
6402 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6403
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006404 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006405 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6406 LookupParsedName(R, S, &SS);
6407 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006408 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006409
Douglas Gregor66992202010-06-29 17:53:46 +00006410 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006411 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006412 // Allow "using namespace std;" or "using namespace ::std;" even if
6413 // "std" hasn't been defined yet, for GCC compatibility.
6414 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6415 NamespcName->isStr("std")) {
6416 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006417 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006418 R.resolveKind();
6419 }
6420 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006421 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006422 }
6423
John McCallf36e02d2009-10-09 21:13:30 +00006424 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006425 NamedDecl *Named = R.getFoundDecl();
6426 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6427 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006428 // C++ [namespace.udir]p1:
6429 // A using-directive specifies that the names in the nominated
6430 // namespace can be used in the scope in which the
6431 // using-directive appears after the using-directive. During
6432 // unqualified name lookup (3.4.1), the names appear as if they
6433 // were declared in the nearest enclosing namespace which
6434 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006435 // namespace. [Note: in this context, "contains" means "contains
6436 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006437
6438 // Find enclosing context containing both using-directive and
6439 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006440 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006441 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6442 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6443 CommonAncestor = CommonAncestor->getParent();
6444
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006445 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006446 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006447 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006448
Douglas Gregor9172aa62011-03-26 22:25:30 +00006449 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006450 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006451 Diag(IdentLoc, diag::warn_using_directive_in_header);
6452 }
6453
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006454 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006455 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006456 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006457 }
6458
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006459 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006460 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006461}
6462
6463void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006464 // If the scope has an associated entity and the using directive is at
6465 // namespace or translation unit scope, add the UsingDirectiveDecl into
6466 // its lookup structure so qualified name lookup can find it.
6467 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6468 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006469 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006470 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006471 // Otherwise, it is at block sope. The using-directives will affect lookup
6472 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006473 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006474}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006475
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006476
John McCalld226f652010-08-21 09:40:31 +00006477Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006478 AccessSpecifier AS,
6479 bool HasUsingKeyword,
6480 SourceLocation UsingLoc,
6481 CXXScopeSpec &SS,
6482 UnqualifiedId &Name,
6483 AttributeList *AttrList,
6484 bool IsTypeName,
6485 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006486 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006487
Douglas Gregor12c118a2009-11-04 16:30:06 +00006488 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006489 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006490 case UnqualifiedId::IK_Identifier:
6491 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006492 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006493 case UnqualifiedId::IK_ConversionFunctionId:
6494 break;
6495
6496 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006497 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006498 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006499 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006500 getLangOpts().CPlusPlus11 ?
Richard Smitha1366cb2012-04-27 19:33:05 +00006501 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
6502 // instead once inheriting constructors work.
6503 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00006504 diag::err_using_decl_constructor)
6505 << SS.getRange();
6506
Richard Smith80ad52f2013-01-02 11:42:31 +00006507 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006508
John McCalld226f652010-08-21 09:40:31 +00006509 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006510
6511 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006512 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006513 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006514 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006515
6516 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006517 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006518 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006519 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006520 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006521
6522 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6523 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006524 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006525 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006526
John McCall60fa3cf2009-12-11 02:10:03 +00006527 // Warn about using declarations.
6528 // TODO: store that the declaration was written without 'using' and
6529 // talk about access decls instead of using decls in the
6530 // diagnostics.
6531 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006532 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006533
6534 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006535 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006536 }
6537
Douglas Gregor56c04582010-12-16 00:46:58 +00006538 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6539 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6540 return 0;
6541
John McCall9488ea12009-11-17 05:59:44 +00006542 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006543 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006544 /* IsInstantiation */ false,
6545 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006546 if (UD)
6547 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006548
John McCalld226f652010-08-21 09:40:31 +00006549 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006550}
6551
Douglas Gregor09acc982010-07-07 23:08:52 +00006552/// \brief Determine whether a using declaration considers the given
6553/// declarations as "equivalent", e.g., if they are redeclarations of
6554/// the same entity or are both typedefs of the same type.
6555static bool
6556IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6557 bool &SuppressRedeclaration) {
6558 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6559 SuppressRedeclaration = false;
6560 return true;
6561 }
6562
Richard Smith162e1c12011-04-15 14:24:37 +00006563 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6564 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006565 SuppressRedeclaration = true;
6566 return Context.hasSameType(TD1->getUnderlyingType(),
6567 TD2->getUnderlyingType());
6568 }
6569
6570 return false;
6571}
6572
6573
John McCall9f54ad42009-12-10 09:41:52 +00006574/// Determines whether to create a using shadow decl for a particular
6575/// decl, given the set of decls existing prior to this using lookup.
6576bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6577 const LookupResult &Previous) {
6578 // Diagnose finding a decl which is not from a base class of the
6579 // current class. We do this now because there are cases where this
6580 // function will silently decide not to build a shadow decl, which
6581 // will pre-empt further diagnostics.
6582 //
6583 // We don't need to do this in C++0x because we do the check once on
6584 // the qualifier.
6585 //
6586 // FIXME: diagnose the following if we care enough:
6587 // struct A { int foo; };
6588 // struct B : A { using A::foo; };
6589 // template <class T> struct C : A {};
6590 // template <class T> struct D : C<T> { using B::foo; } // <---
6591 // This is invalid (during instantiation) in C++03 because B::foo
6592 // resolves to the using decl in B, which is not a base class of D<T>.
6593 // We can't diagnose it immediately because C<T> is an unknown
6594 // specialization. The UsingShadowDecl in D<T> then points directly
6595 // to A::foo, which will look well-formed when we instantiate.
6596 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006597 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006598 DeclContext *OrigDC = Orig->getDeclContext();
6599
6600 // Handle enums and anonymous structs.
6601 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6602 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6603 while (OrigRec->isAnonymousStructOrUnion())
6604 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6605
6606 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6607 if (OrigDC == CurContext) {
6608 Diag(Using->getLocation(),
6609 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006610 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006611 Diag(Orig->getLocation(), diag::note_using_decl_target);
6612 return true;
6613 }
6614
Douglas Gregordc355712011-02-25 00:36:19 +00006615 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006616 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006617 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006618 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006619 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006620 Diag(Orig->getLocation(), diag::note_using_decl_target);
6621 return true;
6622 }
6623 }
6624
6625 if (Previous.empty()) return false;
6626
6627 NamedDecl *Target = Orig;
6628 if (isa<UsingShadowDecl>(Target))
6629 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6630
John McCalld7533ec2009-12-11 02:33:26 +00006631 // If the target happens to be one of the previous declarations, we
6632 // don't have a conflict.
6633 //
6634 // FIXME: but we might be increasing its access, in which case we
6635 // should redeclare it.
6636 NamedDecl *NonTag = 0, *Tag = 0;
6637 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6638 I != E; ++I) {
6639 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006640 bool Result;
6641 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6642 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006643
6644 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6645 }
6646
John McCall9f54ad42009-12-10 09:41:52 +00006647 if (Target->isFunctionOrFunctionTemplate()) {
6648 FunctionDecl *FD;
6649 if (isa<FunctionTemplateDecl>(Target))
6650 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6651 else
6652 FD = cast<FunctionDecl>(Target);
6653
6654 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006655 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006656 case Ovl_Overload:
6657 return false;
6658
6659 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006660 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006661 break;
6662
6663 // We found a decl with the exact signature.
6664 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006665 // If we're in a record, we want to hide the target, so we
6666 // return true (without a diagnostic) to tell the caller not to
6667 // build a shadow decl.
6668 if (CurContext->isRecord())
6669 return true;
6670
6671 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006672 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006673 break;
6674 }
6675
6676 Diag(Target->getLocation(), diag::note_using_decl_target);
6677 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6678 return true;
6679 }
6680
6681 // Target is not a function.
6682
John McCall9f54ad42009-12-10 09:41:52 +00006683 if (isa<TagDecl>(Target)) {
6684 // No conflict between a tag and a non-tag.
6685 if (!Tag) return false;
6686
John McCall41ce66f2009-12-10 19:51:03 +00006687 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006688 Diag(Target->getLocation(), diag::note_using_decl_target);
6689 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6690 return true;
6691 }
6692
6693 // No conflict between a tag and a non-tag.
6694 if (!NonTag) return false;
6695
John McCall41ce66f2009-12-10 19:51:03 +00006696 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006697 Diag(Target->getLocation(), diag::note_using_decl_target);
6698 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6699 return true;
6700}
6701
John McCall9488ea12009-11-17 05:59:44 +00006702/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006703UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006704 UsingDecl *UD,
6705 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006706
6707 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006708 NamedDecl *Target = Orig;
6709 if (isa<UsingShadowDecl>(Target)) {
6710 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6711 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006712 }
6713
6714 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006715 = UsingShadowDecl::Create(Context, CurContext,
6716 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006717 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006718
6719 Shadow->setAccess(UD->getAccess());
6720 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6721 Shadow->setInvalidDecl();
6722
John McCall9488ea12009-11-17 05:59:44 +00006723 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006724 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006725 else
John McCall604e7f12009-12-08 07:46:18 +00006726 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006727
John McCall604e7f12009-12-08 07:46:18 +00006728
John McCall9f54ad42009-12-10 09:41:52 +00006729 return Shadow;
6730}
John McCall604e7f12009-12-08 07:46:18 +00006731
John McCall9f54ad42009-12-10 09:41:52 +00006732/// Hides a using shadow declaration. This is required by the current
6733/// using-decl implementation when a resolvable using declaration in a
6734/// class is followed by a declaration which would hide or override
6735/// one or more of the using decl's targets; for example:
6736///
6737/// struct Base { void foo(int); };
6738/// struct Derived : Base {
6739/// using Base::foo;
6740/// void foo(int);
6741/// };
6742///
6743/// The governing language is C++03 [namespace.udecl]p12:
6744///
6745/// When a using-declaration brings names from a base class into a
6746/// derived class scope, member functions in the derived class
6747/// override and/or hide member functions with the same name and
6748/// parameter types in a base class (rather than conflicting).
6749///
6750/// There are two ways to implement this:
6751/// (1) optimistically create shadow decls when they're not hidden
6752/// by existing declarations, or
6753/// (2) don't create any shadow decls (or at least don't make them
6754/// visible) until we've fully parsed/instantiated the class.
6755/// The problem with (1) is that we might have to retroactively remove
6756/// a shadow decl, which requires several O(n) operations because the
6757/// decl structures are (very reasonably) not designed for removal.
6758/// (2) avoids this but is very fiddly and phase-dependent.
6759void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006760 if (Shadow->getDeclName().getNameKind() ==
6761 DeclarationName::CXXConversionFunctionName)
6762 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6763
John McCall9f54ad42009-12-10 09:41:52 +00006764 // Remove it from the DeclContext...
6765 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006766
John McCall9f54ad42009-12-10 09:41:52 +00006767 // ...and the scope, if applicable...
6768 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006769 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006770 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006771 }
6772
John McCall9f54ad42009-12-10 09:41:52 +00006773 // ...and the using decl.
6774 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6775
6776 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006777 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006778}
6779
John McCall7ba107a2009-11-18 02:36:19 +00006780/// Builds a using declaration.
6781///
6782/// \param IsInstantiation - Whether this call arises from an
6783/// instantiation of an unresolved using declaration. We treat
6784/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006785NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6786 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006787 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006788 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006789 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006790 bool IsInstantiation,
6791 bool IsTypeName,
6792 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006793 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006794 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006795 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006796
Anders Carlsson550b14b2009-08-28 05:49:21 +00006797 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006798
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006799 if (SS.isEmpty()) {
6800 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006801 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006802 }
Mike Stump1eb44332009-09-09 15:08:12 +00006803
John McCall9f54ad42009-12-10 09:41:52 +00006804 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006805 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006806 ForRedeclaration);
6807 Previous.setHideTags(false);
6808 if (S) {
6809 LookupName(Previous, S);
6810
6811 // It is really dumb that we have to do this.
6812 LookupResult::Filter F = Previous.makeFilter();
6813 while (F.hasNext()) {
6814 NamedDecl *D = F.next();
6815 if (!isDeclInScope(D, CurContext, S))
6816 F.erase();
6817 }
6818 F.done();
6819 } else {
6820 assert(IsInstantiation && "no scope in non-instantiation");
6821 assert(CurContext->isRecord() && "scope not record in instantiation");
6822 LookupQualifiedName(Previous, CurContext);
6823 }
6824
John McCall9f54ad42009-12-10 09:41:52 +00006825 // Check for invalid redeclarations.
6826 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6827 return 0;
6828
6829 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006830 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6831 return 0;
6832
John McCallaf8e6ed2009-11-12 03:15:40 +00006833 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006834 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006835 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006836 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006837 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006838 // FIXME: not all declaration name kinds are legal here
6839 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6840 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006841 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006842 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006843 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006844 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6845 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006846 }
John McCalled976492009-12-04 22:46:56 +00006847 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006848 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6849 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006850 }
John McCalled976492009-12-04 22:46:56 +00006851 D->setAccess(AS);
6852 CurContext->addDecl(D);
6853
6854 if (!LookupContext) return D;
6855 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006856
John McCall77bb1aa2010-05-01 00:40:08 +00006857 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006858 UD->setInvalidDecl();
6859 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006860 }
6861
Richard Smithc5a89a12012-04-02 01:30:27 +00006862 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006863 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006864 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006865 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006866 return UD;
6867 }
6868
6869 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006870
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006871 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006872
John McCall604e7f12009-12-08 07:46:18 +00006873 // Unlike most lookups, we don't always want to hide tag
6874 // declarations: tag names are visible through the using declaration
6875 // even if hidden by ordinary names, *except* in a dependent context
6876 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006877 if (!IsInstantiation)
6878 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006879
John McCallb9abd8722012-04-07 03:04:20 +00006880 // For the purposes of this lookup, we have a base object type
6881 // equal to that of the current context.
6882 if (CurContext->isRecord()) {
6883 R.setBaseObjectType(
6884 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6885 }
6886
John McCalla24dc2e2009-11-17 02:14:36 +00006887 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006888
John McCallf36e02d2009-10-09 21:13:30 +00006889 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006890 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006891 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006892 UD->setInvalidDecl();
6893 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006894 }
6895
John McCalled976492009-12-04 22:46:56 +00006896 if (R.isAmbiguous()) {
6897 UD->setInvalidDecl();
6898 return UD;
6899 }
Mike Stump1eb44332009-09-09 15:08:12 +00006900
John McCall7ba107a2009-11-18 02:36:19 +00006901 if (IsTypeName) {
6902 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006903 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006904 Diag(IdentLoc, diag::err_using_typename_non_type);
6905 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6906 Diag((*I)->getUnderlyingDecl()->getLocation(),
6907 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006908 UD->setInvalidDecl();
6909 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006910 }
6911 } else {
6912 // If we asked for a non-typename and we got a type, error out,
6913 // but only if this is an instantiation of an unresolved using
6914 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006915 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006916 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6917 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006918 UD->setInvalidDecl();
6919 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006920 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006921 }
6922
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006923 // C++0x N2914 [namespace.udecl]p6:
6924 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006925 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006926 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6927 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006928 UD->setInvalidDecl();
6929 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006930 }
Mike Stump1eb44332009-09-09 15:08:12 +00006931
John McCall9f54ad42009-12-10 09:41:52 +00006932 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6933 if (!CheckUsingShadowDecl(UD, *I, Previous))
6934 BuildUsingShadowDecl(S, UD, *I);
6935 }
John McCall9488ea12009-11-17 05:59:44 +00006936
6937 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006938}
6939
Sebastian Redlf677ea32011-02-05 19:23:19 +00006940/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006941bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6942 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006943
Douglas Gregordc355712011-02-25 00:36:19 +00006944 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006945 assert(SourceType &&
6946 "Using decl naming constructor doesn't have type in scope spec.");
6947 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6948
6949 // Check whether the named type is a direct base class.
6950 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6951 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6952 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6953 BaseIt != BaseE; ++BaseIt) {
6954 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6955 if (CanonicalSourceType == BaseType)
6956 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006957 if (BaseIt->getType()->isDependentType())
6958 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006959 }
6960
6961 if (BaseIt == BaseE) {
6962 // Did not find SourceType in the bases.
6963 Diag(UD->getUsingLocation(),
6964 diag::err_using_decl_constructor_not_in_direct_base)
6965 << UD->getNameInfo().getSourceRange()
6966 << QualType(SourceType, 0) << TargetClass;
6967 return true;
6968 }
6969
Richard Smithc5a89a12012-04-02 01:30:27 +00006970 if (!CurContext->isDependentContext())
6971 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006972
6973 return false;
6974}
6975
John McCall9f54ad42009-12-10 09:41:52 +00006976/// Checks that the given using declaration is not an invalid
6977/// redeclaration. Note that this is checking only for the using decl
6978/// itself, not for any ill-formedness among the UsingShadowDecls.
6979bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6980 bool isTypeName,
6981 const CXXScopeSpec &SS,
6982 SourceLocation NameLoc,
6983 const LookupResult &Prev) {
6984 // C++03 [namespace.udecl]p8:
6985 // C++0x [namespace.udecl]p10:
6986 // A using-declaration is a declaration and can therefore be used
6987 // repeatedly where (and only where) multiple declarations are
6988 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006989 //
John McCall8a726212010-11-29 18:01:58 +00006990 // That's in non-member contexts.
6991 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006992 return false;
6993
6994 NestedNameSpecifier *Qual
6995 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6996
6997 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6998 NamedDecl *D = *I;
6999
7000 bool DTypename;
7001 NestedNameSpecifier *DQual;
7002 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7003 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007004 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007005 } else if (UnresolvedUsingValueDecl *UD
7006 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7007 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007008 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007009 } else if (UnresolvedUsingTypenameDecl *UD
7010 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7011 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007012 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007013 } else continue;
7014
7015 // using decls differ if one says 'typename' and the other doesn't.
7016 // FIXME: non-dependent using decls?
7017 if (isTypeName != DTypename) continue;
7018
7019 // using decls differ if they name different scopes (but note that
7020 // template instantiation can cause this check to trigger when it
7021 // didn't before instantiation).
7022 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7023 Context.getCanonicalNestedNameSpecifier(DQual))
7024 continue;
7025
7026 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007027 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007028 return true;
7029 }
7030
7031 return false;
7032}
7033
John McCall604e7f12009-12-08 07:46:18 +00007034
John McCalled976492009-12-04 22:46:56 +00007035/// Checks that the given nested-name qualifier used in a using decl
7036/// in the current context is appropriately related to the current
7037/// scope. If an error is found, diagnoses it and returns true.
7038bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7039 const CXXScopeSpec &SS,
7040 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007041 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007042
John McCall604e7f12009-12-08 07:46:18 +00007043 if (!CurContext->isRecord()) {
7044 // C++03 [namespace.udecl]p3:
7045 // C++0x [namespace.udecl]p8:
7046 // A using-declaration for a class member shall be a member-declaration.
7047
7048 // If we weren't able to compute a valid scope, it must be a
7049 // dependent class scope.
7050 if (!NamedContext || NamedContext->isRecord()) {
7051 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7052 << SS.getRange();
7053 return true;
7054 }
7055
7056 // Otherwise, everything is known to be fine.
7057 return false;
7058 }
7059
7060 // The current scope is a record.
7061
7062 // If the named context is dependent, we can't decide much.
7063 if (!NamedContext) {
7064 // FIXME: in C++0x, we can diagnose if we can prove that the
7065 // nested-name-specifier does not refer to a base class, which is
7066 // still possible in some cases.
7067
7068 // Otherwise we have to conservatively report that things might be
7069 // okay.
7070 return false;
7071 }
7072
7073 if (!NamedContext->isRecord()) {
7074 // Ideally this would point at the last name in the specifier,
7075 // but we don't have that level of source info.
7076 Diag(SS.getRange().getBegin(),
7077 diag::err_using_decl_nested_name_specifier_is_not_class)
7078 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7079 return true;
7080 }
7081
Douglas Gregor6fb07292010-12-21 07:41:49 +00007082 if (!NamedContext->isDependentContext() &&
7083 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7084 return true;
7085
Richard Smith80ad52f2013-01-02 11:42:31 +00007086 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007087 // C++0x [namespace.udecl]p3:
7088 // In a using-declaration used as a member-declaration, the
7089 // nested-name-specifier shall name a base class of the class
7090 // being defined.
7091
7092 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7093 cast<CXXRecordDecl>(NamedContext))) {
7094 if (CurContext == NamedContext) {
7095 Diag(NameLoc,
7096 diag::err_using_decl_nested_name_specifier_is_current_class)
7097 << SS.getRange();
7098 return true;
7099 }
7100
7101 Diag(SS.getRange().getBegin(),
7102 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7103 << (NestedNameSpecifier*) SS.getScopeRep()
7104 << cast<CXXRecordDecl>(CurContext)
7105 << SS.getRange();
7106 return true;
7107 }
7108
7109 return false;
7110 }
7111
7112 // C++03 [namespace.udecl]p4:
7113 // A using-declaration used as a member-declaration shall refer
7114 // to a member of a base class of the class being defined [etc.].
7115
7116 // Salient point: SS doesn't have to name a base class as long as
7117 // lookup only finds members from base classes. Therefore we can
7118 // diagnose here only if we can prove that that can't happen,
7119 // i.e. if the class hierarchies provably don't intersect.
7120
7121 // TODO: it would be nice if "definitely valid" results were cached
7122 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7123 // need to be repeated.
7124
7125 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007126 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007127
7128 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7129 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7130 Data->Bases.insert(Base);
7131 return true;
7132 }
7133
7134 bool hasDependentBases(const CXXRecordDecl *Class) {
7135 return !Class->forallBases(collect, this);
7136 }
7137
7138 /// Returns true if the base is dependent or is one of the
7139 /// accumulated base classes.
7140 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7141 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7142 return !Data->Bases.count(Base);
7143 }
7144
7145 bool mightShareBases(const CXXRecordDecl *Class) {
7146 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7147 }
7148 };
7149
7150 UserData Data;
7151
7152 // Returns false if we find a dependent base.
7153 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7154 return false;
7155
7156 // Returns false if the class has a dependent base or if it or one
7157 // of its bases is present in the base set of the current context.
7158 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7159 return false;
7160
7161 Diag(SS.getRange().getBegin(),
7162 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7163 << (NestedNameSpecifier*) SS.getScopeRep()
7164 << cast<CXXRecordDecl>(CurContext)
7165 << SS.getRange();
7166
7167 return true;
John McCalled976492009-12-04 22:46:56 +00007168}
7169
Richard Smith162e1c12011-04-15 14:24:37 +00007170Decl *Sema::ActOnAliasDeclaration(Scope *S,
7171 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007172 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007173 SourceLocation UsingLoc,
7174 UnqualifiedId &Name,
7175 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007176 // Skip up to the relevant declaration scope.
7177 while (S->getFlags() & Scope::TemplateParamScope)
7178 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007179 assert((S->getFlags() & Scope::DeclScope) &&
7180 "got alias-declaration outside of declaration scope");
7181
7182 if (Type.isInvalid())
7183 return 0;
7184
7185 bool Invalid = false;
7186 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7187 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007188 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007189
7190 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7191 return 0;
7192
7193 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007194 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007195 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007196 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7197 TInfo->getTypeLoc().getBeginLoc());
7198 }
Richard Smith162e1c12011-04-15 14:24:37 +00007199
7200 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7201 LookupName(Previous, S);
7202
7203 // Warn about shadowing the name of a template parameter.
7204 if (Previous.isSingleResult() &&
7205 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007206 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007207 Previous.clear();
7208 }
7209
7210 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7211 "name in alias declaration must be an identifier");
7212 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7213 Name.StartLocation,
7214 Name.Identifier, TInfo);
7215
7216 NewTD->setAccess(AS);
7217
7218 if (Invalid)
7219 NewTD->setInvalidDecl();
7220
Richard Smith3e4c6c42011-05-05 21:57:07 +00007221 CheckTypedefForVariablyModifiedType(S, NewTD);
7222 Invalid |= NewTD->isInvalidDecl();
7223
Richard Smith162e1c12011-04-15 14:24:37 +00007224 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007225
7226 NamedDecl *NewND;
7227 if (TemplateParamLists.size()) {
7228 TypeAliasTemplateDecl *OldDecl = 0;
7229 TemplateParameterList *OldTemplateParams = 0;
7230
7231 if (TemplateParamLists.size() != 1) {
7232 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007233 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7234 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007235 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007236 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007237
7238 // Only consider previous declarations in the same scope.
7239 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7240 /*ExplicitInstantiationOrSpecialization*/false);
7241 if (!Previous.empty()) {
7242 Redeclaration = true;
7243
7244 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7245 if (!OldDecl && !Invalid) {
7246 Diag(UsingLoc, diag::err_redefinition_different_kind)
7247 << Name.Identifier;
7248
7249 NamedDecl *OldD = Previous.getRepresentativeDecl();
7250 if (OldD->getLocation().isValid())
7251 Diag(OldD->getLocation(), diag::note_previous_definition);
7252
7253 Invalid = true;
7254 }
7255
7256 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7257 if (TemplateParameterListsAreEqual(TemplateParams,
7258 OldDecl->getTemplateParameters(),
7259 /*Complain=*/true,
7260 TPL_TemplateMatch))
7261 OldTemplateParams = OldDecl->getTemplateParameters();
7262 else
7263 Invalid = true;
7264
7265 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7266 if (!Invalid &&
7267 !Context.hasSameType(OldTD->getUnderlyingType(),
7268 NewTD->getUnderlyingType())) {
7269 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7270 // but we can't reasonably accept it.
7271 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7272 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7273 if (OldTD->getLocation().isValid())
7274 Diag(OldTD->getLocation(), diag::note_previous_definition);
7275 Invalid = true;
7276 }
7277 }
7278 }
7279
7280 // Merge any previous default template arguments into our parameters,
7281 // and check the parameter list.
7282 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7283 TPC_TypeAliasTemplate))
7284 return 0;
7285
7286 TypeAliasTemplateDecl *NewDecl =
7287 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7288 Name.Identifier, TemplateParams,
7289 NewTD);
7290
7291 NewDecl->setAccess(AS);
7292
7293 if (Invalid)
7294 NewDecl->setInvalidDecl();
7295 else if (OldDecl)
7296 NewDecl->setPreviousDeclaration(OldDecl);
7297
7298 NewND = NewDecl;
7299 } else {
7300 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7301 NewND = NewTD;
7302 }
Richard Smith162e1c12011-04-15 14:24:37 +00007303
7304 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007305 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007306
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007307 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007308 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007309}
7310
John McCalld226f652010-08-21 09:40:31 +00007311Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007312 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007313 SourceLocation AliasLoc,
7314 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007315 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007316 SourceLocation IdentLoc,
7317 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007318
Anders Carlsson81c85c42009-03-28 23:53:49 +00007319 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007320 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7321 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007322
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007323 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007324 NamedDecl *PrevDecl
7325 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7326 ForRedeclaration);
7327 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7328 PrevDecl = 0;
7329
7330 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007331 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007332 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007333 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007334 // FIXME: At some point, we'll want to create the (redundant)
7335 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007336 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007337 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007338 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007339 }
Mike Stump1eb44332009-09-09 15:08:12 +00007340
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007341 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7342 diag::err_redefinition_different_kind;
7343 Diag(AliasLoc, DiagID) << Alias;
7344 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007345 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007346 }
7347
John McCalla24dc2e2009-11-17 02:14:36 +00007348 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007349 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007350
John McCallf36e02d2009-10-09 21:13:30 +00007351 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007352 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007353 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007354 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007355 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007356 }
Mike Stump1eb44332009-09-09 15:08:12 +00007357
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007358 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007359 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007360 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007361 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007362
John McCall3dbd3d52010-02-16 06:53:13 +00007363 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007364 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007365}
7366
Sean Hunt001cad92011-05-10 00:49:42 +00007367Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007368Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7369 CXXMethodDecl *MD) {
7370 CXXRecordDecl *ClassDecl = MD->getParent();
7371
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007372 // C++ [except.spec]p14:
7373 // An implicitly declared special member function (Clause 12) shall have an
7374 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007375 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007376 if (ClassDecl->isInvalidDecl())
7377 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007378
Sebastian Redl60618fa2011-03-12 11:50:43 +00007379 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007380 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7381 BEnd = ClassDecl->bases_end();
7382 B != BEnd; ++B) {
7383 if (B->isVirtual()) // Handled below.
7384 continue;
7385
Douglas Gregor18274032010-07-03 00:47:00 +00007386 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7387 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007388 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7389 // If this is a deleted function, add it anyway. This might be conformant
7390 // with the standard. This might not. I'm not sure. It might not matter.
7391 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007392 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007393 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007394 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007395
7396 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007397 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7398 BEnd = ClassDecl->vbases_end();
7399 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007400 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7401 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007402 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7403 // If this is a deleted function, add it anyway. This might be conformant
7404 // with the standard. This might not. I'm not sure. It might not matter.
7405 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007406 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007407 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007408 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007409
7410 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007411 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7412 FEnd = ClassDecl->field_end();
7413 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007414 if (F->hasInClassInitializer()) {
7415 if (Expr *E = F->getInClassInitializer())
7416 ExceptSpec.CalledExpr(E);
7417 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007418 // DR1351:
7419 // If the brace-or-equal-initializer of a non-static data member
7420 // invokes a defaulted default constructor of its class or of an
7421 // enclosing class in a potentially evaluated subexpression, the
7422 // program is ill-formed.
7423 //
7424 // This resolution is unworkable: the exception specification of the
7425 // default constructor can be needed in an unevaluated context, in
7426 // particular, in the operand of a noexcept-expression, and we can be
7427 // unable to compute an exception specification for an enclosed class.
7428 //
7429 // We do not allow an in-class initializer to require the evaluation
7430 // of the exception specification for any in-class initializer whose
7431 // definition is not lexically complete.
7432 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007433 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007434 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007435 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7436 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7437 // If this is a deleted function, add it anyway. This might be conformant
7438 // with the standard. This might not. I'm not sure. It might not matter.
7439 // In particular, the problem is that this function never gets called. It
7440 // might just be ill-formed because this function attempts to refer to
7441 // a deleted function here.
7442 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007443 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007444 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007445 }
John McCalle23cf432010-12-14 08:05:40 +00007446
Sean Hunt001cad92011-05-10 00:49:42 +00007447 return ExceptSpec;
7448}
7449
Richard Smithafb49182012-11-29 01:34:07 +00007450namespace {
7451/// RAII object to register a special member as being currently declared.
7452struct DeclaringSpecialMember {
7453 Sema &S;
7454 Sema::SpecialMemberDecl D;
7455 bool WasAlreadyBeingDeclared;
7456
7457 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7458 : S(S), D(RD, CSM) {
7459 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7460 if (WasAlreadyBeingDeclared)
7461 // This almost never happens, but if it does, ensure that our cache
7462 // doesn't contain a stale result.
7463 S.SpecialMemberCache.clear();
7464
7465 // FIXME: Register a note to be produced if we encounter an error while
7466 // declaring the special member.
7467 }
7468 ~DeclaringSpecialMember() {
7469 if (!WasAlreadyBeingDeclared)
7470 S.SpecialMembersBeingDeclared.erase(D);
7471 }
7472
7473 /// \brief Are we already trying to declare this special member?
7474 bool isAlreadyBeingDeclared() const {
7475 return WasAlreadyBeingDeclared;
7476 }
7477};
7478}
7479
Sean Hunt001cad92011-05-10 00:49:42 +00007480CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7481 CXXRecordDecl *ClassDecl) {
7482 // C++ [class.ctor]p5:
7483 // A default constructor for a class X is a constructor of class X
7484 // that can be called without an argument. If there is no
7485 // user-declared constructor for class X, a default constructor is
7486 // implicitly declared. An implicitly-declared default constructor
7487 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007488 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007489 "Should not build implicit default constructor!");
7490
Richard Smithafb49182012-11-29 01:34:07 +00007491 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7492 if (DSM.isAlreadyBeingDeclared())
7493 return 0;
7494
Richard Smith7756afa2012-06-10 05:43:50 +00007495 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7496 CXXDefaultConstructor,
7497 false);
7498
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007499 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007500 CanQualType ClassType
7501 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007502 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007503 DeclarationName Name
7504 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007505 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007506 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007507 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007508 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007509 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007510 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007511 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007512 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007513
7514 // Build an exception specification pointing back at this constructor.
7515 FunctionProtoType::ExtProtoInfo EPI;
7516 EPI.ExceptionSpecType = EST_Unevaluated;
7517 EPI.ExceptionSpecDecl = DefaultCon;
7518 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7519
Richard Smithbc2a35d2012-12-08 08:32:28 +00007520 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7521 // constructors is easy to compute.
7522 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7523
7524 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7525 DefaultCon->setDeletedAsWritten();
7526
Douglas Gregor18274032010-07-03 00:47:00 +00007527 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007528 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007529
Douglas Gregor23c94db2010-07-02 17:43:08 +00007530 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007531 PushOnScopeChains(DefaultCon, S, false);
7532 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007533
Douglas Gregor32df23e2010-07-01 22:02:46 +00007534 return DefaultCon;
7535}
7536
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007537void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7538 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007539 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007540 !Constructor->doesThisDeclarationHaveABody() &&
7541 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007542 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007543
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007544 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007545 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007546
Eli Friedman9a14db32012-10-18 20:14:08 +00007547 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007548 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007549 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007550 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007551 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007552 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007553 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007554 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007555 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007556
7557 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007558 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007559
7560 Constructor->setUsed();
7561 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007562
7563 if (ASTMutationListener *L = getASTMutationListener()) {
7564 L->CompletedImplicitDefinition(Constructor);
7565 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007566}
7567
Richard Smith7a614d82011-06-11 17:19:42 +00007568void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007569 // Check that any explicitly-defaulted methods have exception specifications
7570 // compatible with their implicit exception specifications.
7571 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007572}
7573
Sebastian Redlf677ea32011-02-05 19:23:19 +00007574void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7575 // We start with an initial pass over the base classes to collect those that
7576 // inherit constructors from. If there are none, we can forgo all further
7577 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007578 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007579 BasesVector BasesToInheritFrom;
7580 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7581 BaseE = ClassDecl->bases_end();
7582 BaseIt != BaseE; ++BaseIt) {
7583 if (BaseIt->getInheritConstructors()) {
7584 QualType Base = BaseIt->getType();
7585 if (Base->isDependentType()) {
7586 // If we inherit constructors from anything that is dependent, just
7587 // abort processing altogether. We'll get another chance for the
7588 // instantiations.
7589 return;
7590 }
7591 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7592 }
7593 }
7594 if (BasesToInheritFrom.empty())
7595 return;
7596
7597 // Now collect the constructors that we already have in the current class.
7598 // Those take precedence over inherited constructors.
7599 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7600 // unless there is a user-declared constructor with the same signature in
7601 // the class where the using-declaration appears.
7602 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7603 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7604 CtorE = ClassDecl->ctor_end();
7605 CtorIt != CtorE; ++CtorIt) {
7606 ExistingConstructors.insert(
7607 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7608 }
7609
Sebastian Redlf677ea32011-02-05 19:23:19 +00007610 DeclarationName CreatedCtorName =
7611 Context.DeclarationNames.getCXXConstructorName(
7612 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7613
7614 // Now comes the true work.
7615 // First, we keep a map from constructor types to the base that introduced
7616 // them. Needed for finding conflicting constructors. We also keep the
7617 // actually inserted declarations in there, for pretty diagnostics.
7618 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7619 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7620 ConstructorToSourceMap InheritedConstructors;
7621 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7622 BaseE = BasesToInheritFrom.end();
7623 BaseIt != BaseE; ++BaseIt) {
7624 const RecordType *Base = *BaseIt;
7625 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7626 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7627 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7628 CtorE = BaseDecl->ctor_end();
7629 CtorIt != CtorE; ++CtorIt) {
7630 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00007631 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00007632 DeclarationName Name =
7633 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00007634 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7635 LookupQualifiedName(Result, CurContext);
7636 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007637 SourceLocation UsingLoc = UD ? UD->getLocation() :
7638 ClassDecl->getLocation();
7639
7640 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7641 // from the class X named in the using-declaration consists of actual
7642 // constructors and notional constructors that result from the
7643 // transformation of defaulted parameters as follows:
7644 // - all non-template default constructors of X, and
7645 // - for each non-template constructor of X that has at least one
7646 // parameter with a default argument, the set of constructors that
7647 // results from omitting any ellipsis parameter specification and
7648 // successively omitting parameters with a default argument from the
7649 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00007650 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007651 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7652 const FunctionProtoType *BaseCtorType =
7653 BaseCtor->getType()->getAs<FunctionProtoType>();
7654
7655 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7656 maxParams = BaseCtor->getNumParams();
7657 params <= maxParams; ++params) {
7658 // Skip default constructors. They're never inherited.
7659 if (params == 0)
7660 continue;
7661 // Skip copy and move constructors for the same reason.
7662 if (CanBeCopyOrMove && params == 1)
7663 continue;
7664
7665 // Build up a function type for this particular constructor.
7666 // FIXME: The working paper does not consider that the exception spec
7667 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007668 // source. This code doesn't yet, either. When it does, this code will
7669 // need to be delayed until after exception specifications and in-class
7670 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007671 const Type *NewCtorType;
7672 if (params == maxParams)
7673 NewCtorType = BaseCtorType;
7674 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007675 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007676 for (unsigned i = 0; i < params; ++i) {
7677 Args.push_back(BaseCtorType->getArgType(i));
7678 }
7679 FunctionProtoType::ExtProtoInfo ExtInfo =
7680 BaseCtorType->getExtProtoInfo();
7681 ExtInfo.Variadic = false;
7682 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7683 Args.data(), params, ExtInfo)
7684 .getTypePtr();
7685 }
7686 const Type *CanonicalNewCtorType =
7687 Context.getCanonicalType(NewCtorType);
7688
7689 // Now that we have the type, first check if the class already has a
7690 // constructor with this signature.
7691 if (ExistingConstructors.count(CanonicalNewCtorType))
7692 continue;
7693
7694 // Then we check if we have already declared an inherited constructor
7695 // with this signature.
7696 std::pair<ConstructorToSourceMap::iterator, bool> result =
7697 InheritedConstructors.insert(std::make_pair(
7698 CanonicalNewCtorType,
7699 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7700 if (!result.second) {
7701 // Already in the map. If it came from a different class, that's an
7702 // error. Not if it's from the same.
7703 CanQualType PreviousBase = result.first->second.first;
7704 if (CanonicalBase != PreviousBase) {
7705 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7706 const CXXConstructorDecl *PrevBaseCtor =
7707 PrevCtor->getInheritedConstructor();
7708 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7709
7710 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7711 Diag(BaseCtor->getLocation(),
7712 diag::note_using_decl_constructor_conflict_current_ctor);
7713 Diag(PrevBaseCtor->getLocation(),
7714 diag::note_using_decl_constructor_conflict_previous_ctor);
7715 Diag(PrevCtor->getLocation(),
7716 diag::note_using_decl_constructor_conflict_previous_using);
7717 }
7718 continue;
7719 }
7720
7721 // OK, we're there, now add the constructor.
7722 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007723 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007724 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7725 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007726 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7727 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007728 /*ImplicitlyDeclared=*/true,
7729 // FIXME: Due to a defect in the standard, we treat inherited
7730 // constructors as constexpr even if that makes them ill-formed.
7731 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007732 NewCtor->setAccess(BaseCtor->getAccess());
7733
7734 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007735 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007736 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007737 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7738 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007739 /*IdentifierInfo=*/0,
7740 BaseCtorType->getArgType(i),
7741 /*TInfo=*/0, SC_None,
7742 SC_None, /*DefaultArg=*/0));
7743 }
David Blaikie4278c652011-09-21 18:16:56 +00007744 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007745 NewCtor->setInheritedConstructor(BaseCtor);
7746
Sebastian Redlf677ea32011-02-05 19:23:19 +00007747 ClassDecl->addDecl(NewCtor);
7748 result.first->second.second = NewCtor;
7749 }
7750 }
7751 }
7752}
7753
Sean Huntcb45a0f2011-05-12 22:46:25 +00007754Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007755Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7756 CXXRecordDecl *ClassDecl = MD->getParent();
7757
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007758 // C++ [except.spec]p14:
7759 // An implicitly declared special member function (Clause 12) shall have
7760 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007761 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007762 if (ClassDecl->isInvalidDecl())
7763 return ExceptSpec;
7764
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007765 // Direct base-class destructors.
7766 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7767 BEnd = ClassDecl->bases_end();
7768 B != BEnd; ++B) {
7769 if (B->isVirtual()) // Handled below.
7770 continue;
7771
7772 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007773 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007774 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007775 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007776
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007777 // Virtual base-class destructors.
7778 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7779 BEnd = ClassDecl->vbases_end();
7780 B != BEnd; ++B) {
7781 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007782 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007783 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007784 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007785
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007786 // Field destructors.
7787 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7788 FEnd = ClassDecl->field_end();
7789 F != FEnd; ++F) {
7790 if (const RecordType *RecordTy
7791 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007792 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007793 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007794 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007795
Sean Huntcb45a0f2011-05-12 22:46:25 +00007796 return ExceptSpec;
7797}
7798
7799CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7800 // C++ [class.dtor]p2:
7801 // If a class has no user-declared destructor, a destructor is
7802 // declared implicitly. An implicitly-declared destructor is an
7803 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00007804 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00007805
Richard Smithafb49182012-11-29 01:34:07 +00007806 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7807 if (DSM.isAlreadyBeingDeclared())
7808 return 0;
7809
Douglas Gregor4923aa22010-07-02 20:37:36 +00007810 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007811 CanQualType ClassType
7812 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007813 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007814 DeclarationName Name
7815 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007816 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007817 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007818 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7819 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007820 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007821 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007822 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007823 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007824
7825 // Build an exception specification pointing back at this destructor.
7826 FunctionProtoType::ExtProtoInfo EPI;
7827 EPI.ExceptionSpecType = EST_Unevaluated;
7828 EPI.ExceptionSpecDecl = Destructor;
7829 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7830
Richard Smithbc2a35d2012-12-08 08:32:28 +00007831 AddOverriddenMethods(ClassDecl, Destructor);
7832
7833 // We don't need to use SpecialMemberIsTrivial here; triviality for
7834 // destructors is easy to compute.
7835 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7836
7837 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7838 Destructor->setDeletedAsWritten();
7839
Douglas Gregor4923aa22010-07-02 20:37:36 +00007840 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007841 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007842
Douglas Gregor4923aa22010-07-02 20:37:36 +00007843 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007844 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007845 PushOnScopeChains(Destructor, S, false);
7846 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007847
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007848 return Destructor;
7849}
7850
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007851void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007852 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007853 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007854 !Destructor->doesThisDeclarationHaveABody() &&
7855 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007856 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007857 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007858 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007859
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007860 if (Destructor->isInvalidDecl())
7861 return;
7862
Eli Friedman9a14db32012-10-18 20:14:08 +00007863 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007864
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007865 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007866 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7867 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007868
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007869 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007870 Diag(CurrentLocation, diag::note_member_synthesized_at)
7871 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7872
7873 Destructor->setInvalidDecl();
7874 return;
7875 }
7876
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007877 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007878 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007879 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007880 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007881 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007882
7883 if (ASTMutationListener *L = getASTMutationListener()) {
7884 L->CompletedImplicitDefinition(Destructor);
7885 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007886}
7887
Richard Smitha4156b82012-04-21 18:42:51 +00007888/// \brief Perform any semantic analysis which needs to be delayed until all
7889/// pending class member declarations have been parsed.
7890void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00007891 // If the context is an invalid C++ class, just suppress these checks.
7892 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
7893 if (Record->isInvalidDecl()) {
7894 DelayedDestructorExceptionSpecChecks.clear();
7895 return;
7896 }
7897 }
7898
Richard Smitha4156b82012-04-21 18:42:51 +00007899 // Perform any deferred checking of exception specifications for virtual
7900 // destructors.
7901 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7902 i != e; ++i) {
7903 const CXXDestructorDecl *Dtor =
7904 DelayedDestructorExceptionSpecChecks[i].first;
7905 assert(!Dtor->getParent()->isDependentType() &&
7906 "Should not ever add destructors of templates into the list.");
7907 CheckOverridingFunctionExceptionSpec(Dtor,
7908 DelayedDestructorExceptionSpecChecks[i].second);
7909 }
7910 DelayedDestructorExceptionSpecChecks.clear();
7911}
7912
Richard Smithb9d0b762012-07-27 04:22:15 +00007913void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7914 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00007915 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00007916 "adjusting dtor exception specs was introduced in c++11");
7917
Sebastian Redl0ee33912011-05-19 05:13:44 +00007918 // C++11 [class.dtor]p3:
7919 // A declaration of a destructor that does not have an exception-
7920 // specification is implicitly considered to have the same exception-
7921 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007922 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007923 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007924 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007925 return;
7926
Chandler Carruth3f224b22011-09-20 04:55:26 +00007927 // Replace the destructor's type, building off the existing one. Fortunately,
7928 // the only thing of interest in the destructor type is its extended info.
7929 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007930 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7931 EPI.ExceptionSpecType = EST_Unevaluated;
7932 EPI.ExceptionSpecDecl = Destructor;
7933 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007934
Sebastian Redl0ee33912011-05-19 05:13:44 +00007935 // FIXME: If the destructor has a body that could throw, and the newly created
7936 // spec doesn't allow exceptions, we should emit a warning, because this
7937 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007938 // However, we don't have a body or an exception specification yet, so it
7939 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007940}
7941
Richard Smith8c889532012-11-14 00:50:40 +00007942/// When generating a defaulted copy or move assignment operator, if a field
7943/// should be copied with __builtin_memcpy rather than via explicit assignments,
7944/// do so. This optimization only applies for arrays of scalars, and for arrays
7945/// of class type where the selected copy/move-assignment operator is trivial.
7946static StmtResult
7947buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
7948 Expr *To, Expr *From) {
7949 // Compute the size of the memory buffer to be copied.
7950 QualType SizeType = S.Context.getSizeType();
7951 llvm::APInt Size(S.Context.getTypeSize(SizeType),
7952 S.Context.getTypeSizeInChars(T).getQuantity());
7953
7954 // Take the address of the field references for "from" and "to". We
7955 // directly construct UnaryOperators here because semantic analysis
7956 // does not permit us to take the address of an xvalue.
7957 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
7958 S.Context.getPointerType(From->getType()),
7959 VK_RValue, OK_Ordinary, Loc);
7960 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
7961 S.Context.getPointerType(To->getType()),
7962 VK_RValue, OK_Ordinary, Loc);
7963
7964 const Type *E = T->getBaseElementTypeUnsafe();
7965 bool NeedsCollectableMemCpy =
7966 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
7967
7968 // Create a reference to the __builtin_objc_memmove_collectable function
7969 StringRef MemCpyName = NeedsCollectableMemCpy ?
7970 "__builtin_objc_memmove_collectable" :
7971 "__builtin_memcpy";
7972 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
7973 Sema::LookupOrdinaryName);
7974 S.LookupName(R, S.TUScope, true);
7975
7976 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
7977 if (!MemCpy)
7978 // Something went horribly wrong earlier, and we will have complained
7979 // about it.
7980 return StmtError();
7981
7982 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
7983 VK_RValue, Loc, 0);
7984 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
7985
7986 Expr *CallArgs[] = {
7987 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
7988 };
7989 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
7990 Loc, CallArgs, Loc);
7991
7992 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7993 return S.Owned(Call.takeAs<Stmt>());
7994}
7995
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007996/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007997/// \c To.
7998///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007999/// This routine is used to copy/move the members of a class with an
8000/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008001/// copied are arrays, this routine builds for loops to copy them.
8002///
8003/// \param S The Sema object used for type-checking.
8004///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008005/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008006///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008007/// \param T The type of the expressions being copied/moved. Both expressions
8008/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008009///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008010/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008011///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008012/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008013///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008014/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008015/// Otherwise, it's a non-static member subobject.
8016///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008017/// \param Copying Whether we're copying or moving.
8018///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008019/// \param Depth Internal parameter recording the depth of the recursion.
8020///
Richard Smith8c889532012-11-14 00:50:40 +00008021/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8022/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008023static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008024buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8025 Expr *To, Expr *From,
8026 bool CopyingBaseSubobject, bool Copying,
8027 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008028 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008029 // Each subobject is assigned in the manner appropriate to its type:
8030 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008031 // - if the subobject is of class type, as if by a call to operator= with
8032 // the subobject as the object expression and the corresponding
8033 // subobject of x as a single function argument (as if by explicit
8034 // qualification; that is, ignoring any possible virtual overriding
8035 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008036 //
8037 // C++03 [class.copy]p13:
8038 // - if the subobject is of class type, the copy assignment operator for
8039 // the class is used (as if by explicit qualification; that is,
8040 // ignoring any possible virtual overriding functions in more derived
8041 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008042 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8043 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008044
Douglas Gregor06a9f362010-05-01 20:49:11 +00008045 // Look for operator=.
8046 DeclarationName Name
8047 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8048 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8049 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008050
Richard Smith044c8aa2012-11-13 00:54:12 +00008051 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8052 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008053 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008054 LookupResult::Filter F = OpLookup.makeFilter();
8055 while (F.hasNext()) {
8056 NamedDecl *D = F.next();
8057 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8058 if (Method->isCopyAssignmentOperator() ||
8059 (!Copying && Method->isMoveAssignmentOperator()))
8060 continue;
8061
8062 F.erase();
8063 }
8064 F.done();
John McCallb0207482010-03-16 06:11:48 +00008065 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008066
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008067 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008068 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008069 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008070 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008071 // ambiguities), we need to cast "this" to that subobject type; to
8072 // ensure that we don't go through the virtual call mechanism, we need
8073 // to qualify the operator= name with the base class (see below). However,
8074 // this means that if the base class has a protected copy assignment
8075 // operator, the protected member access check will fail. So, we
8076 // rewrite "protected" access to "public" access in this case, since we
8077 // know by construction that we're calling from a derived class.
8078 if (CopyingBaseSubobject) {
8079 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8080 L != LEnd; ++L) {
8081 if (L.getAccess() == AS_protected)
8082 L.setAccess(AS_public);
8083 }
8084 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008085
Douglas Gregor06a9f362010-05-01 20:49:11 +00008086 // Create the nested-name-specifier that will be used to qualify the
8087 // reference to operator=; this is required to suppress the virtual
8088 // call mechanism.
8089 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008090 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008091 SS.MakeTrivial(S.Context,
8092 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008093 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008094 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008095
Douglas Gregor06a9f362010-05-01 20:49:11 +00008096 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008097 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008098 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008099 /*TemplateKWLoc=*/SourceLocation(),
8100 /*FirstQualifierInScope=*/0,
8101 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008102 /*TemplateArgs=*/0,
8103 /*SuppressQualifierCheck=*/true);
8104 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008105 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008106
Douglas Gregor06a9f362010-05-01 20:49:11 +00008107 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008108
Richard Smith044c8aa2012-11-13 00:54:12 +00008109 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008110 OpEqualRef.takeAs<Expr>(),
8111 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008112 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008113 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008114
Richard Smith8c889532012-11-14 00:50:40 +00008115 // If we built a call to a trivial 'operator=' while copying an array,
8116 // bail out. We'll replace the whole shebang with a memcpy.
8117 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8118 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8119 return StmtResult((Stmt*)0);
8120
Richard Smith044c8aa2012-11-13 00:54:12 +00008121 // Convert to an expression-statement, and clean up any produced
8122 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008123 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008124 }
John McCallb0207482010-03-16 06:11:48 +00008125
Richard Smith044c8aa2012-11-13 00:54:12 +00008126 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008127 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008128 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008129 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008130 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008131 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008132 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008133 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008134 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008135
8136 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008137 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008138
Douglas Gregor06a9f362010-05-01 20:49:11 +00008139 // Construct a loop over the array bounds, e.g.,
8140 //
8141 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8142 //
8143 // that will copy each of the array elements.
8144 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008145
Douglas Gregor06a9f362010-05-01 20:49:11 +00008146 // Create the iteration variable.
8147 IdentifierInfo *IterationVarName = 0;
8148 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008149 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008150 llvm::raw_svector_ostream OS(Str);
8151 OS << "__i" << Depth;
8152 IterationVarName = &S.Context.Idents.get(OS.str());
8153 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008154 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008155 IterationVarName, SizeType,
8156 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00008157 SC_None, SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008158
Douglas Gregor06a9f362010-05-01 20:49:11 +00008159 // Initialize the iteration variable to zero.
8160 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008161 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008162
8163 // Create a reference to the iteration variable; we'll use this several
8164 // times throughout.
8165 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008166 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008167 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008168 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8169 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8170
Douglas Gregor06a9f362010-05-01 20:49:11 +00008171 // Create the DeclStmt that holds the iteration variable.
8172 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008173
Douglas Gregor06a9f362010-05-01 20:49:11 +00008174 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008175 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008176 IterationVarRefRVal,
8177 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008178 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008179 IterationVarRefRVal,
8180 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008181 if (!Copying) // Cast to rvalue
8182 From = CastForMoving(S, From);
8183
8184 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008185 StmtResult Copy =
8186 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8187 To, From, CopyingBaseSubobject,
8188 Copying, Depth + 1);
8189 // Bail out if copying fails or if we determined that we should use memcpy.
8190 if (Copy.isInvalid() || !Copy.get())
8191 return Copy;
8192
8193 // Create the comparison against the array bound.
8194 llvm::APInt Upper
8195 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8196 Expr *Comparison
8197 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8198 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8199 BO_NE, S.Context.BoolTy,
8200 VK_RValue, OK_Ordinary, Loc, false);
8201
8202 // Create the pre-increment of the iteration variable.
8203 Expr *Increment
8204 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8205 VK_LValue, OK_Ordinary, Loc);
8206
Douglas Gregor06a9f362010-05-01 20:49:11 +00008207 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008208 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008209 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008210 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008211 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008212}
8213
Richard Smith8c889532012-11-14 00:50:40 +00008214static StmtResult
8215buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8216 Expr *To, Expr *From,
8217 bool CopyingBaseSubobject, bool Copying) {
8218 // Maybe we should use a memcpy?
8219 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8220 T.isTriviallyCopyableType(S.Context))
8221 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8222
8223 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8224 CopyingBaseSubobject,
8225 Copying, 0));
8226
8227 // If we ended up picking a trivial assignment operator for an array of a
8228 // non-trivially-copyable class type, just emit a memcpy.
8229 if (!Result.isInvalid() && !Result.get())
8230 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8231
8232 return Result;
8233}
8234
Richard Smithb9d0b762012-07-27 04:22:15 +00008235Sema::ImplicitExceptionSpecification
8236Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8237 CXXRecordDecl *ClassDecl = MD->getParent();
8238
8239 ImplicitExceptionSpecification ExceptSpec(*this);
8240 if (ClassDecl->isInvalidDecl())
8241 return ExceptSpec;
8242
8243 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8244 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8245 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8246
Douglas Gregorb87786f2010-07-01 17:48:08 +00008247 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008248 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008249 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008250
8251 // It is unspecified whether or not an implicit copy assignment operator
8252 // attempts to deduplicate calls to assignment operators of virtual bases are
8253 // made. As such, this exception specification is effectively unspecified.
8254 // Based on a similar decision made for constness in C++0x, we're erring on
8255 // the side of assuming such calls to be made regardless of whether they
8256 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008257 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8258 BaseEnd = ClassDecl->bases_end();
8259 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008260 if (Base->isVirtual())
8261 continue;
8262
Douglas Gregora376d102010-07-02 21:50:04 +00008263 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008264 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008265 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8266 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008267 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008268 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008269
8270 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8271 BaseEnd = ClassDecl->vbases_end();
8272 Base != BaseEnd; ++Base) {
8273 CXXRecordDecl *BaseClassDecl
8274 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8275 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8276 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008277 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008278 }
8279
Douglas Gregorb87786f2010-07-01 17:48:08 +00008280 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8281 FieldEnd = ClassDecl->field_end();
8282 Field != FieldEnd;
8283 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008284 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008285 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8286 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008287 LookupCopyingAssignment(FieldClassDecl,
8288 ArgQuals | FieldType.getCVRQualifiers(),
8289 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008290 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008291 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008292 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008293
Richard Smithb9d0b762012-07-27 04:22:15 +00008294 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008295}
8296
8297CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8298 // Note: The following rules are largely analoguous to the copy
8299 // constructor rules. Note that virtual bases are not taken into account
8300 // for determining the argument type of the operator. Note also that
8301 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008302 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008303
Richard Smithafb49182012-11-29 01:34:07 +00008304 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8305 if (DSM.isAlreadyBeingDeclared())
8306 return 0;
8307
Sean Hunt30de05c2011-05-14 05:23:20 +00008308 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8309 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008310 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008311 ArgType = ArgType.withConst();
8312 ArgType = Context.getLValueReferenceType(ArgType);
8313
Douglas Gregord3c35902010-07-01 16:36:15 +00008314 // An implicitly-declared copy assignment operator is an inline public
8315 // member of its class.
8316 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008317 SourceLocation ClassLoc = ClassDecl->getLocation();
8318 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008319 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008320 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00008321 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00008322 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008323 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008324 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008325 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008326 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008327 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008328
8329 // Build an exception specification pointing back at this member.
8330 FunctionProtoType::ExtProtoInfo EPI;
8331 EPI.ExceptionSpecType = EST_Unevaluated;
8332 EPI.ExceptionSpecDecl = CopyAssignment;
8333 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8334
Douglas Gregord3c35902010-07-01 16:36:15 +00008335 // Add the parameter to the operator.
8336 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008337 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008338 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008339 SC_None,
8340 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008341 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008342
Richard Smithbc2a35d2012-12-08 08:32:28 +00008343 AddOverriddenMethods(ClassDecl, CopyAssignment);
8344
8345 CopyAssignment->setTrivial(
8346 ClassDecl->needsOverloadResolutionForCopyAssignment()
8347 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8348 : ClassDecl->hasTrivialCopyAssignment());
8349
Nico Weberafcc96a2012-01-23 03:19:29 +00008350 // C++0x [class.copy]p19:
8351 // .... If the class definition does not explicitly declare a copy
8352 // assignment operator, there is no user-declared move constructor, and
8353 // there is no user-declared move assignment operator, a copy assignment
8354 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008355 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00008356 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008357
Richard Smithbc2a35d2012-12-08 08:32:28 +00008358 // Note that we have added this copy-assignment operator.
8359 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8360
8361 if (Scope *S = getScopeForContext(ClassDecl))
8362 PushOnScopeChains(CopyAssignment, S, false);
8363 ClassDecl->addDecl(CopyAssignment);
8364
Douglas Gregord3c35902010-07-01 16:36:15 +00008365 return CopyAssignment;
8366}
8367
Douglas Gregor06a9f362010-05-01 20:49:11 +00008368void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8369 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008370 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008371 CopyAssignOperator->isOverloadedOperator() &&
8372 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008373 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8374 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008375 "DefineImplicitCopyAssignment called for wrong function");
8376
8377 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8378
8379 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8380 CopyAssignOperator->setInvalidDecl();
8381 return;
8382 }
8383
8384 CopyAssignOperator->setUsed();
8385
Eli Friedman9a14db32012-10-18 20:14:08 +00008386 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008387 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008388
8389 // C++0x [class.copy]p30:
8390 // The implicitly-defined or explicitly-defaulted copy assignment operator
8391 // for a non-union class X performs memberwise copy assignment of its
8392 // subobjects. The direct base classes of X are assigned first, in the
8393 // order of their declaration in the base-specifier-list, and then the
8394 // immediate non-static data members of X are assigned, in the order in
8395 // which they were declared in the class definition.
8396
8397 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008398 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008399
8400 // The parameter for the "other" object, which we are copying from.
8401 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8402 Qualifiers OtherQuals = Other->getType().getQualifiers();
8403 QualType OtherRefType = Other->getType();
8404 if (const LValueReferenceType *OtherRef
8405 = OtherRefType->getAs<LValueReferenceType>()) {
8406 OtherRefType = OtherRef->getPointeeType();
8407 OtherQuals = OtherRefType.getQualifiers();
8408 }
8409
8410 // Our location for everything implicitly-generated.
8411 SourceLocation Loc = CopyAssignOperator->getLocation();
8412
8413 // Construct a reference to the "other" object. We'll be using this
8414 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008415 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008416 assert(OtherRef && "Reference to parameter cannot fail!");
8417
8418 // Construct the "this" pointer. We'll be using this throughout the generated
8419 // ASTs.
8420 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8421 assert(This && "Reference to this cannot fail!");
8422
8423 // Assign base classes.
8424 bool Invalid = false;
8425 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8426 E = ClassDecl->bases_end(); Base != E; ++Base) {
8427 // Form the assignment:
8428 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8429 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008430 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008431 Invalid = true;
8432 continue;
8433 }
8434
John McCallf871d0c2010-08-07 06:22:56 +00008435 CXXCastPath BasePath;
8436 BasePath.push_back(Base);
8437
Douglas Gregor06a9f362010-05-01 20:49:11 +00008438 // Construct the "from" expression, which is an implicit cast to the
8439 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008440 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008441 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8442 CK_UncheckedDerivedToBase,
8443 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008444
8445 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008446 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008447
8448 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008449 To = ImpCastExprToType(To.take(),
8450 Context.getCVRQualifiedType(BaseType,
8451 CopyAssignOperator->getTypeQualifiers()),
8452 CK_UncheckedDerivedToBase,
8453 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008454
8455 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008456 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008457 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008458 /*CopyingBaseSubobject=*/true,
8459 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008460 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008461 Diag(CurrentLocation, diag::note_member_synthesized_at)
8462 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8463 CopyAssignOperator->setInvalidDecl();
8464 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008465 }
8466
8467 // Success! Record the copy.
8468 Statements.push_back(Copy.takeAs<Expr>());
8469 }
8470
Douglas Gregor06a9f362010-05-01 20:49:11 +00008471 // Assign non-static members.
8472 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8473 FieldEnd = ClassDecl->field_end();
8474 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008475 if (Field->isUnnamedBitfield())
8476 continue;
8477
Douglas Gregor06a9f362010-05-01 20:49:11 +00008478 // Check for members of reference type; we can't copy those.
8479 if (Field->getType()->isReferenceType()) {
8480 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8481 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8482 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008483 Diag(CurrentLocation, diag::note_member_synthesized_at)
8484 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008485 Invalid = true;
8486 continue;
8487 }
8488
8489 // Check for members of const-qualified, non-class type.
8490 QualType BaseType = Context.getBaseElementType(Field->getType());
8491 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8492 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8493 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8494 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008495 Diag(CurrentLocation, diag::note_member_synthesized_at)
8496 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008497 Invalid = true;
8498 continue;
8499 }
John McCallb77115d2011-06-17 00:18:42 +00008500
8501 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008502 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8503 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008504
8505 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008506 if (FieldType->isIncompleteArrayType()) {
8507 assert(ClassDecl->hasFlexibleArrayMember() &&
8508 "Incomplete array type is not valid");
8509 continue;
8510 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008511
8512 // Build references to the field in the object we're copying from and to.
8513 CXXScopeSpec SS; // Intentionally empty
8514 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8515 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008516 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008517 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008518 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008519 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008520 SS, SourceLocation(), 0,
8521 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008522 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008523 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008524 SS, SourceLocation(), 0,
8525 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008526 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8527 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008528
Douglas Gregor06a9f362010-05-01 20:49:11 +00008529 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008530 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008531 To.get(), From.get(),
8532 /*CopyingBaseSubobject=*/false,
8533 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008534 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008535 Diag(CurrentLocation, diag::note_member_synthesized_at)
8536 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8537 CopyAssignOperator->setInvalidDecl();
8538 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008539 }
8540
8541 // Success! Record the copy.
8542 Statements.push_back(Copy.takeAs<Stmt>());
8543 }
8544
8545 if (!Invalid) {
8546 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008547 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008548
John McCall60d7b3a2010-08-24 06:29:42 +00008549 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008550 if (Return.isInvalid())
8551 Invalid = true;
8552 else {
8553 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008554
8555 if (Trap.hasErrorOccurred()) {
8556 Diag(CurrentLocation, diag::note_member_synthesized_at)
8557 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8558 Invalid = true;
8559 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008560 }
8561 }
8562
8563 if (Invalid) {
8564 CopyAssignOperator->setInvalidDecl();
8565 return;
8566 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008567
8568 StmtResult Body;
8569 {
8570 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008571 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008572 /*isStmtExpr=*/false);
8573 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8574 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008575 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008576
8577 if (ASTMutationListener *L = getASTMutationListener()) {
8578 L->CompletedImplicitDefinition(CopyAssignOperator);
8579 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008580}
8581
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008582Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008583Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8584 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008585
Richard Smithb9d0b762012-07-27 04:22:15 +00008586 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008587 if (ClassDecl->isInvalidDecl())
8588 return ExceptSpec;
8589
8590 // C++0x [except.spec]p14:
8591 // An implicitly declared special member function (Clause 12) shall have an
8592 // exception-specification. [...]
8593
8594 // It is unspecified whether or not an implicit move assignment operator
8595 // attempts to deduplicate calls to assignment operators of virtual bases are
8596 // made. As such, this exception specification is effectively unspecified.
8597 // Based on a similar decision made for constness in C++0x, we're erring on
8598 // the side of assuming such calls to be made regardless of whether they
8599 // actually happen.
8600 // Note that a move constructor is not implicitly declared when there are
8601 // virtual bases, but it can still be user-declared and explicitly defaulted.
8602 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8603 BaseEnd = ClassDecl->bases_end();
8604 Base != BaseEnd; ++Base) {
8605 if (Base->isVirtual())
8606 continue;
8607
8608 CXXRecordDecl *BaseClassDecl
8609 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8610 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008611 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008612 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008613 }
8614
8615 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8616 BaseEnd = ClassDecl->vbases_end();
8617 Base != BaseEnd; ++Base) {
8618 CXXRecordDecl *BaseClassDecl
8619 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8620 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008621 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008622 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008623 }
8624
8625 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8626 FieldEnd = ClassDecl->field_end();
8627 Field != FieldEnd;
8628 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008629 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008630 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008631 if (CXXMethodDecl *MoveAssign =
8632 LookupMovingAssignment(FieldClassDecl,
8633 FieldType.getCVRQualifiers(),
8634 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008635 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008636 }
8637 }
8638
8639 return ExceptSpec;
8640}
8641
Richard Smith1c931be2012-04-02 18:40:40 +00008642/// Determine whether the class type has any direct or indirect virtual base
8643/// classes which have a non-trivial move assignment operator.
8644static bool
8645hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8646 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8647 BaseEnd = ClassDecl->vbases_end();
8648 Base != BaseEnd; ++Base) {
8649 CXXRecordDecl *BaseClass =
8650 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8651
8652 // Try to declare the move assignment. If it would be deleted, then the
8653 // class does not have a non-trivial move assignment.
8654 if (BaseClass->needsImplicitMoveAssignment())
8655 S.DeclareImplicitMoveAssignment(BaseClass);
8656
Richard Smith426391c2012-11-16 00:53:38 +00008657 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008658 return true;
8659 }
8660
8661 return false;
8662}
8663
8664/// Determine whether the given type either has a move constructor or is
8665/// trivially copyable.
8666static bool
8667hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8668 Type = S.Context.getBaseElementType(Type);
8669
8670 // FIXME: Technically, non-trivially-copyable non-class types, such as
8671 // reference types, are supposed to return false here, but that appears
8672 // to be a standard defect.
8673 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008674 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008675 return true;
8676
8677 if (Type.isTriviallyCopyableType(S.Context))
8678 return true;
8679
8680 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008681 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8682 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008683 if (ClassDecl->needsImplicitMoveConstructor())
8684 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008685 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008686 }
8687
Richard Smithe5411b72012-12-01 02:35:44 +00008688 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8689 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008690 if (ClassDecl->needsImplicitMoveAssignment())
8691 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008692 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008693}
8694
8695/// Determine whether all non-static data members and direct or virtual bases
8696/// of class \p ClassDecl have either a move operation, or are trivially
8697/// copyable.
8698static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8699 bool IsConstructor) {
8700 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8701 BaseEnd = ClassDecl->bases_end();
8702 Base != BaseEnd; ++Base) {
8703 if (Base->isVirtual())
8704 continue;
8705
8706 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8707 return false;
8708 }
8709
8710 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8711 BaseEnd = ClassDecl->vbases_end();
8712 Base != BaseEnd; ++Base) {
8713 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8714 return false;
8715 }
8716
8717 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8718 FieldEnd = ClassDecl->field_end();
8719 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008720 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008721 return false;
8722 }
8723
8724 return true;
8725}
8726
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008727CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008728 // C++11 [class.copy]p20:
8729 // If the definition of a class X does not explicitly declare a move
8730 // assignment operator, one will be implicitly declared as defaulted
8731 // if and only if:
8732 //
8733 // - [first 4 bullets]
8734 assert(ClassDecl->needsImplicitMoveAssignment());
8735
Richard Smithafb49182012-11-29 01:34:07 +00008736 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8737 if (DSM.isAlreadyBeingDeclared())
8738 return 0;
8739
Richard Smith1c931be2012-04-02 18:40:40 +00008740 // [Checked after we build the declaration]
8741 // - the move assignment operator would not be implicitly defined as
8742 // deleted,
8743
8744 // [DR1402]:
8745 // - X has no direct or indirect virtual base class with a non-trivial
8746 // move assignment operator, and
8747 // - each of X's non-static data members and direct or virtual base classes
8748 // has a type that either has a move assignment operator or is trivially
8749 // copyable.
8750 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8751 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8752 ClassDecl->setFailedImplicitMoveAssignment();
8753 return 0;
8754 }
8755
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008756 // Note: The following rules are largely analoguous to the move
8757 // constructor rules.
8758
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008759 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8760 QualType RetType = Context.getLValueReferenceType(ArgType);
8761 ArgType = Context.getRValueReferenceType(ArgType);
8762
8763 // An implicitly-declared move assignment operator is an inline public
8764 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008765 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8766 SourceLocation ClassLoc = ClassDecl->getLocation();
8767 DeclarationNameInfo NameInfo(Name, ClassLoc);
8768 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008769 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008770 /*TInfo=*/0, /*isStatic=*/false,
8771 /*StorageClassAsWritten=*/SC_None,
8772 /*isInline=*/true,
8773 /*isConstexpr=*/false,
8774 SourceLocation());
8775 MoveAssignment->setAccess(AS_public);
8776 MoveAssignment->setDefaulted();
8777 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008778
Richard Smithb9d0b762012-07-27 04:22:15 +00008779 // Build an exception specification pointing back at this member.
8780 FunctionProtoType::ExtProtoInfo EPI;
8781 EPI.ExceptionSpecType = EST_Unevaluated;
8782 EPI.ExceptionSpecDecl = MoveAssignment;
8783 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8784
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008785 // Add the parameter to the operator.
8786 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8787 ClassLoc, ClassLoc, /*Id=*/0,
8788 ArgType, /*TInfo=*/0,
8789 SC_None,
8790 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008791 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008792
Richard Smithbc2a35d2012-12-08 08:32:28 +00008793 AddOverriddenMethods(ClassDecl, MoveAssignment);
8794
8795 MoveAssignment->setTrivial(
8796 ClassDecl->needsOverloadResolutionForMoveAssignment()
8797 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8798 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008799
8800 // C++0x [class.copy]p9:
8801 // If the definition of a class X does not explicitly declare a move
8802 // assignment operator, one will be implicitly declared as defaulted if and
8803 // only if:
8804 // [...]
8805 // - the move assignment operator would not be implicitly defined as
8806 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008807 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008808 // Cache this result so that we don't try to generate this over and over
8809 // on every lookup, leaking memory and wasting time.
8810 ClassDecl->setFailedImplicitMoveAssignment();
8811 return 0;
8812 }
8813
Richard Smithbc2a35d2012-12-08 08:32:28 +00008814 // Note that we have added this copy-assignment operator.
8815 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8816
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008817 if (Scope *S = getScopeForContext(ClassDecl))
8818 PushOnScopeChains(MoveAssignment, S, false);
8819 ClassDecl->addDecl(MoveAssignment);
8820
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008821 return MoveAssignment;
8822}
8823
8824void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8825 CXXMethodDecl *MoveAssignOperator) {
8826 assert((MoveAssignOperator->isDefaulted() &&
8827 MoveAssignOperator->isOverloadedOperator() &&
8828 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008829 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8830 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008831 "DefineImplicitMoveAssignment called for wrong function");
8832
8833 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8834
8835 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8836 MoveAssignOperator->setInvalidDecl();
8837 return;
8838 }
8839
8840 MoveAssignOperator->setUsed();
8841
Eli Friedman9a14db32012-10-18 20:14:08 +00008842 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008843 DiagnosticErrorTrap Trap(Diags);
8844
8845 // C++0x [class.copy]p28:
8846 // The implicitly-defined or move assignment operator for a non-union class
8847 // X performs memberwise move assignment of its subobjects. The direct base
8848 // classes of X are assigned first, in the order of their declaration in the
8849 // base-specifier-list, and then the immediate non-static data members of X
8850 // are assigned, in the order in which they were declared in the class
8851 // definition.
8852
8853 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008854 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008855
8856 // The parameter for the "other" object, which we are move from.
8857 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8858 QualType OtherRefType = Other->getType()->
8859 getAs<RValueReferenceType>()->getPointeeType();
8860 assert(OtherRefType.getQualifiers() == 0 &&
8861 "Bad argument type of defaulted move assignment");
8862
8863 // Our location for everything implicitly-generated.
8864 SourceLocation Loc = MoveAssignOperator->getLocation();
8865
8866 // Construct a reference to the "other" object. We'll be using this
8867 // throughout the generated ASTs.
8868 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8869 assert(OtherRef && "Reference to parameter cannot fail!");
8870 // Cast to rvalue.
8871 OtherRef = CastForMoving(*this, OtherRef);
8872
8873 // Construct the "this" pointer. We'll be using this throughout the generated
8874 // ASTs.
8875 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8876 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008877
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008878 // Assign base classes.
8879 bool Invalid = false;
8880 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8881 E = ClassDecl->bases_end(); Base != E; ++Base) {
8882 // Form the assignment:
8883 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8884 QualType BaseType = Base->getType().getUnqualifiedType();
8885 if (!BaseType->isRecordType()) {
8886 Invalid = true;
8887 continue;
8888 }
8889
8890 CXXCastPath BasePath;
8891 BasePath.push_back(Base);
8892
8893 // Construct the "from" expression, which is an implicit cast to the
8894 // appropriately-qualified base type.
8895 Expr *From = OtherRef;
8896 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008897 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008898
8899 // Dereference "this".
8900 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8901
8902 // Implicitly cast "this" to the appropriately-qualified base type.
8903 To = ImpCastExprToType(To.take(),
8904 Context.getCVRQualifiedType(BaseType,
8905 MoveAssignOperator->getTypeQualifiers()),
8906 CK_UncheckedDerivedToBase,
8907 VK_LValue, &BasePath);
8908
8909 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00008910 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008911 To.get(), From,
8912 /*CopyingBaseSubobject=*/true,
8913 /*Copying=*/false);
8914 if (Move.isInvalid()) {
8915 Diag(CurrentLocation, diag::note_member_synthesized_at)
8916 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8917 MoveAssignOperator->setInvalidDecl();
8918 return;
8919 }
8920
8921 // Success! Record the move.
8922 Statements.push_back(Move.takeAs<Expr>());
8923 }
8924
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008925 // Assign non-static members.
8926 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8927 FieldEnd = ClassDecl->field_end();
8928 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008929 if (Field->isUnnamedBitfield())
8930 continue;
8931
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008932 // Check for members of reference type; we can't move those.
8933 if (Field->getType()->isReferenceType()) {
8934 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8935 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8936 Diag(Field->getLocation(), diag::note_declared_at);
8937 Diag(CurrentLocation, diag::note_member_synthesized_at)
8938 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8939 Invalid = true;
8940 continue;
8941 }
8942
8943 // Check for members of const-qualified, non-class type.
8944 QualType BaseType = Context.getBaseElementType(Field->getType());
8945 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8946 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8947 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8948 Diag(Field->getLocation(), diag::note_declared_at);
8949 Diag(CurrentLocation, diag::note_member_synthesized_at)
8950 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8951 Invalid = true;
8952 continue;
8953 }
8954
8955 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008956 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8957 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008958
8959 QualType FieldType = Field->getType().getNonReferenceType();
8960 if (FieldType->isIncompleteArrayType()) {
8961 assert(ClassDecl->hasFlexibleArrayMember() &&
8962 "Incomplete array type is not valid");
8963 continue;
8964 }
8965
8966 // Build references to the field in the object we're copying from and to.
8967 CXXScopeSpec SS; // Intentionally empty
8968 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8969 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008970 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008971 MemberLookup.resolveKind();
8972 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8973 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008974 SS, SourceLocation(), 0,
8975 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008976 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8977 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008978 SS, SourceLocation(), 0,
8979 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008980 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8981 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8982
8983 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8984 "Member reference with rvalue base must be rvalue except for reference "
8985 "members, which aren't allowed for move assignment.");
8986
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008987 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008988 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008989 To.get(), From.get(),
8990 /*CopyingBaseSubobject=*/false,
8991 /*Copying=*/false);
8992 if (Move.isInvalid()) {
8993 Diag(CurrentLocation, diag::note_member_synthesized_at)
8994 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8995 MoveAssignOperator->setInvalidDecl();
8996 return;
8997 }
Richard Smithe7ce7092012-11-12 23:33:00 +00008998
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008999 // Success! Record the copy.
9000 Statements.push_back(Move.takeAs<Stmt>());
9001 }
9002
9003 if (!Invalid) {
9004 // Add a "return *this;"
9005 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9006
9007 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9008 if (Return.isInvalid())
9009 Invalid = true;
9010 else {
9011 Statements.push_back(Return.takeAs<Stmt>());
9012
9013 if (Trap.hasErrorOccurred()) {
9014 Diag(CurrentLocation, diag::note_member_synthesized_at)
9015 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9016 Invalid = true;
9017 }
9018 }
9019 }
9020
9021 if (Invalid) {
9022 MoveAssignOperator->setInvalidDecl();
9023 return;
9024 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009025
9026 StmtResult Body;
9027 {
9028 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009029 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009030 /*isStmtExpr=*/false);
9031 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9032 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009033 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9034
9035 if (ASTMutationListener *L = getASTMutationListener()) {
9036 L->CompletedImplicitDefinition(MoveAssignOperator);
9037 }
9038}
9039
Richard Smithb9d0b762012-07-27 04:22:15 +00009040Sema::ImplicitExceptionSpecification
9041Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9042 CXXRecordDecl *ClassDecl = MD->getParent();
9043
9044 ImplicitExceptionSpecification ExceptSpec(*this);
9045 if (ClassDecl->isInvalidDecl())
9046 return ExceptSpec;
9047
9048 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9049 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9050 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9051
Douglas Gregor0d405db2010-07-01 20:59:04 +00009052 // C++ [except.spec]p14:
9053 // An implicitly declared special member function (Clause 12) shall have an
9054 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009055 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9056 BaseEnd = ClassDecl->bases_end();
9057 Base != BaseEnd;
9058 ++Base) {
9059 // Virtual bases are handled below.
9060 if (Base->isVirtual())
9061 continue;
9062
Douglas Gregor22584312010-07-02 23:41:54 +00009063 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009064 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009065 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009066 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009067 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009068 }
9069 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9070 BaseEnd = ClassDecl->vbases_end();
9071 Base != BaseEnd;
9072 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009073 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009074 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009075 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009076 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009077 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009078 }
9079 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9080 FieldEnd = ClassDecl->field_end();
9081 Field != FieldEnd;
9082 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009083 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009084 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9085 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009086 LookupCopyingConstructor(FieldClassDecl,
9087 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009088 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009089 }
9090 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009091
Richard Smithb9d0b762012-07-27 04:22:15 +00009092 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009093}
9094
9095CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9096 CXXRecordDecl *ClassDecl) {
9097 // C++ [class.copy]p4:
9098 // If the class definition does not explicitly declare a copy
9099 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009100 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009101
Richard Smithafb49182012-11-29 01:34:07 +00009102 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9103 if (DSM.isAlreadyBeingDeclared())
9104 return 0;
9105
Sean Hunt49634cf2011-05-13 06:10:58 +00009106 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9107 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009108 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009109 if (Const)
9110 ArgType = ArgType.withConst();
9111 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009112
Richard Smith7756afa2012-06-10 05:43:50 +00009113 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9114 CXXCopyConstructor,
9115 Const);
9116
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009117 DeclarationName Name
9118 = Context.DeclarationNames.getCXXConstructorName(
9119 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009120 SourceLocation ClassLoc = ClassDecl->getLocation();
9121 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009122
9123 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009124 // member of its class.
9125 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009126 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009127 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009128 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009129 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009130 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009131
Richard Smithb9d0b762012-07-27 04:22:15 +00009132 // Build an exception specification pointing back at this member.
9133 FunctionProtoType::ExtProtoInfo EPI;
9134 EPI.ExceptionSpecType = EST_Unevaluated;
9135 EPI.ExceptionSpecDecl = CopyConstructor;
9136 CopyConstructor->setType(
9137 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9138
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009139 // Add the parameter to the constructor.
9140 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009141 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009142 /*IdentifierInfo=*/0,
9143 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009144 SC_None,
9145 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009146 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009147
Richard Smithbc2a35d2012-12-08 08:32:28 +00009148 CopyConstructor->setTrivial(
9149 ClassDecl->needsOverloadResolutionForCopyConstructor()
9150 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9151 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009152
Nico Weberafcc96a2012-01-23 03:19:29 +00009153 // C++11 [class.copy]p8:
9154 // ... If the class definition does not explicitly declare a copy
9155 // constructor, there is no user-declared move constructor, and there is no
9156 // user-declared move assignment operator, a copy constructor is implicitly
9157 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009158 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00009159 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00009160
Richard Smithbc2a35d2012-12-08 08:32:28 +00009161 // Note that we have declared this constructor.
9162 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9163
9164 if (Scope *S = getScopeForContext(ClassDecl))
9165 PushOnScopeChains(CopyConstructor, S, false);
9166 ClassDecl->addDecl(CopyConstructor);
9167
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009168 return CopyConstructor;
9169}
9170
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009171void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009172 CXXConstructorDecl *CopyConstructor) {
9173 assert((CopyConstructor->isDefaulted() &&
9174 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009175 !CopyConstructor->doesThisDeclarationHaveABody() &&
9176 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009177 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009178
Anders Carlsson63010a72010-04-23 16:24:12 +00009179 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009180 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009181
Eli Friedman9a14db32012-10-18 20:14:08 +00009182 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009183 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009184
David Blaikie93c86172013-01-17 05:26:25 +00009185 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009186 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009187 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009188 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009189 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009190 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009191 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009192 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9193 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009194 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009195 /*isStmtExpr=*/false)
9196 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009197 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009198 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009199
9200 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009201 if (ASTMutationListener *L = getASTMutationListener()) {
9202 L->CompletedImplicitDefinition(CopyConstructor);
9203 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009204}
9205
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009206Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009207Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9208 CXXRecordDecl *ClassDecl = MD->getParent();
9209
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009210 // C++ [except.spec]p14:
9211 // An implicitly declared special member function (Clause 12) shall have an
9212 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009213 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009214 if (ClassDecl->isInvalidDecl())
9215 return ExceptSpec;
9216
9217 // Direct base-class constructors.
9218 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9219 BEnd = ClassDecl->bases_end();
9220 B != BEnd; ++B) {
9221 if (B->isVirtual()) // Handled below.
9222 continue;
9223
9224 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9225 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009226 CXXConstructorDecl *Constructor =
9227 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009228 // If this is a deleted function, add it anyway. This might be conformant
9229 // with the standard. This might not. I'm not sure. It might not matter.
9230 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009231 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009232 }
9233 }
9234
9235 // Virtual base-class constructors.
9236 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9237 BEnd = ClassDecl->vbases_end();
9238 B != BEnd; ++B) {
9239 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9240 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009241 CXXConstructorDecl *Constructor =
9242 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009243 // If this is a deleted function, add it anyway. This might be conformant
9244 // with the standard. This might not. I'm not sure. It might not matter.
9245 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009246 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009247 }
9248 }
9249
9250 // Field constructors.
9251 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9252 FEnd = ClassDecl->field_end();
9253 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009254 QualType FieldType = Context.getBaseElementType(F->getType());
9255 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9256 CXXConstructorDecl *Constructor =
9257 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009258 // If this is a deleted function, add it anyway. This might be conformant
9259 // with the standard. This might not. I'm not sure. It might not matter.
9260 // In particular, the problem is that this function never gets called. It
9261 // might just be ill-formed because this function attempts to refer to
9262 // a deleted function here.
9263 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009264 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009265 }
9266 }
9267
9268 return ExceptSpec;
9269}
9270
9271CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9272 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009273 // C++11 [class.copy]p9:
9274 // If the definition of a class X does not explicitly declare a move
9275 // constructor, one will be implicitly declared as defaulted if and only if:
9276 //
9277 // - [first 4 bullets]
9278 assert(ClassDecl->needsImplicitMoveConstructor());
9279
Richard Smithafb49182012-11-29 01:34:07 +00009280 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9281 if (DSM.isAlreadyBeingDeclared())
9282 return 0;
9283
Richard Smith1c931be2012-04-02 18:40:40 +00009284 // [Checked after we build the declaration]
9285 // - the move assignment operator would not be implicitly defined as
9286 // deleted,
9287
9288 // [DR1402]:
9289 // - each of X's non-static data members and direct or virtual base classes
9290 // has a type that either has a move constructor or is trivially copyable.
9291 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9292 ClassDecl->setFailedImplicitMoveConstructor();
9293 return 0;
9294 }
9295
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009296 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9297 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009298
Richard Smith7756afa2012-06-10 05:43:50 +00009299 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9300 CXXMoveConstructor,
9301 false);
9302
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009303 DeclarationName Name
9304 = Context.DeclarationNames.getCXXConstructorName(
9305 Context.getCanonicalType(ClassType));
9306 SourceLocation ClassLoc = ClassDecl->getLocation();
9307 DeclarationNameInfo NameInfo(Name, ClassLoc);
9308
9309 // C++0x [class.copy]p11:
9310 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009311 // member of its class.
9312 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009313 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009314 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009315 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009316 MoveConstructor->setAccess(AS_public);
9317 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009318
Richard Smithb9d0b762012-07-27 04:22:15 +00009319 // Build an exception specification pointing back at this member.
9320 FunctionProtoType::ExtProtoInfo EPI;
9321 EPI.ExceptionSpecType = EST_Unevaluated;
9322 EPI.ExceptionSpecDecl = MoveConstructor;
9323 MoveConstructor->setType(
9324 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9325
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009326 // Add the parameter to the constructor.
9327 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9328 ClassLoc, ClassLoc,
9329 /*IdentifierInfo=*/0,
9330 ArgType, /*TInfo=*/0,
9331 SC_None,
9332 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009333 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009334
Richard Smithbc2a35d2012-12-08 08:32:28 +00009335 MoveConstructor->setTrivial(
9336 ClassDecl->needsOverloadResolutionForMoveConstructor()
9337 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9338 : ClassDecl->hasTrivialMoveConstructor());
9339
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009340 // C++0x [class.copy]p9:
9341 // If the definition of a class X does not explicitly declare a move
9342 // constructor, one will be implicitly declared as defaulted if and only if:
9343 // [...]
9344 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009345 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009346 // Cache this result so that we don't try to generate this over and over
9347 // on every lookup, leaking memory and wasting time.
9348 ClassDecl->setFailedImplicitMoveConstructor();
9349 return 0;
9350 }
9351
9352 // Note that we have declared this constructor.
9353 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9354
9355 if (Scope *S = getScopeForContext(ClassDecl))
9356 PushOnScopeChains(MoveConstructor, S, false);
9357 ClassDecl->addDecl(MoveConstructor);
9358
9359 return MoveConstructor;
9360}
9361
9362void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9363 CXXConstructorDecl *MoveConstructor) {
9364 assert((MoveConstructor->isDefaulted() &&
9365 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009366 !MoveConstructor->doesThisDeclarationHaveABody() &&
9367 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009368 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9369
9370 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9371 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9372
Eli Friedman9a14db32012-10-18 20:14:08 +00009373 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009374 DiagnosticErrorTrap Trap(Diags);
9375
David Blaikie93c86172013-01-17 05:26:25 +00009376 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009377 Trap.hasErrorOccurred()) {
9378 Diag(CurrentLocation, diag::note_member_synthesized_at)
9379 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9380 MoveConstructor->setInvalidDecl();
9381 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009382 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009383 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9384 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009385 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009386 /*isStmtExpr=*/false)
9387 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009388 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009389 }
9390
9391 MoveConstructor->setUsed();
9392
9393 if (ASTMutationListener *L = getASTMutationListener()) {
9394 L->CompletedImplicitDefinition(MoveConstructor);
9395 }
9396}
9397
Douglas Gregore4e68d42012-02-15 19:33:52 +00009398bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9399 return FD->isDeleted() &&
9400 (FD->isDefaulted() || FD->isImplicit()) &&
9401 isa<CXXMethodDecl>(FD);
9402}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009403
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009404/// \brief Mark the call operator of the given lambda closure type as "used".
9405static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9406 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009407 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009408 Lambda->lookup(
9409 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009410 CallOperator->setReferenced();
9411 CallOperator->setUsed();
9412}
9413
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009414void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9415 SourceLocation CurrentLocation,
9416 CXXConversionDecl *Conv)
9417{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009418 CXXRecordDecl *Lambda = Conv->getParent();
9419
9420 // Make sure that the lambda call operator is marked used.
9421 markLambdaCallOperatorUsed(*this, Lambda);
9422
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009423 Conv->setUsed();
9424
Eli Friedman9a14db32012-10-18 20:14:08 +00009425 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009426 DiagnosticErrorTrap Trap(Diags);
9427
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009428 // Return the address of the __invoke function.
9429 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9430 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009431 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009432 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9433 VK_LValue, Conv->getLocation()).take();
9434 assert(FunctionRef && "Can't refer to __invoke function?");
9435 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009436 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009437 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009438 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009439
9440 // Fill in the __invoke function with a dummy implementation. IR generation
9441 // will fill in the actual details.
9442 Invoke->setUsed();
9443 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009444 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009445
9446 if (ASTMutationListener *L = getASTMutationListener()) {
9447 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009448 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009449 }
9450}
9451
9452void Sema::DefineImplicitLambdaToBlockPointerConversion(
9453 SourceLocation CurrentLocation,
9454 CXXConversionDecl *Conv)
9455{
9456 Conv->setUsed();
9457
Eli Friedman9a14db32012-10-18 20:14:08 +00009458 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009459 DiagnosticErrorTrap Trap(Diags);
9460
Douglas Gregorac1303e2012-02-22 05:02:47 +00009461 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009462 Expr *This = ActOnCXXThis(CurrentLocation).take();
9463 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009464
Eli Friedman23f02672012-03-01 04:01:32 +00009465 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9466 Conv->getLocation(),
9467 Conv, DerefThis);
9468
9469 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9470 // behavior. Note that only the general conversion function does this
9471 // (since it's unusable otherwise); in the case where we inline the
9472 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009473 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009474 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9475 CK_CopyAndAutoreleaseBlockObject,
9476 BuildBlock.get(), 0, VK_RValue);
9477
9478 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009479 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009480 Conv->setInvalidDecl();
9481 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009482 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009483
Douglas Gregorac1303e2012-02-22 05:02:47 +00009484 // Create the return statement that returns the block from the conversion
9485 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009486 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009487 if (Return.isInvalid()) {
9488 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9489 Conv->setInvalidDecl();
9490 return;
9491 }
9492
9493 // Set the body of the conversion function.
9494 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009495 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009496 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009497 Conv->getLocation()));
9498
Douglas Gregorac1303e2012-02-22 05:02:47 +00009499 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009500 if (ASTMutationListener *L = getASTMutationListener()) {
9501 L->CompletedImplicitDefinition(Conv);
9502 }
9503}
9504
Douglas Gregorf52757d2012-03-10 06:53:13 +00009505/// \brief Determine whether the given list arguments contains exactly one
9506/// "real" (non-default) argument.
9507static bool hasOneRealArgument(MultiExprArg Args) {
9508 switch (Args.size()) {
9509 case 0:
9510 return false;
9511
9512 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009513 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009514 return false;
9515
9516 // fall through
9517 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009518 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009519 }
9520
9521 return false;
9522}
9523
John McCall60d7b3a2010-08-24 06:29:42 +00009524ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009525Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009526 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009527 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009528 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009529 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009530 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009531 unsigned ConstructKind,
9532 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009533 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009534
Douglas Gregor2f599792010-04-02 18:24:57 +00009535 // C++0x [class.copy]p34:
9536 // When certain criteria are met, an implementation is allowed to
9537 // omit the copy/move construction of a class object, even if the
9538 // copy/move constructor and/or destructor for the object have
9539 // side effects. [...]
9540 // - when a temporary class object that has not been bound to a
9541 // reference (12.2) would be copied/moved to a class object
9542 // with the same cv-unqualified type, the copy/move operation
9543 // can be omitted by constructing the temporary object
9544 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009545 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009546 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009547 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009548 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009549 }
Mike Stump1eb44332009-09-09 15:08:12 +00009550
9551 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009552 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009553 IsListInitialization, RequiresZeroInit,
9554 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009555}
9556
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009557/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9558/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009559ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009560Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9561 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009562 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009563 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009564 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009565 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009566 unsigned ConstructKind,
9567 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009568 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009569 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009570 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +00009571 HadMultipleCandidates,
9572 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009573 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9574 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009575}
9576
John McCall68c6c9a2010-02-02 09:10:11 +00009577void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009578 if (VD->isInvalidDecl()) return;
9579
John McCall68c6c9a2010-02-02 09:10:11 +00009580 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009581 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009582 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009583 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009584
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009585 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009586 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009587 CheckDestructorAccess(VD->getLocation(), Destructor,
9588 PDiag(diag::err_access_dtor_var)
9589 << VD->getDeclName()
9590 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009591 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009592
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009593 if (!VD->hasGlobalStorage()) return;
9594
9595 // Emit warning for non-trivial dtor in global scope (a real global,
9596 // class-static, function-static).
9597 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9598
9599 // TODO: this should be re-enabled for static locals by !CXAAtExit
9600 if (!VD->isStaticLocal())
9601 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009602}
9603
Douglas Gregor39da0b82009-09-09 23:08:42 +00009604/// \brief Given a constructor and the set of arguments provided for the
9605/// constructor, convert the arguments and add any required default arguments
9606/// to form a proper call to this constructor.
9607///
9608/// \returns true if an error occurred, false otherwise.
9609bool
9610Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9611 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009612 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009613 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009614 bool AllowExplicit,
9615 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009616 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9617 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009618 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009619
9620 const FunctionProtoType *Proto
9621 = Constructor->getType()->getAs<FunctionProtoType>();
9622 assert(Proto && "Constructor without a prototype?");
9623 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009624
9625 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009626 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009627 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009628 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009629 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009630
9631 VariadicCallType CallType =
9632 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009633 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009634 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9635 Proto, 0, Args, NumArgs, AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009636 CallType, AllowExplicit,
9637 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009638 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009639
9640 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9641
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00009642 CheckConstructorCall(Constructor,
9643 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9644 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +00009645 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009646
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009647 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009648}
9649
Anders Carlsson20d45d22009-12-12 00:32:00 +00009650static inline bool
9651CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9652 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009653 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009654 if (isa<NamespaceDecl>(DC)) {
9655 return SemaRef.Diag(FnDecl->getLocation(),
9656 diag::err_operator_new_delete_declared_in_namespace)
9657 << FnDecl->getDeclName();
9658 }
9659
9660 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009661 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009662 return SemaRef.Diag(FnDecl->getLocation(),
9663 diag::err_operator_new_delete_declared_static)
9664 << FnDecl->getDeclName();
9665 }
9666
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009667 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009668}
9669
Anders Carlsson156c78e2009-12-13 17:53:43 +00009670static inline bool
9671CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9672 CanQualType ExpectedResultType,
9673 CanQualType ExpectedFirstParamType,
9674 unsigned DependentParamTypeDiag,
9675 unsigned InvalidParamTypeDiag) {
9676 QualType ResultType =
9677 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9678
9679 // Check that the result type is not dependent.
9680 if (ResultType->isDependentType())
9681 return SemaRef.Diag(FnDecl->getLocation(),
9682 diag::err_operator_new_delete_dependent_result_type)
9683 << FnDecl->getDeclName() << ExpectedResultType;
9684
9685 // Check that the result type is what we expect.
9686 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9687 return SemaRef.Diag(FnDecl->getLocation(),
9688 diag::err_operator_new_delete_invalid_result_type)
9689 << FnDecl->getDeclName() << ExpectedResultType;
9690
9691 // A function template must have at least 2 parameters.
9692 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9693 return SemaRef.Diag(FnDecl->getLocation(),
9694 diag::err_operator_new_delete_template_too_few_parameters)
9695 << FnDecl->getDeclName();
9696
9697 // The function decl must have at least 1 parameter.
9698 if (FnDecl->getNumParams() == 0)
9699 return SemaRef.Diag(FnDecl->getLocation(),
9700 diag::err_operator_new_delete_too_few_parameters)
9701 << FnDecl->getDeclName();
9702
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009703 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009704 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9705 if (FirstParamType->isDependentType())
9706 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9707 << FnDecl->getDeclName() << ExpectedFirstParamType;
9708
9709 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009710 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009711 ExpectedFirstParamType)
9712 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9713 << FnDecl->getDeclName() << ExpectedFirstParamType;
9714
9715 return false;
9716}
9717
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009718static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009719CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009720 // C++ [basic.stc.dynamic.allocation]p1:
9721 // A program is ill-formed if an allocation function is declared in a
9722 // namespace scope other than global scope or declared static in global
9723 // scope.
9724 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9725 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009726
9727 CanQualType SizeTy =
9728 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9729
9730 // C++ [basic.stc.dynamic.allocation]p1:
9731 // The return type shall be void*. The first parameter shall have type
9732 // std::size_t.
9733 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9734 SizeTy,
9735 diag::err_operator_new_dependent_param_type,
9736 diag::err_operator_new_param_type))
9737 return true;
9738
9739 // C++ [basic.stc.dynamic.allocation]p1:
9740 // The first parameter shall not have an associated default argument.
9741 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009742 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009743 diag::err_operator_new_default_arg)
9744 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9745
9746 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009747}
9748
9749static bool
Richard Smith444d3842012-10-20 08:26:51 +00009750CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009751 // C++ [basic.stc.dynamic.deallocation]p1:
9752 // A program is ill-formed if deallocation functions are declared in a
9753 // namespace scope other than global scope or declared static in global
9754 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009755 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9756 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009757
9758 // C++ [basic.stc.dynamic.deallocation]p2:
9759 // Each deallocation function shall return void and its first parameter
9760 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009761 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9762 SemaRef.Context.VoidPtrTy,
9763 diag::err_operator_delete_dependent_param_type,
9764 diag::err_operator_delete_param_type))
9765 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009766
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009767 return false;
9768}
9769
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009770/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9771/// of this overloaded operator is well-formed. If so, returns false;
9772/// otherwise, emits appropriate diagnostics and returns true.
9773bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009774 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009775 "Expected an overloaded operator declaration");
9776
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009777 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9778
Mike Stump1eb44332009-09-09 15:08:12 +00009779 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009780 // The allocation and deallocation functions, operator new,
9781 // operator new[], operator delete and operator delete[], are
9782 // described completely in 3.7.3. The attributes and restrictions
9783 // found in the rest of this subclause do not apply to them unless
9784 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009785 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009786 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009787
Anders Carlssona3ccda52009-12-12 00:26:23 +00009788 if (Op == OO_New || Op == OO_Array_New)
9789 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009790
9791 // C++ [over.oper]p6:
9792 // An operator function shall either be a non-static member
9793 // function or be a non-member function and have at least one
9794 // parameter whose type is a class, a reference to a class, an
9795 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009796 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9797 if (MethodDecl->isStatic())
9798 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009799 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009800 } else {
9801 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009802 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9803 ParamEnd = FnDecl->param_end();
9804 Param != ParamEnd; ++Param) {
9805 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009806 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9807 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009808 ClassOrEnumParam = true;
9809 break;
9810 }
9811 }
9812
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009813 if (!ClassOrEnumParam)
9814 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009815 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009816 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009817 }
9818
9819 // C++ [over.oper]p8:
9820 // An operator function cannot have default arguments (8.3.6),
9821 // except where explicitly stated below.
9822 //
Mike Stump1eb44332009-09-09 15:08:12 +00009823 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009824 // (C++ [over.call]p1).
9825 if (Op != OO_Call) {
9826 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9827 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009828 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009829 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009830 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009831 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009832 }
9833 }
9834
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009835 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9836 { false, false, false }
9837#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9838 , { Unary, Binary, MemberOnly }
9839#include "clang/Basic/OperatorKinds.def"
9840 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009841
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009842 bool CanBeUnaryOperator = OperatorUses[Op][0];
9843 bool CanBeBinaryOperator = OperatorUses[Op][1];
9844 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009845
9846 // C++ [over.oper]p8:
9847 // [...] Operator functions cannot have more or fewer parameters
9848 // than the number required for the corresponding operator, as
9849 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009850 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009851 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009852 if (Op != OO_Call &&
9853 ((NumParams == 1 && !CanBeUnaryOperator) ||
9854 (NumParams == 2 && !CanBeBinaryOperator) ||
9855 (NumParams < 1) || (NumParams > 2))) {
9856 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009857 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009858 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009859 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009860 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009861 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009862 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009863 assert(CanBeBinaryOperator &&
9864 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009865 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009866 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009867
Chris Lattner416e46f2008-11-21 07:57:12 +00009868 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009869 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009870 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009871
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009872 // Overloaded operators other than operator() cannot be variadic.
9873 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009874 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009875 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009876 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009877 }
9878
9879 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009880 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9881 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009882 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009883 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009884 }
9885
9886 // C++ [over.inc]p1:
9887 // The user-defined function called operator++ implements the
9888 // prefix and postfix ++ operator. If this function is a member
9889 // function with no parameters, or a non-member function with one
9890 // parameter of class or enumeration type, it defines the prefix
9891 // increment operator ++ for objects of that type. If the function
9892 // is a member function with one parameter (which shall be of type
9893 // int) or a non-member function with two parameters (the second
9894 // of which shall be of type int), it defines the postfix
9895 // increment operator ++ for objects of that type.
9896 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9897 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9898 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009899 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009900 ParamIsInt = BT->getKind() == BuiltinType::Int;
9901
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009902 if (!ParamIsInt)
9903 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009904 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009905 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009906 }
9907
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009908 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009909}
Chris Lattner5a003a42008-12-17 07:09:26 +00009910
Sean Hunta6c058d2010-01-13 09:01:02 +00009911/// CheckLiteralOperatorDeclaration - Check whether the declaration
9912/// of this literal operator function is well-formed. If so, returns
9913/// false; otherwise, emits appropriate diagnostics and returns true.
9914bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009915 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009916 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9917 << FnDecl->getDeclName();
9918 return true;
9919 }
9920
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009921 if (FnDecl->isExternC()) {
9922 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9923 return true;
9924 }
9925
Sean Hunta6c058d2010-01-13 09:01:02 +00009926 bool Valid = false;
9927
Richard Smith36f5cfe2012-03-09 08:00:36 +00009928 // This might be the definition of a literal operator template.
9929 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9930 // This might be a specialization of a literal operator template.
9931 if (!TpDecl)
9932 TpDecl = FnDecl->getPrimaryTemplate();
9933
Sean Hunt216c2782010-04-07 23:11:06 +00009934 // template <char...> type operator "" name() is the only valid template
9935 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009936 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009937 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009938 // Must have only one template parameter
9939 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9940 if (Params->size() == 1) {
9941 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009942 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009943
Sean Hunt216c2782010-04-07 23:11:06 +00009944 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009945 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9946 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9947 Valid = true;
9948 }
9949 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009950 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009951 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009952 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9953
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009954 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009955
Sean Hunt30019c02010-04-07 22:57:35 +00009956 // unsigned long long int, long double, and any character type are allowed
9957 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009958 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9959 Context.hasSameType(T, Context.LongDoubleTy) ||
9960 Context.hasSameType(T, Context.CharTy) ||
9961 Context.hasSameType(T, Context.WCharTy) ||
9962 Context.hasSameType(T, Context.Char16Ty) ||
9963 Context.hasSameType(T, Context.Char32Ty)) {
9964 if (++Param == FnDecl->param_end())
9965 Valid = true;
9966 goto FinishedParams;
9967 }
9968
Sean Hunt30019c02010-04-07 22:57:35 +00009969 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009970 const PointerType *PT = T->getAs<PointerType>();
9971 if (!PT)
9972 goto FinishedParams;
9973 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009974 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009975 goto FinishedParams;
9976 T = T.getUnqualifiedType();
9977
9978 // Move on to the second parameter;
9979 ++Param;
9980
9981 // If there is no second parameter, the first must be a const char *
9982 if (Param == FnDecl->param_end()) {
9983 if (Context.hasSameType(T, Context.CharTy))
9984 Valid = true;
9985 goto FinishedParams;
9986 }
9987
9988 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9989 // are allowed as the first parameter to a two-parameter function
9990 if (!(Context.hasSameType(T, Context.CharTy) ||
9991 Context.hasSameType(T, Context.WCharTy) ||
9992 Context.hasSameType(T, Context.Char16Ty) ||
9993 Context.hasSameType(T, Context.Char32Ty)))
9994 goto FinishedParams;
9995
9996 // The second and final parameter must be an std::size_t
9997 T = (*Param)->getType().getUnqualifiedType();
9998 if (Context.hasSameType(T, Context.getSizeType()) &&
9999 ++Param == FnDecl->param_end())
10000 Valid = true;
10001 }
10002
10003 // FIXME: This diagnostic is absolutely terrible.
10004FinishedParams:
10005 if (!Valid) {
10006 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10007 << FnDecl->getDeclName();
10008 return true;
10009 }
10010
Richard Smitha9e88b22012-03-09 08:16:22 +000010011 // A parameter-declaration-clause containing a default argument is not
10012 // equivalent to any of the permitted forms.
10013 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10014 ParamEnd = FnDecl->param_end();
10015 Param != ParamEnd; ++Param) {
10016 if ((*Param)->hasDefaultArg()) {
10017 Diag((*Param)->getDefaultArgRange().getBegin(),
10018 diag::err_literal_operator_default_argument)
10019 << (*Param)->getDefaultArgRange();
10020 break;
10021 }
10022 }
10023
Richard Smith2fb4ae32012-03-08 02:39:21 +000010024 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010025 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10026 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010027 // C++11 [usrlit.suffix]p1:
10028 // Literal suffix identifiers that do not start with an underscore
10029 // are reserved for future standardization.
10030 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010031 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010032
Sean Hunta6c058d2010-01-13 09:01:02 +000010033 return false;
10034}
10035
Douglas Gregor074149e2009-01-05 19:45:36 +000010036/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10037/// linkage specification, including the language and (if present)
10038/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10039/// the location of the language string literal, which is provided
10040/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10041/// the '{' brace. Otherwise, this linkage specification does not
10042/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010043Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10044 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010045 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010046 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010047 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010048 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010049 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010050 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010051 Language = LinkageSpecDecl::lang_cxx;
10052 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010053 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010054 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010055 }
Mike Stump1eb44332009-09-09 15:08:12 +000010056
Chris Lattnercc98eac2008-12-17 07:13:27 +000010057 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010058
Douglas Gregor074149e2009-01-05 19:45:36 +000010059 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010060 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010061 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010062 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010063 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010064}
10065
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010066/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010067/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10068/// valid, it's the position of the closing '}' brace in a linkage
10069/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010070Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010071 Decl *LinkageSpec,
10072 SourceLocation RBraceLoc) {
10073 if (LinkageSpec) {
10074 if (RBraceLoc.isValid()) {
10075 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10076 LSDecl->setRBraceLoc(RBraceLoc);
10077 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010078 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010079 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010080 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010081}
10082
Douglas Gregord308e622009-05-18 20:51:54 +000010083/// \brief Perform semantic analysis for the variable declaration that
10084/// occurs within a C++ catch clause, returning the newly-created
10085/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010086VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010087 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010088 SourceLocation StartLoc,
10089 SourceLocation Loc,
10090 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010091 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010092 QualType ExDeclType = TInfo->getType();
10093
Sebastian Redl4b07b292008-12-22 19:15:10 +000010094 // Arrays and functions decay.
10095 if (ExDeclType->isArrayType())
10096 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10097 else if (ExDeclType->isFunctionType())
10098 ExDeclType = Context.getPointerType(ExDeclType);
10099
10100 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10101 // The exception-declaration shall not denote a pointer or reference to an
10102 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010103 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010104 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010105 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010106 Invalid = true;
10107 }
Douglas Gregord308e622009-05-18 20:51:54 +000010108
Sebastian Redl4b07b292008-12-22 19:15:10 +000010109 QualType BaseType = ExDeclType;
10110 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010111 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010112 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010113 BaseType = Ptr->getPointeeType();
10114 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010115 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010116 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010117 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010118 BaseType = Ref->getPointeeType();
10119 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010120 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010121 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010122 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010123 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010124 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010125
Mike Stump1eb44332009-09-09 15:08:12 +000010126 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010127 RequireNonAbstractType(Loc, ExDeclType,
10128 diag::err_abstract_type_in_decl,
10129 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010130 Invalid = true;
10131
John McCall5a180392010-07-24 00:37:23 +000010132 // Only the non-fragile NeXT runtime currently supports C++ catches
10133 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010134 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010135 QualType T = ExDeclType;
10136 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10137 T = RT->getPointeeType();
10138
10139 if (T->isObjCObjectType()) {
10140 Diag(Loc, diag::err_objc_object_catch);
10141 Invalid = true;
10142 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010143 // FIXME: should this be a test for macosx-fragile specifically?
10144 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010145 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010146 }
10147 }
10148
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010149 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10150 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010151 ExDecl->setExceptionVariable(true);
10152
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010153 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010154 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010155 Invalid = true;
10156
Douglas Gregorc41b8782011-07-06 18:14:43 +000010157 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010158 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +000010159 // C++ [except.handle]p16:
10160 // The object declared in an exception-declaration or, if the
10161 // exception-declaration does not specify a name, a temporary (12.2) is
10162 // copy-initialized (8.5) from the exception object. [...]
10163 // The object is destroyed when the handler exits, after the destruction
10164 // of any automatic objects initialized within the handler.
10165 //
10166 // We just pretend to initialize the object with itself, then make sure
10167 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010168 QualType initType = ExDeclType;
10169
10170 InitializedEntity entity =
10171 InitializedEntity::InitializeVariable(ExDecl);
10172 InitializationKind initKind =
10173 InitializationKind::CreateCopy(Loc, SourceLocation());
10174
10175 Expr *opaqueValue =
10176 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10177 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10178 ExprResult result = sequence.Perform(*this, entity, initKind,
10179 MultiExprArg(&opaqueValue, 1));
10180 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010181 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010182 else {
10183 // If the constructor used was non-trivial, set this as the
10184 // "initializer".
10185 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10186 if (!construct->getConstructor()->isTrivial()) {
10187 Expr *init = MaybeCreateExprWithCleanups(construct);
10188 ExDecl->setInit(init);
10189 }
10190
10191 // And make sure it's destructable.
10192 FinalizeVarWithDestructor(ExDecl, recordType);
10193 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010194 }
10195 }
10196
Douglas Gregord308e622009-05-18 20:51:54 +000010197 if (Invalid)
10198 ExDecl->setInvalidDecl();
10199
10200 return ExDecl;
10201}
10202
10203/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10204/// handler.
John McCalld226f652010-08-21 09:40:31 +000010205Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010206 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010207 bool Invalid = D.isInvalidType();
10208
10209 // Check for unexpanded parameter packs.
10210 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10211 UPPC_ExceptionType)) {
10212 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10213 D.getIdentifierLoc());
10214 Invalid = true;
10215 }
10216
Sebastian Redl4b07b292008-12-22 19:15:10 +000010217 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010218 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010219 LookupOrdinaryName,
10220 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010221 // The scope should be freshly made just for us. There is just no way
10222 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010223 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010224 if (PrevDecl->isTemplateParameter()) {
10225 // Maybe we will complain about the shadowed template parameter.
10226 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010227 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010228 }
10229 }
10230
Chris Lattnereaaebc72009-04-25 08:06:05 +000010231 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010232 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10233 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010234 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010235 }
10236
Douglas Gregor83cb9422010-09-09 17:09:21 +000010237 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010238 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010239 D.getIdentifierLoc(),
10240 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010241 if (Invalid)
10242 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010243
Sebastian Redl4b07b292008-12-22 19:15:10 +000010244 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010245 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010246 PushOnScopeChains(ExDecl, S);
10247 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010248 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010249
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010250 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010251 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010252}
Anders Carlssonfb311762009-03-14 00:25:26 +000010253
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010254Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010255 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010256 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010257 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010258 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010259
Richard Smithe3f470a2012-07-11 22:37:56 +000010260 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10261 return 0;
10262
10263 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10264 AssertMessage, RParenLoc, false);
10265}
10266
10267Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10268 Expr *AssertExpr,
10269 StringLiteral *AssertMessage,
10270 SourceLocation RParenLoc,
10271 bool Failed) {
10272 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10273 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010274 // In a static_assert-declaration, the constant-expression shall be a
10275 // constant expression that can be contextually converted to bool.
10276 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10277 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010278 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010279
Richard Smithdaaefc52011-12-14 23:32:26 +000010280 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010281 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010282 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010283 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010284 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010285
Richard Smithe3f470a2012-07-11 22:37:56 +000010286 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010287 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010288 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010289 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010290 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010291 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010292 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010293 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010294 }
Mike Stump1eb44332009-09-09 15:08:12 +000010295
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010296 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010297 AssertExpr, AssertMessage, RParenLoc,
10298 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010299
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010300 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010301 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010302}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010303
Douglas Gregor1d869352010-04-07 16:53:43 +000010304/// \brief Perform semantic analysis of the given friend type declaration.
10305///
10306/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010307FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010308 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010309 TypeSourceInfo *TSInfo) {
10310 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10311
10312 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010313 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010314
Richard Smith6b130222011-10-18 21:39:00 +000010315 // C++03 [class.friend]p2:
10316 // An elaborated-type-specifier shall be used in a friend declaration
10317 // for a class.*
10318 //
10319 // * The class-key of the elaborated-type-specifier is required.
10320 if (!ActiveTemplateInstantiations.empty()) {
10321 // Do not complain about the form of friend template types during
10322 // template instantiation; we will already have complained when the
10323 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010324 } else {
10325 if (!T->isElaboratedTypeSpecifier()) {
10326 // If we evaluated the type to a record type, suggest putting
10327 // a tag in front.
10328 if (const RecordType *RT = T->getAs<RecordType>()) {
10329 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010330
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010331 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010332
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010333 Diag(TypeRange.getBegin(),
10334 getLangOpts().CPlusPlus11 ?
10335 diag::warn_cxx98_compat_unelaborated_friend_type :
10336 diag::ext_unelaborated_friend_type)
10337 << (unsigned) RD->getTagKind()
10338 << T
10339 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10340 InsertionText);
10341 } else {
10342 Diag(FriendLoc,
10343 getLangOpts().CPlusPlus11 ?
10344 diag::warn_cxx98_compat_nonclass_type_friend :
10345 diag::ext_nonclass_type_friend)
10346 << T
10347 << TypeRange;
10348 }
10349 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010350 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010351 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010352 diag::warn_cxx98_compat_enum_friend :
10353 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010354 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010355 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010356 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010357
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010358 // C++11 [class.friend]p3:
10359 // A friend declaration that does not declare a function shall have one
10360 // of the following forms:
10361 // friend elaborated-type-specifier ;
10362 // friend simple-type-specifier ;
10363 // friend typename-specifier ;
10364 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10365 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10366 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010367
Douglas Gregor06245bf2010-04-07 17:57:12 +000010368 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010369 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010370 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010371 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010372}
10373
John McCall9a34edb2010-10-19 01:40:49 +000010374/// Handle a friend tag declaration where the scope specifier was
10375/// templated.
10376Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10377 unsigned TagSpec, SourceLocation TagLoc,
10378 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010379 IdentifierInfo *Name,
10380 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010381 AttributeList *Attr,
10382 MultiTemplateParamsArg TempParamLists) {
10383 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10384
10385 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010386 bool Invalid = false;
10387
10388 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010389 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010390 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010391 TempParamLists.size(),
10392 /*friend*/ true,
10393 isExplicitSpecialization,
10394 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010395 if (TemplateParams->size() > 0) {
10396 // This is a declaration of a class template.
10397 if (Invalid)
10398 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010399
Eric Christopher4110e132011-07-21 05:34:24 +000010400 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10401 SS, Name, NameLoc, Attr,
10402 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010403 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010404 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010405 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010406 } else {
10407 // The "template<>" header is extraneous.
10408 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10409 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10410 isExplicitSpecialization = true;
10411 }
10412 }
10413
10414 if (Invalid) return 0;
10415
John McCall9a34edb2010-10-19 01:40:49 +000010416 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010417 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010418 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010419 isAllExplicitSpecializations = false;
10420 break;
10421 }
10422 }
10423
10424 // FIXME: don't ignore attributes.
10425
10426 // If it's explicit specializations all the way down, just forget
10427 // about the template header and build an appropriate non-templated
10428 // friend. TODO: for source fidelity, remember the headers.
10429 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010430 if (SS.isEmpty()) {
10431 bool Owned = false;
10432 bool IsDependent = false;
10433 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10434 Attr, AS_public,
10435 /*ModulePrivateLoc=*/SourceLocation(),
10436 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010437 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010438 /*ScopedEnumUsesClassTag=*/false,
10439 /*UnderlyingType=*/TypeResult());
10440 }
10441
Douglas Gregor2494dd02011-03-01 01:34:45 +000010442 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010443 ElaboratedTypeKeyword Keyword
10444 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010445 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010446 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010447 if (T.isNull())
10448 return 0;
10449
10450 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10451 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010452 DependentNameTypeLoc TL =
10453 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010454 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010455 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010456 TL.setNameLoc(NameLoc);
10457 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010458 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010459 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010460 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010461 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010462 }
10463
10464 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010465 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010466 Friend->setAccess(AS_public);
10467 CurContext->addDecl(Friend);
10468 return Friend;
10469 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010470
10471 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10472
10473
John McCall9a34edb2010-10-19 01:40:49 +000010474
10475 // Handle the case of a templated-scope friend class. e.g.
10476 // template <class T> class A<T>::B;
10477 // FIXME: we don't support these right now.
10478 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10479 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10480 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000010481 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010482 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010483 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010484 TL.setNameLoc(NameLoc);
10485
10486 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010487 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010488 Friend->setAccess(AS_public);
10489 Friend->setUnsupportedFriend(true);
10490 CurContext->addDecl(Friend);
10491 return Friend;
10492}
10493
10494
John McCalldd4a3b02009-09-16 22:47:08 +000010495/// Handle a friend type declaration. This works in tandem with
10496/// ActOnTag.
10497///
10498/// Notes on friend class templates:
10499///
10500/// We generally treat friend class declarations as if they were
10501/// declaring a class. So, for example, the elaborated type specifier
10502/// in a friend declaration is required to obey the restrictions of a
10503/// class-head (i.e. no typedefs in the scope chain), template
10504/// parameters are required to match up with simple template-ids, &c.
10505/// However, unlike when declaring a template specialization, it's
10506/// okay to refer to a template specialization without an empty
10507/// template parameter declaration, e.g.
10508/// friend class A<T>::B<unsigned>;
10509/// We permit this as a special case; if there are any template
10510/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010511/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010512Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010513 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010514 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010515
10516 assert(DS.isFriendSpecified());
10517 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10518
John McCalldd4a3b02009-09-16 22:47:08 +000010519 // Try to convert the decl specifier to a type. This works for
10520 // friend templates because ActOnTag never produces a ClassTemplateDecl
10521 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010522 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010523 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10524 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010525 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010526 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010527
Douglas Gregor6ccab972010-12-16 01:14:37 +000010528 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10529 return 0;
10530
John McCalldd4a3b02009-09-16 22:47:08 +000010531 // This is definitely an error in C++98. It's probably meant to
10532 // be forbidden in C++0x, too, but the specification is just
10533 // poorly written.
10534 //
10535 // The problem is with declarations like the following:
10536 // template <T> friend A<T>::foo;
10537 // where deciding whether a class C is a friend or not now hinges
10538 // on whether there exists an instantiation of A that causes
10539 // 'foo' to equal C. There are restrictions on class-heads
10540 // (which we declare (by fiat) elaborated friend declarations to
10541 // be) that makes this tractable.
10542 //
10543 // FIXME: handle "template <> friend class A<T>;", which
10544 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010545 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010546 Diag(Loc, diag::err_tagless_friend_type_template)
10547 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010548 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010549 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010550
John McCall02cace72009-08-28 07:59:38 +000010551 // C++98 [class.friend]p1: A friend of a class is a function
10552 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010553 // This is fixed in DR77, which just barely didn't make the C++03
10554 // deadline. It's also a very silly restriction that seriously
10555 // affects inner classes and which nobody else seems to implement;
10556 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010557 //
10558 // But note that we could warn about it: it's always useless to
10559 // friend one of your own members (it's not, however, worthless to
10560 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010561
John McCalldd4a3b02009-09-16 22:47:08 +000010562 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010563 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010564 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010565 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010566 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010567 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010568 DS.getFriendSpecLoc());
10569 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010570 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010571
10572 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010573 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010574
John McCalldd4a3b02009-09-16 22:47:08 +000010575 D->setAccess(AS_public);
10576 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010577
John McCalld226f652010-08-21 09:40:31 +000010578 return D;
John McCall02cace72009-08-28 07:59:38 +000010579}
10580
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000010581NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10582 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010583 const DeclSpec &DS = D.getDeclSpec();
10584
10585 assert(DS.isFriendSpecified());
10586 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10587
10588 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010589 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010590
10591 // C++ [class.friend]p1
10592 // A friend of a class is a function or class....
10593 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010594 // It *doesn't* see through dependent types, which is correct
10595 // according to [temp.arg.type]p3:
10596 // If a declaration acquires a function type through a
10597 // type dependent on a template-parameter and this causes
10598 // a declaration that does not use the syntactic form of a
10599 // function declarator to have a function type, the program
10600 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010601 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010602 Diag(Loc, diag::err_unexpected_friend);
10603
10604 // It might be worthwhile to try to recover by creating an
10605 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010606 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010607 }
10608
10609 // C++ [namespace.memdef]p3
10610 // - If a friend declaration in a non-local class first declares a
10611 // class or function, the friend class or function is a member
10612 // of the innermost enclosing namespace.
10613 // - The name of the friend is not found by simple name lookup
10614 // until a matching declaration is provided in that namespace
10615 // scope (either before or after the class declaration granting
10616 // friendship).
10617 // - If a friend function is called, its name may be found by the
10618 // name lookup that considers functions from namespaces and
10619 // classes associated with the types of the function arguments.
10620 // - When looking for a prior declaration of a class or a function
10621 // declared as a friend, scopes outside the innermost enclosing
10622 // namespace scope are not considered.
10623
John McCall337ec3d2010-10-12 23:13:28 +000010624 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010625 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10626 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010627 assert(Name);
10628
Douglas Gregor6ccab972010-12-16 01:14:37 +000010629 // Check for unexpanded parameter packs.
10630 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10631 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10632 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10633 return 0;
10634
John McCall67d1a672009-08-06 02:15:43 +000010635 // The context we found the declaration in, or in which we should
10636 // create the declaration.
10637 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010638 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010639 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010640 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010641
John McCall337ec3d2010-10-12 23:13:28 +000010642 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010643
John McCall337ec3d2010-10-12 23:13:28 +000010644 // There are four cases here.
10645 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010646 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010647 // there as appropriate.
10648 // Recover from invalid scope qualifiers as if they just weren't there.
10649 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010650 // C++0x [namespace.memdef]p3:
10651 // If the name in a friend declaration is neither qualified nor
10652 // a template-id and the declaration is a function or an
10653 // elaborated-type-specifier, the lookup to determine whether
10654 // the entity has been previously declared shall not consider
10655 // any scopes outside the innermost enclosing namespace.
10656 // C++0x [class.friend]p11:
10657 // If a friend declaration appears in a local class and the name
10658 // specified is an unqualified name, a prior declaration is
10659 // looked up without considering scopes that are outside the
10660 // innermost enclosing non-class scope. For a friend function
10661 // declaration, if there is no prior declaration, the program is
10662 // ill-formed.
10663 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010664 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010665
John McCall29ae6e52010-10-13 05:45:15 +000010666 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010667 DC = CurContext;
10668 while (true) {
10669 // Skip class contexts. If someone can cite chapter and verse
10670 // for this behavior, that would be nice --- it's what GCC and
10671 // EDG do, and it seems like a reasonable intent, but the spec
10672 // really only says that checks for unqualified existing
10673 // declarations should stop at the nearest enclosing namespace,
10674 // not that they should only consider the nearest enclosing
10675 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010676 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010677 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010678
John McCall68263142009-11-18 22:49:29 +000010679 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010680
10681 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010682 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010683 break;
John McCall29ae6e52010-10-13 05:45:15 +000010684
John McCall8a407372010-10-14 22:22:28 +000010685 if (isTemplateId) {
10686 if (isa<TranslationUnitDecl>(DC)) break;
10687 } else {
10688 if (DC->isFileContext()) break;
10689 }
John McCall67d1a672009-08-06 02:15:43 +000010690 DC = DC->getParent();
10691 }
10692
10693 // C++ [class.friend]p1: A friend of a class is a function or
10694 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010695 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010696 // Most C++ 98 compilers do seem to give an error here, so
10697 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010698 if (!Previous.empty() && DC->Equals(CurContext))
10699 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010700 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010701 diag::warn_cxx98_compat_friend_is_member :
10702 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010703
John McCall380aaa42010-10-13 06:22:15 +000010704 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010705
Douglas Gregor883af832011-10-10 01:11:59 +000010706 // C++ [class.friend]p6:
10707 // A function can be defined in a friend declaration of a class if and
10708 // only if the class is a non-local class (9.8), the function name is
10709 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010710 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010711 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10712 }
10713
John McCall337ec3d2010-10-12 23:13:28 +000010714 // - There's a non-dependent scope specifier, in which case we
10715 // compute it and do a previous lookup there for a function
10716 // or function template.
10717 } else if (!SS.getScopeRep()->isDependent()) {
10718 DC = computeDeclContext(SS);
10719 if (!DC) return 0;
10720
10721 if (RequireCompleteDeclContext(SS, DC)) return 0;
10722
10723 LookupQualifiedName(Previous, DC);
10724
10725 // Ignore things found implicitly in the wrong scope.
10726 // TODO: better diagnostics for this case. Suggesting the right
10727 // qualified scope would be nice...
10728 LookupResult::Filter F = Previous.makeFilter();
10729 while (F.hasNext()) {
10730 NamedDecl *D = F.next();
10731 if (!DC->InEnclosingNamespaceSetOf(
10732 D->getDeclContext()->getRedeclContext()))
10733 F.erase();
10734 }
10735 F.done();
10736
10737 if (Previous.empty()) {
10738 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010739 Diag(Loc, diag::err_qualified_friend_not_found)
10740 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010741 return 0;
10742 }
10743
10744 // C++ [class.friend]p1: A friend of a class is a function or
10745 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010746 if (DC->Equals(CurContext))
10747 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010748 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010749 diag::warn_cxx98_compat_friend_is_member :
10750 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010751
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010752 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010753 // C++ [class.friend]p6:
10754 // A function can be defined in a friend declaration of a class if and
10755 // only if the class is a non-local class (9.8), the function name is
10756 // unqualified, and the function has namespace scope.
10757 SemaDiagnosticBuilder DB
10758 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10759
10760 DB << SS.getScopeRep();
10761 if (DC->isFileContext())
10762 DB << FixItHint::CreateRemoval(SS.getRange());
10763 SS.clear();
10764 }
John McCall337ec3d2010-10-12 23:13:28 +000010765
10766 // - There's a scope specifier that does not match any template
10767 // parameter lists, in which case we use some arbitrary context,
10768 // create a method or method template, and wait for instantiation.
10769 // - There's a scope specifier that does match some template
10770 // parameter lists, which we don't handle right now.
10771 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010772 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010773 // C++ [class.friend]p6:
10774 // A function can be defined in a friend declaration of a class if and
10775 // only if the class is a non-local class (9.8), the function name is
10776 // unqualified, and the function has namespace scope.
10777 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10778 << SS.getScopeRep();
10779 }
10780
John McCall337ec3d2010-10-12 23:13:28 +000010781 DC = CurContext;
10782 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010783 }
Douglas Gregor883af832011-10-10 01:11:59 +000010784
John McCall29ae6e52010-10-13 05:45:15 +000010785 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010786 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010787 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10788 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10789 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010790 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010791 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10792 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010793 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010794 }
John McCall67d1a672009-08-06 02:15:43 +000010795 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010796
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010797 // FIXME: This is an egregious hack to cope with cases where the scope stack
10798 // does not contain the declaration context, i.e., in an out-of-line
10799 // definition of a class.
10800 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10801 if (!DCScope) {
10802 FakeDCScope.setEntity(DC);
10803 DCScope = &FakeDCScope;
10804 }
10805
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010806 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010807 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010808 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010809 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010810
Douglas Gregor182ddf02009-09-28 00:08:27 +000010811 assert(ND->getDeclContext() == DC);
10812 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010813
John McCallab88d972009-08-31 22:39:49 +000010814 // Add the function declaration to the appropriate lookup tables,
10815 // adjusting the redeclarations list as necessary. We don't
10816 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010817 //
John McCallab88d972009-08-31 22:39:49 +000010818 // Also update the scope-based lookup if the target context's
10819 // lookup context is in lexical scope.
10820 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010821 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010822 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010823 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010824 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010825 }
John McCall02cace72009-08-28 07:59:38 +000010826
10827 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010828 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010829 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010830 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010831 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010832
John McCall1f2e1a92012-08-10 03:15:35 +000010833 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010834 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010835 } else {
10836 if (DC->isRecord()) CheckFriendAccess(ND);
10837
John McCall6102ca12010-10-16 06:59:13 +000010838 FunctionDecl *FD;
10839 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10840 FD = FTD->getTemplatedDecl();
10841 else
10842 FD = cast<FunctionDecl>(ND);
10843
10844 // Mark templated-scope function declarations as unsupported.
10845 if (FD->getNumTemplateParameterLists())
10846 FrD->setUnsupportedFriend(true);
10847 }
John McCall337ec3d2010-10-12 23:13:28 +000010848
John McCalld226f652010-08-21 09:40:31 +000010849 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010850}
10851
John McCalld226f652010-08-21 09:40:31 +000010852void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10853 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010854
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000010855 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000010856 if (!Fn) {
10857 Diag(DelLoc, diag::err_deleted_non_function);
10858 return;
10859 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010860 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010861 // Don't consider the implicit declaration we generate for explicit
10862 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010863 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10864 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010865 Diag(DelLoc, diag::err_deleted_decl_not_first);
10866 Diag(Prev->getLocation(), diag::note_previous_declaration);
10867 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010868 // If the declaration wasn't the first, we delete the function anyway for
10869 // recovery.
10870 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010871 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010872}
Sebastian Redl13e88542009-04-27 21:33:24 +000010873
Sean Hunte4246a62011-05-12 06:15:49 +000010874void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000010875 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000010876
10877 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010878 if (MD->getParent()->isDependentType()) {
10879 MD->setDefaulted();
10880 MD->setExplicitlyDefaulted();
10881 return;
10882 }
10883
Sean Hunte4246a62011-05-12 06:15:49 +000010884 CXXSpecialMember Member = getSpecialMember(MD);
10885 if (Member == CXXInvalid) {
10886 Diag(DefaultLoc, diag::err_default_special_members);
10887 return;
10888 }
10889
10890 MD->setDefaulted();
10891 MD->setExplicitlyDefaulted();
10892
Sean Huntcd10dec2011-05-23 23:14:04 +000010893 // If this definition appears within the record, do the checking when
10894 // the record is complete.
10895 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000010896 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000010897 // Find the uninstantiated declaration that actually had the '= default'
10898 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000010899 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000010900
10901 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010902 return;
10903
Richard Smithb9d0b762012-07-27 04:22:15 +000010904 CheckExplicitlyDefaultedSpecialMember(MD);
10905
Richard Smith1d28caf2012-12-11 01:14:52 +000010906 // The exception specification is needed because we are defining the
10907 // function.
10908 ResolveExceptionSpec(DefaultLoc,
10909 MD->getType()->castAs<FunctionProtoType>());
10910
Sean Hunte4246a62011-05-12 06:15:49 +000010911 switch (Member) {
10912 case CXXDefaultConstructor: {
10913 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010914 if (!CD->isInvalidDecl())
10915 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10916 break;
10917 }
10918
10919 case CXXCopyConstructor: {
10920 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010921 if (!CD->isInvalidDecl())
10922 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010923 break;
10924 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010925
Sean Hunt2b188082011-05-14 05:23:28 +000010926 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010927 if (!MD->isInvalidDecl())
10928 DefineImplicitCopyAssignment(DefaultLoc, MD);
10929 break;
10930 }
10931
Sean Huntcb45a0f2011-05-12 22:46:25 +000010932 case CXXDestructor: {
10933 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010934 if (!DD->isInvalidDecl())
10935 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010936 break;
10937 }
10938
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010939 case CXXMoveConstructor: {
10940 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010941 if (!CD->isInvalidDecl())
10942 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010943 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010944 }
Sean Hunt82713172011-05-25 23:16:36 +000010945
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010946 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010947 if (!MD->isInvalidDecl())
10948 DefineImplicitMoveAssignment(DefaultLoc, MD);
10949 break;
10950 }
10951
10952 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010953 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010954 }
10955 } else {
10956 Diag(DefaultLoc, diag::err_default_special_members);
10957 }
10958}
10959
Sebastian Redl13e88542009-04-27 21:33:24 +000010960static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010961 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010962 Stmt *SubStmt = *CI;
10963 if (!SubStmt)
10964 continue;
10965 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010966 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010967 diag::err_return_in_constructor_handler);
10968 if (!isa<Expr>(SubStmt))
10969 SearchForReturnInStmt(Self, SubStmt);
10970 }
10971}
10972
10973void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10974 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10975 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10976 SearchForReturnInStmt(*this, Handler);
10977 }
10978}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010979
David Blaikie299adab2013-01-18 23:03:15 +000010980bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000010981 const CXXMethodDecl *Old) {
10982 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
10983 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
10984
10985 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
10986
10987 // If the calling conventions match, everything is fine
10988 if (NewCC == OldCC)
10989 return false;
10990
10991 // If either of the calling conventions are set to "default", we need to pick
10992 // something more sensible based on the target. This supports code where the
10993 // one method explicitly sets thiscall, and another has no explicit calling
10994 // convention.
10995 CallingConv Default =
10996 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
10997 if (NewCC == CC_Default)
10998 NewCC = Default;
10999 if (OldCC == CC_Default)
11000 OldCC = Default;
11001
11002 // If the calling conventions still don't match, then report the error
11003 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011004 Diag(New->getLocation(),
11005 diag::err_conflicting_overriding_cc_attributes)
11006 << New->getDeclName() << New->getType() << Old->getType();
11007 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11008 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011009 }
11010
11011 return false;
11012}
11013
Mike Stump1eb44332009-09-09 15:08:12 +000011014bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011015 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011016 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11017 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011018
Chandler Carruth73857792010-02-15 11:53:20 +000011019 if (Context.hasSameType(NewTy, OldTy) ||
11020 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011021 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011022
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011023 // Check if the return types are covariant
11024 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011025
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011026 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011027 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11028 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011029 NewClassTy = NewPT->getPointeeType();
11030 OldClassTy = OldPT->getPointeeType();
11031 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011032 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11033 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11034 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11035 NewClassTy = NewRT->getPointeeType();
11036 OldClassTy = OldRT->getPointeeType();
11037 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011038 }
11039 }
Mike Stump1eb44332009-09-09 15:08:12 +000011040
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011041 // The return types aren't either both pointers or references to a class type.
11042 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011043 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011044 diag::err_different_return_type_for_overriding_virtual_function)
11045 << New->getDeclName() << NewTy << OldTy;
11046 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011047
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011048 return true;
11049 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011050
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011051 // C++ [class.virtual]p6:
11052 // If the return type of D::f differs from the return type of B::f, the
11053 // class type in the return type of D::f shall be complete at the point of
11054 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011055 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11056 if (!RT->isBeingDefined() &&
11057 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011058 diag::err_covariant_return_incomplete,
11059 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011060 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011061 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011062
Douglas Gregora4923eb2009-11-16 21:35:15 +000011063 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011064 // Check if the new class derives from the old class.
11065 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11066 Diag(New->getLocation(),
11067 diag::err_covariant_return_not_derived)
11068 << New->getDeclName() << NewTy << OldTy;
11069 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11070 return true;
11071 }
Mike Stump1eb44332009-09-09 15:08:12 +000011072
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011073 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011074 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011075 diag::err_covariant_return_inaccessible_base,
11076 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11077 // FIXME: Should this point to the return type?
11078 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011079 // FIXME: this note won't trigger for delayed access control
11080 // diagnostics, and it's impossible to get an undelayed error
11081 // here from access control during the original parse because
11082 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011083 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11084 return true;
11085 }
11086 }
Mike Stump1eb44332009-09-09 15:08:12 +000011087
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011088 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011089 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011090 Diag(New->getLocation(),
11091 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011092 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011093 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11094 return true;
11095 };
Mike Stump1eb44332009-09-09 15:08:12 +000011096
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011097
11098 // The new class type must have the same or less qualifiers as the old type.
11099 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11100 Diag(New->getLocation(),
11101 diag::err_covariant_return_type_class_type_more_qualified)
11102 << New->getDeclName() << NewTy << OldTy;
11103 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11104 return true;
11105 };
Mike Stump1eb44332009-09-09 15:08:12 +000011106
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011107 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011108}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011109
Douglas Gregor4ba31362009-12-01 17:24:26 +000011110/// \brief Mark the given method pure.
11111///
11112/// \param Method the method to be marked pure.
11113///
11114/// \param InitRange the source range that covers the "0" initializer.
11115bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011116 SourceLocation EndLoc = InitRange.getEnd();
11117 if (EndLoc.isValid())
11118 Method->setRangeEnd(EndLoc);
11119
Douglas Gregor4ba31362009-12-01 17:24:26 +000011120 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11121 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011122 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011123 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011124
11125 if (!Method->isInvalidDecl())
11126 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11127 << Method->getDeclName() << InitRange;
11128 return true;
11129}
11130
Douglas Gregor552e2992012-02-21 02:22:07 +000011131/// \brief Determine whether the given declaration is a static data member.
11132static bool isStaticDataMember(Decl *D) {
11133 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11134 if (!Var)
11135 return false;
11136
11137 return Var->isStaticDataMember();
11138}
John McCall731ad842009-12-19 09:28:58 +000011139/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11140/// an initializer for the out-of-line declaration 'Dcl'. The scope
11141/// is a fresh scope pushed for just this purpose.
11142///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011143/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11144/// static data member of class X, names should be looked up in the scope of
11145/// class X.
John McCalld226f652010-08-21 09:40:31 +000011146void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011147 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011148 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011149
John McCall731ad842009-12-19 09:28:58 +000011150 // We should only get called for declarations with scope specifiers, like:
11151 // int foo::bar;
11152 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011153 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011154
11155 // If we are parsing the initializer for a static data member, push a
11156 // new expression evaluation context that is associated with this static
11157 // data member.
11158 if (isStaticDataMember(D))
11159 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011160}
11161
11162/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011163/// initializer for the out-of-line declaration 'D'.
11164void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011165 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011166 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011167
Douglas Gregor552e2992012-02-21 02:22:07 +000011168 if (isStaticDataMember(D))
11169 PopExpressionEvaluationContext();
11170
John McCall731ad842009-12-19 09:28:58 +000011171 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011172 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011173}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011174
11175/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11176/// C++ if/switch/while/for statement.
11177/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011178DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011179 // C++ 6.4p2:
11180 // The declarator shall not specify a function or an array.
11181 // The type-specifier-seq shall not contain typedef and shall not declare a
11182 // new class or enumeration.
11183 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11184 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011185
11186 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011187 if (!Dcl)
11188 return true;
11189
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011190 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11191 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011192 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011193 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011194 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011195
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011196 return Dcl;
11197}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011198
Douglas Gregordfe65432011-07-28 19:11:31 +000011199void Sema::LoadExternalVTableUses() {
11200 if (!ExternalSource)
11201 return;
11202
11203 SmallVector<ExternalVTableUse, 4> VTables;
11204 ExternalSource->ReadUsedVTables(VTables);
11205 SmallVector<VTableUse, 4> NewUses;
11206 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11207 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11208 = VTablesUsed.find(VTables[I].Record);
11209 // Even if a definition wasn't required before, it may be required now.
11210 if (Pos != VTablesUsed.end()) {
11211 if (!Pos->second && VTables[I].DefinitionRequired)
11212 Pos->second = true;
11213 continue;
11214 }
11215
11216 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11217 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11218 }
11219
11220 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11221}
11222
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011223void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11224 bool DefinitionRequired) {
11225 // Ignore any vtable uses in unevaluated operands or for classes that do
11226 // not have a vtable.
11227 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11228 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011229 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011230 return;
11231
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011232 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011233 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011234 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11235 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11236 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11237 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011238 // If we already had an entry, check to see if we are promoting this vtable
11239 // to required a definition. If so, we need to reappend to the VTableUses
11240 // list, since we may have already processed the first entry.
11241 if (DefinitionRequired && !Pos.first->second) {
11242 Pos.first->second = true;
11243 } else {
11244 // Otherwise, we can early exit.
11245 return;
11246 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011247 }
11248
11249 // Local classes need to have their virtual members marked
11250 // immediately. For all other classes, we mark their virtual members
11251 // at the end of the translation unit.
11252 if (Class->isLocalClass())
11253 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011254 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011255 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011256}
11257
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011258bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011259 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011260 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011261 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011262
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011263 // Note: The VTableUses vector could grow as a result of marking
11264 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011265 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011266 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011267 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011268 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011269 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011270 if (!Class)
11271 continue;
11272
11273 SourceLocation Loc = VTableUses[I].second;
11274
Richard Smithb9d0b762012-07-27 04:22:15 +000011275 bool DefineVTable = true;
11276
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011277 // If this class has a key function, but that key function is
11278 // defined in another translation unit, we don't need to emit the
11279 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011280 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011281 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011282 switch (KeyFunction->getTemplateSpecializationKind()) {
11283 case TSK_Undeclared:
11284 case TSK_ExplicitSpecialization:
11285 case TSK_ExplicitInstantiationDeclaration:
11286 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011287 DefineVTable = false;
11288 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011289
11290 case TSK_ExplicitInstantiationDefinition:
11291 case TSK_ImplicitInstantiation:
11292 // We will be instantiating the key function.
11293 break;
11294 }
11295 } else if (!KeyFunction) {
11296 // If we have a class with no key function that is the subject
11297 // of an explicit instantiation declaration, suppress the
11298 // vtable; it will live with the explicit instantiation
11299 // definition.
11300 bool IsExplicitInstantiationDeclaration
11301 = Class->getTemplateSpecializationKind()
11302 == TSK_ExplicitInstantiationDeclaration;
11303 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11304 REnd = Class->redecls_end();
11305 R != REnd; ++R) {
11306 TemplateSpecializationKind TSK
11307 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11308 if (TSK == TSK_ExplicitInstantiationDeclaration)
11309 IsExplicitInstantiationDeclaration = true;
11310 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11311 IsExplicitInstantiationDeclaration = false;
11312 break;
11313 }
11314 }
11315
11316 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011317 DefineVTable = false;
11318 }
11319
11320 // The exception specifications for all virtual members may be needed even
11321 // if we are not providing an authoritative form of the vtable in this TU.
11322 // We may choose to emit it available_externally anyway.
11323 if (!DefineVTable) {
11324 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11325 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011326 }
11327
11328 // Mark all of the virtual members of this class as referenced, so
11329 // that we can build a vtable. Then, tell the AST consumer that a
11330 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011331 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011332 MarkVirtualMembersReferenced(Loc, Class);
11333 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11334 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11335
11336 // Optionally warn if we're emitting a weak vtable.
11337 if (Class->getLinkage() == ExternalLinkage &&
11338 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011339 const FunctionDecl *KeyFunctionDef = 0;
11340 if (!KeyFunction ||
11341 (KeyFunction->hasBody(KeyFunctionDef) &&
11342 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011343 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11344 TSK_ExplicitInstantiationDefinition
11345 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11346 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011347 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011348 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011349 VTableUses.clear();
11350
Douglas Gregor78844032011-04-22 22:25:37 +000011351 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011352}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011353
Richard Smithb9d0b762012-07-27 04:22:15 +000011354void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11355 const CXXRecordDecl *RD) {
11356 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11357 E = RD->method_end(); I != E; ++I)
11358 if ((*I)->isVirtual() && !(*I)->isPure())
11359 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11360}
11361
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011362void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11363 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011364 // Mark all functions which will appear in RD's vtable as used.
11365 CXXFinalOverriderMap FinalOverriders;
11366 RD->getFinalOverriders(FinalOverriders);
11367 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11368 E = FinalOverriders.end();
11369 I != E; ++I) {
11370 for (OverridingMethods::const_iterator OI = I->second.begin(),
11371 OE = I->second.end();
11372 OI != OE; ++OI) {
11373 assert(OI->second.size() > 0 && "no final overrider");
11374 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011375
Richard Smithff817f72012-07-07 06:59:51 +000011376 // C++ [basic.def.odr]p2:
11377 // [...] A virtual member function is used if it is not pure. [...]
11378 if (!Overrider->isPure())
11379 MarkFunctionReferenced(Loc, Overrider);
11380 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011381 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011382
11383 // Only classes that have virtual bases need a VTT.
11384 if (RD->getNumVBases() == 0)
11385 return;
11386
11387 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11388 e = RD->bases_end(); i != e; ++i) {
11389 const CXXRecordDecl *Base =
11390 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011391 if (Base->getNumVBases() == 0)
11392 continue;
11393 MarkVirtualMembersReferenced(Loc, Base);
11394 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011395}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011396
11397/// SetIvarInitializers - This routine builds initialization ASTs for the
11398/// Objective-C implementation whose ivars need be initialized.
11399void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011400 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011401 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011402 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011403 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011404 CollectIvarsToConstructOrDestruct(OID, ivars);
11405 if (ivars.empty())
11406 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011407 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011408 for (unsigned i = 0; i < ivars.size(); i++) {
11409 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011410 if (Field->isInvalidDecl())
11411 continue;
11412
Sean Huntcbb67482011-01-08 20:30:50 +000011413 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011414 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11415 InitializationKind InitKind =
11416 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11417
11418 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011419 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011420 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011421 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011422 // Note, MemberInit could actually come back empty if no initialization
11423 // is required (e.g., because it would call a trivial default constructor)
11424 if (!MemberInit.get() || MemberInit.isInvalid())
11425 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011426
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011427 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011428 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11429 SourceLocation(),
11430 MemberInit.takeAs<Expr>(),
11431 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011432 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011433
11434 // Be sure that the destructor is accessible and is marked as referenced.
11435 if (const RecordType *RecordTy
11436 = Context.getBaseElementType(Field->getType())
11437 ->getAs<RecordType>()) {
11438 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011439 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011440 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011441 CheckDestructorAccess(Field->getLocation(), Destructor,
11442 PDiag(diag::err_access_dtor_ivar)
11443 << Context.getBaseElementType(Field->getType()));
11444 }
11445 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011446 }
11447 ObjCImplementation->setIvarInitializers(Context,
11448 AllToInit.data(), AllToInit.size());
11449 }
11450}
Sean Huntfe57eef2011-05-04 05:57:24 +000011451
Sean Huntebcbe1d2011-05-04 23:29:54 +000011452static
11453void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11454 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11455 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11456 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11457 Sema &S) {
11458 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11459 CE = Current.end();
11460 if (Ctor->isInvalidDecl())
11461 return;
11462
Richard Smitha8eaf002012-08-23 06:16:52 +000011463 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11464
11465 // Target may not be determinable yet, for instance if this is a dependent
11466 // call in an uninstantiated template.
11467 if (Target) {
11468 const FunctionDecl *FNTarget = 0;
11469 (void)Target->hasBody(FNTarget);
11470 Target = const_cast<CXXConstructorDecl*>(
11471 cast_or_null<CXXConstructorDecl>(FNTarget));
11472 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011473
11474 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11475 // Avoid dereferencing a null pointer here.
11476 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11477
11478 if (!Current.insert(Canonical))
11479 return;
11480
11481 // We know that beyond here, we aren't chaining into a cycle.
11482 if (!Target || !Target->isDelegatingConstructor() ||
11483 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11484 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11485 Valid.insert(*CI);
11486 Current.clear();
11487 // We've hit a cycle.
11488 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11489 Current.count(TCanonical)) {
11490 // If we haven't diagnosed this cycle yet, do so now.
11491 if (!Invalid.count(TCanonical)) {
11492 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011493 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011494 << Ctor;
11495
Richard Smitha8eaf002012-08-23 06:16:52 +000011496 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011497 if (TCanonical != Canonical)
11498 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11499
11500 CXXConstructorDecl *C = Target;
11501 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011502 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011503 (void)C->getTargetConstructor()->hasBody(FNTarget);
11504 assert(FNTarget && "Ctor cycle through bodiless function");
11505
Richard Smitha8eaf002012-08-23 06:16:52 +000011506 C = const_cast<CXXConstructorDecl*>(
11507 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011508 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11509 }
11510 }
11511
11512 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11513 Invalid.insert(*CI);
11514 Current.clear();
11515 } else {
11516 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11517 }
11518}
11519
11520
Sean Huntfe57eef2011-05-04 05:57:24 +000011521void Sema::CheckDelegatingCtorCycles() {
11522 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11523
Sean Huntebcbe1d2011-05-04 23:29:54 +000011524 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11525 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011526
Douglas Gregor0129b562011-07-27 21:57:17 +000011527 for (DelegatingCtorDeclsType::iterator
11528 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011529 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011530 I != E; ++I)
11531 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011532
11533 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11534 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011535}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011536
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011537namespace {
11538 /// \brief AST visitor that finds references to the 'this' expression.
11539 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11540 Sema &S;
11541
11542 public:
11543 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11544
11545 bool VisitCXXThisExpr(CXXThisExpr *E) {
11546 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11547 << E->isImplicit();
11548 return false;
11549 }
11550 };
11551}
11552
11553bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11554 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11555 if (!TSInfo)
11556 return false;
11557
11558 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011559 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011560 if (!ProtoTL)
11561 return false;
11562
11563 // C++11 [expr.prim.general]p3:
11564 // [The expression this] shall not appear before the optional
11565 // cv-qualifier-seq and it shall not appear within the declaration of a
11566 // static member function (although its type and value category are defined
11567 // within a static member function as they are within a non-static member
11568 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011569 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000011570 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011571 FindCXXThisExpr Finder(*this);
11572
11573 // If the return type came after the cv-qualifier-seq, check it now.
11574 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000011575 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011576 return true;
11577
11578 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011579 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11580 return true;
11581
11582 return checkThisInStaticMemberFunctionAttributes(Method);
11583}
11584
11585bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11586 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11587 if (!TSInfo)
11588 return false;
11589
11590 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011591 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011592 if (!ProtoTL)
11593 return false;
11594
David Blaikie39e6ab42013-02-18 22:06:02 +000011595 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011596 FindCXXThisExpr Finder(*this);
11597
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011598 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011599 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011600 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011601 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011602 case EST_DynamicNone:
11603 case EST_MSAny:
11604 case EST_None:
11605 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011606
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011607 case EST_ComputedNoexcept:
11608 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11609 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011610
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011611 case EST_Dynamic:
11612 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011613 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011614 E != EEnd; ++E) {
11615 if (!Finder.TraverseType(*E))
11616 return true;
11617 }
11618 break;
11619 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011620
11621 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011622}
11623
11624bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11625 FindCXXThisExpr Finder(*this);
11626
11627 // Check attributes.
11628 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11629 A != AEnd; ++A) {
11630 // FIXME: This should be emitted by tblgen.
11631 Expr *Arg = 0;
11632 ArrayRef<Expr *> Args;
11633 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11634 Arg = G->getArg();
11635 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11636 Arg = G->getArg();
11637 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11638 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11639 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11640 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11641 else if (ExclusiveLockFunctionAttr *ELF
11642 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11643 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11644 else if (SharedLockFunctionAttr *SLF
11645 = dyn_cast<SharedLockFunctionAttr>(*A))
11646 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11647 else if (ExclusiveTrylockFunctionAttr *ETLF
11648 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11649 Arg = ETLF->getSuccessValue();
11650 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11651 } else if (SharedTrylockFunctionAttr *STLF
11652 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11653 Arg = STLF->getSuccessValue();
11654 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11655 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11656 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11657 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11658 Arg = LR->getArg();
11659 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11660 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11661 else if (ExclusiveLocksRequiredAttr *ELR
11662 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11663 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11664 else if (SharedLocksRequiredAttr *SLR
11665 = dyn_cast<SharedLocksRequiredAttr>(*A))
11666 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11667
11668 if (Arg && !Finder.TraverseStmt(Arg))
11669 return true;
11670
11671 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11672 if (!Finder.TraverseStmt(Args[I]))
11673 return true;
11674 }
11675 }
11676
11677 return false;
11678}
11679
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011680void
11681Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11682 ArrayRef<ParsedType> DynamicExceptions,
11683 ArrayRef<SourceRange> DynamicExceptionRanges,
11684 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011685 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011686 FunctionProtoType::ExtProtoInfo &EPI) {
11687 Exceptions.clear();
11688 EPI.ExceptionSpecType = EST;
11689 if (EST == EST_Dynamic) {
11690 Exceptions.reserve(DynamicExceptions.size());
11691 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11692 // FIXME: Preserve type source info.
11693 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11694
11695 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11696 collectUnexpandedParameterPacks(ET, Unexpanded);
11697 if (!Unexpanded.empty()) {
11698 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11699 UPPC_ExceptionType,
11700 Unexpanded);
11701 continue;
11702 }
11703
11704 // Check that the type is valid for an exception spec, and
11705 // drop it if not.
11706 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11707 Exceptions.push_back(ET);
11708 }
11709 EPI.NumExceptions = Exceptions.size();
11710 EPI.Exceptions = Exceptions.data();
11711 return;
11712 }
11713
11714 if (EST == EST_ComputedNoexcept) {
11715 // If an error occurred, there's no expression here.
11716 if (NoexceptExpr) {
11717 assert((NoexceptExpr->isTypeDependent() ||
11718 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11719 Context.BoolTy) &&
11720 "Parser should have made sure that the expression is boolean");
11721 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11722 EPI.ExceptionSpecType = EST_BasicNoexcept;
11723 return;
11724 }
11725
11726 if (!NoexceptExpr->isValueDependent())
11727 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011728 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011729 /*AllowFold*/ false).take();
11730 EPI.NoexceptExpr = NoexceptExpr;
11731 }
11732 return;
11733 }
11734}
11735
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011736/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11737Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11738 // Implicitly declared functions (e.g. copy constructors) are
11739 // __host__ __device__
11740 if (D->isImplicit())
11741 return CFT_HostDevice;
11742
11743 if (D->hasAttr<CUDAGlobalAttr>())
11744 return CFT_Global;
11745
11746 if (D->hasAttr<CUDADeviceAttr>()) {
11747 if (D->hasAttr<CUDAHostAttr>())
11748 return CFT_HostDevice;
11749 else
11750 return CFT_Device;
11751 }
11752
11753 return CFT_Host;
11754}
11755
11756bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11757 CUDAFunctionTarget CalleeTarget) {
11758 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11759 // Callable from the device only."
11760 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11761 return true;
11762
11763 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11764 // Callable from the host only."
11765 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11766 // Callable from the host only."
11767 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11768 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11769 return true;
11770
11771 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11772 return true;
11773
11774 return false;
11775}