blob: 55b64351381dab281e40dff304dc592266185b68 [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,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001175 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001176 ParsedType basetype, SourceLocation BaseLoc,
1177 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001178 if (!classdecl)
1179 return true;
1180
Douglas Gregor40808ce2009-03-09 23:48:35 +00001181 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001182 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001183 if (!Class)
1184 return true;
1185
Nick Lewycky56062202010-07-26 16:56:01 +00001186 TypeSourceInfo *TInfo = 0;
1187 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001188
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001189 if (EllipsisLoc.isInvalid() &&
1190 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001191 UPPC_BaseType))
1192 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001193
Douglas Gregor2943aed2009-03-03 04:44:36 +00001194 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001195 Virtual, Access, TInfo,
1196 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001197 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001198 else
1199 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Douglas Gregor2943aed2009-03-03 04:44:36 +00001201 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001202}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001203
Douglas Gregor2943aed2009-03-03 04:44:36 +00001204/// \brief Performs the actual work of attaching the given base class
1205/// specifiers to a C++ class.
1206bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1207 unsigned NumBases) {
1208 if (NumBases == 0)
1209 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001210
1211 // Used to keep track of which base types we have already seen, so
1212 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001213 // that the key is always the unqualified canonical type of the base
1214 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001215 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1216
1217 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001218 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001219 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001220 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001221 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001222 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001223 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001224
1225 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1226 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001227 // C++ [class.mi]p3:
1228 // A class shall not be specified as a direct base class of a
1229 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001230 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001231 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001232 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001233 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001234
1235 // Delete the duplicate base class specifier; we're going to
1236 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001237 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001238
1239 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001240 } else {
1241 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001242 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001243 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001244 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1245 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1246 if (Class->isInterface() &&
1247 (!RD->isInterface() ||
1248 KnownBase->getAccessSpecifier() != AS_public)) {
1249 // The Microsoft extension __interface does not permit bases that
1250 // are not themselves public interfaces.
1251 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1252 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1253 << RD->getSourceRange();
1254 Invalid = true;
1255 }
1256 if (RD->hasAttr<WeakAttr>())
1257 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1258 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001259 }
1260 }
1261
1262 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001263 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001264
1265 // Delete the remaining (good) base class specifiers, since their
1266 // data has been copied into the CXXRecordDecl.
1267 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001268 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001269
1270 return Invalid;
1271}
1272
1273/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1274/// class, after checking whether there are any duplicate base
1275/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001276void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001277 unsigned NumBases) {
1278 if (!ClassDecl || !Bases || !NumBases)
1279 return;
1280
1281 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001282 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001283 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001284}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001285
John McCall3cb0ebd2010-03-10 03:28:59 +00001286static CXXRecordDecl *GetClassForType(QualType T) {
1287 if (const RecordType *RT = T->getAs<RecordType>())
1288 return cast<CXXRecordDecl>(RT->getDecl());
1289 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1290 return ICT->getDecl();
1291 else
1292 return 0;
1293}
1294
Douglas Gregora8f32e02009-10-06 17:59:45 +00001295/// \brief Determine whether the type \p Derived is a C++ class that is
1296/// derived from the type \p Base.
1297bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001298 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001299 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001300
1301 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1302 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001303 return false;
1304
John McCall3cb0ebd2010-03-10 03:28:59 +00001305 CXXRecordDecl *BaseRD = GetClassForType(Base);
1306 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001307 return false;
1308
John McCall86ff3082010-02-04 22:26:26 +00001309 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1310 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001311}
1312
1313/// \brief Determine whether the type \p Derived is a C++ class that is
1314/// derived from the type \p Base.
1315bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001316 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001317 return false;
1318
John McCall3cb0ebd2010-03-10 03:28:59 +00001319 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1320 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001321 return false;
1322
John McCall3cb0ebd2010-03-10 03:28:59 +00001323 CXXRecordDecl *BaseRD = GetClassForType(Base);
1324 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001325 return false;
1326
Douglas Gregora8f32e02009-10-06 17:59:45 +00001327 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1328}
1329
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001330void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001331 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001332 assert(BasePathArray.empty() && "Base path array must be empty!");
1333 assert(Paths.isRecordingPaths() && "Must record paths!");
1334
1335 const CXXBasePath &Path = Paths.front();
1336
1337 // We first go backward and check if we have a virtual base.
1338 // FIXME: It would be better if CXXBasePath had the base specifier for
1339 // the nearest virtual base.
1340 unsigned Start = 0;
1341 for (unsigned I = Path.size(); I != 0; --I) {
1342 if (Path[I - 1].Base->isVirtual()) {
1343 Start = I - 1;
1344 break;
1345 }
1346 }
1347
1348 // Now add all bases.
1349 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001350 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001351}
1352
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001353/// \brief Determine whether the given base path includes a virtual
1354/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001355bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1356 for (CXXCastPath::const_iterator B = BasePath.begin(),
1357 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001358 B != BEnd; ++B)
1359 if ((*B)->isVirtual())
1360 return true;
1361
1362 return false;
1363}
1364
Douglas Gregora8f32e02009-10-06 17:59:45 +00001365/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1366/// conversion (where Derived and Base are class types) is
1367/// well-formed, meaning that the conversion is unambiguous (and
1368/// that all of the base classes are accessible). Returns true
1369/// and emits a diagnostic if the code is ill-formed, returns false
1370/// otherwise. Loc is the location where this routine should point to
1371/// if there is an error, and Range is the source range to highlight
1372/// if there is an error.
1373bool
1374Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001375 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001376 unsigned AmbigiousBaseConvID,
1377 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001378 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001379 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001380 // First, determine whether the path from Derived to Base is
1381 // ambiguous. This is slightly more expensive than checking whether
1382 // the Derived to Base conversion exists, because here we need to
1383 // explore multiple paths to determine if there is an ambiguity.
1384 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1385 /*DetectVirtual=*/false);
1386 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1387 assert(DerivationOkay &&
1388 "Can only be used with a derived-to-base conversion");
1389 (void)DerivationOkay;
1390
1391 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001392 if (InaccessibleBaseID) {
1393 // Check that the base class can be accessed.
1394 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1395 InaccessibleBaseID)) {
1396 case AR_inaccessible:
1397 return true;
1398 case AR_accessible:
1399 case AR_dependent:
1400 case AR_delayed:
1401 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001402 }
John McCall6b2accb2010-02-10 09:31:12 +00001403 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001404
1405 // Build a base path if necessary.
1406 if (BasePath)
1407 BuildBasePathArray(Paths, *BasePath);
1408 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001409 }
1410
1411 // We know that the derived-to-base conversion is ambiguous, and
1412 // we're going to produce a diagnostic. Perform the derived-to-base
1413 // search just one more time to compute all of the possible paths so
1414 // that we can print them out. This is more expensive than any of
1415 // the previous derived-to-base checks we've done, but at this point
1416 // performance isn't as much of an issue.
1417 Paths.clear();
1418 Paths.setRecordingPaths(true);
1419 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1420 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1421 (void)StillOkay;
1422
1423 // Build up a textual representation of the ambiguous paths, e.g.,
1424 // D -> B -> A, that will be used to illustrate the ambiguous
1425 // conversions in the diagnostic. We only print one of the paths
1426 // to each base class subobject.
1427 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1428
1429 Diag(Loc, AmbigiousBaseConvID)
1430 << Derived << Base << PathDisplayStr << Range << Name;
1431 return true;
1432}
1433
1434bool
1435Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001436 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001437 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001438 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001439 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001440 IgnoreAccess ? 0
1441 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001442 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001443 Loc, Range, DeclarationName(),
1444 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001445}
1446
1447
1448/// @brief Builds a string representing ambiguous paths from a
1449/// specific derived class to different subobjects of the same base
1450/// class.
1451///
1452/// This function builds a string that can be used in error messages
1453/// to show the different paths that one can take through the
1454/// inheritance hierarchy to go from the derived class to different
1455/// subobjects of a base class. The result looks something like this:
1456/// @code
1457/// struct D -> struct B -> struct A
1458/// struct D -> struct C -> struct A
1459/// @endcode
1460std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1461 std::string PathDisplayStr;
1462 std::set<unsigned> DisplayedPaths;
1463 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1464 Path != Paths.end(); ++Path) {
1465 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1466 // We haven't displayed a path to this particular base
1467 // class subobject yet.
1468 PathDisplayStr += "\n ";
1469 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1470 for (CXXBasePath::const_iterator Element = Path->begin();
1471 Element != Path->end(); ++Element)
1472 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1473 }
1474 }
1475
1476 return PathDisplayStr;
1477}
1478
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001479//===----------------------------------------------------------------------===//
1480// C++ class member Handling
1481//===----------------------------------------------------------------------===//
1482
Abramo Bagnara6206d532010-06-05 05:09:32 +00001483/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001484bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1485 SourceLocation ASLoc,
1486 SourceLocation ColonLoc,
1487 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001488 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001489 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001490 ASLoc, ColonLoc);
1491 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001492 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001493}
1494
Richard Smitha4b39652012-08-06 03:25:17 +00001495/// CheckOverrideControl - Check C++11 override control semantics.
1496void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001497 if (D->isInvalidDecl())
1498 return;
1499
Chris Lattner5f9e2722011-07-23 10:55:15 +00001500 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001501
Richard Smitha4b39652012-08-06 03:25:17 +00001502 // Do we know which functions this declaration might be overriding?
1503 bool OverridesAreKnown = !MD ||
1504 (!MD->getParent()->hasAnyDependentBases() &&
1505 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001506
Richard Smitha4b39652012-08-06 03:25:17 +00001507 if (!MD || !MD->isVirtual()) {
1508 if (OverridesAreKnown) {
1509 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1510 Diag(OA->getLocation(),
1511 diag::override_keyword_only_allowed_on_virtual_member_functions)
1512 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1513 D->dropAttr<OverrideAttr>();
1514 }
1515 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1516 Diag(FA->getLocation(),
1517 diag::override_keyword_only_allowed_on_virtual_member_functions)
1518 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1519 D->dropAttr<FinalAttr>();
1520 }
1521 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001522 return;
1523 }
Richard Smitha4b39652012-08-06 03:25:17 +00001524
1525 if (!OverridesAreKnown)
1526 return;
1527
1528 // C++11 [class.virtual]p5:
1529 // If a virtual function is marked with the virt-specifier override and
1530 // does not override a member function of a base class, the program is
1531 // ill-formed.
1532 bool HasOverriddenMethods =
1533 MD->begin_overridden_methods() != MD->end_overridden_methods();
1534 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1535 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1536 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001537}
1538
Richard Smitha4b39652012-08-06 03:25:17 +00001539/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001540/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001541/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001542bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1543 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001544 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001545 return false;
1546
1547 Diag(New->getLocation(), diag::err_final_function_overridden)
1548 << New->getDeclName();
1549 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1550 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001551}
1552
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001553static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001554 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1555 // FIXME: Destruction of ObjC lifetime types has side-effects.
1556 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1557 return !RD->isCompleteDefinition() ||
1558 !RD->hasTrivialDefaultConstructor() ||
1559 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001560 return false;
1561}
1562
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001563/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1564/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001565/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001566/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1567/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001568NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001569Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001570 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001571 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001572 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001573 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001574 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1575 DeclarationName Name = NameInfo.getName();
1576 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001577
1578 // For anonymous bitfields, the location should point to the type.
1579 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001580 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001581
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001582 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001583
John McCall4bde1e12010-06-04 08:34:12 +00001584 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001585 assert(!DS.isFriendSpecified());
1586
Richard Smith1ab0d902011-06-25 02:28:38 +00001587 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001588
John McCalle402e722012-09-25 07:32:39 +00001589 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1590 // The Microsoft extension __interface only permits public member functions
1591 // and prohibits constructors, destructors, operators, non-public member
1592 // functions, static methods and data members.
1593 unsigned InvalidDecl;
1594 bool ShowDeclName = true;
1595 if (!isFunc)
1596 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1597 else if (AS != AS_public)
1598 InvalidDecl = 2;
1599 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1600 InvalidDecl = 3;
1601 else switch (Name.getNameKind()) {
1602 case DeclarationName::CXXConstructorName:
1603 InvalidDecl = 4;
1604 ShowDeclName = false;
1605 break;
1606
1607 case DeclarationName::CXXDestructorName:
1608 InvalidDecl = 5;
1609 ShowDeclName = false;
1610 break;
1611
1612 case DeclarationName::CXXOperatorName:
1613 case DeclarationName::CXXConversionFunctionName:
1614 InvalidDecl = 6;
1615 break;
1616
1617 default:
1618 InvalidDecl = 0;
1619 break;
1620 }
1621
1622 if (InvalidDecl) {
1623 if (ShowDeclName)
1624 Diag(Loc, diag::err_invalid_member_in_interface)
1625 << (InvalidDecl-1) << Name;
1626 else
1627 Diag(Loc, diag::err_invalid_member_in_interface)
1628 << (InvalidDecl-1) << "";
1629 return 0;
1630 }
1631 }
1632
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001633 // C++ 9.2p6: A member shall not be declared to have automatic storage
1634 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001635 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1636 // data members and cannot be applied to names declared const or static,
1637 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001638 switch (DS.getStorageClassSpec()) {
1639 case DeclSpec::SCS_unspecified:
1640 case DeclSpec::SCS_typedef:
1641 case DeclSpec::SCS_static:
1642 // FALL THROUGH.
1643 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001644 case DeclSpec::SCS_mutable:
1645 if (isFunc) {
1646 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001647 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001648 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001649 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Sebastian Redla11f42f2008-11-17 23:24:37 +00001651 // FIXME: It would be nicer if the keyword was ignored only for this
1652 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001653 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001654 }
1655 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001656 default:
1657 if (DS.getStorageClassSpecLoc().isValid())
1658 Diag(DS.getStorageClassSpecLoc(),
1659 diag::err_storageclass_invalid_for_member);
1660 else
1661 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1662 D.getMutableDeclSpec().ClearStorageClassSpecs();
1663 }
1664
Sebastian Redl669d5d72008-11-14 23:42:31 +00001665 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1666 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001667 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001668
David Blaikie1d87fba2013-01-30 01:22:18 +00001669 if (DS.isConstexprSpecified() && isInstField) {
1670 SemaDiagnosticBuilder B =
1671 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1672 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1673 if (InitStyle == ICIS_NoInit) {
1674 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1675 D.getMutableDeclSpec().ClearConstexprSpec();
1676 const char *PrevSpec;
1677 unsigned DiagID;
1678 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1679 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001680 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001681 assert(!Failed && "Making a constexpr member const shouldn't fail");
1682 } else {
1683 B << 1;
1684 const char *PrevSpec;
1685 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001686 if (D.getMutableDeclSpec().SetStorageClassSpec(
1687 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001688 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001689 "This is the only DeclSpec that should fail to be applied");
1690 B << 1;
1691 } else {
1692 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1693 isInstField = false;
1694 }
1695 }
1696 }
1697
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001698 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001699 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001700 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001701
1702 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001703 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001704 Diag(Loc, diag::err_bad_variable_name)
1705 << Name;
1706 return 0;
1707 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001708
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001709 IdentifierInfo *II = Name.getAsIdentifierInfo();
1710
Douglas Gregorf2503652011-09-21 14:40:46 +00001711 // Member field could not be with "template" keyword.
1712 // So TemplateParameterLists should be empty in this case.
1713 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001714 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001715 if (TemplateParams->size()) {
1716 // There is no such thing as a member field template.
1717 Diag(D.getIdentifierLoc(), diag::err_template_member)
1718 << II
1719 << SourceRange(TemplateParams->getTemplateLoc(),
1720 TemplateParams->getRAngleLoc());
1721 } else {
1722 // There is an extraneous 'template<>' for this member.
1723 Diag(TemplateParams->getTemplateLoc(),
1724 diag::err_template_member_noparams)
1725 << II
1726 << SourceRange(TemplateParams->getTemplateLoc(),
1727 TemplateParams->getRAngleLoc());
1728 }
1729 return 0;
1730 }
1731
Douglas Gregor922fff22010-10-13 22:19:53 +00001732 if (SS.isSet() && !SS.isInvalid()) {
1733 // The user provided a superfluous scope specifier inside a class
1734 // definition:
1735 //
1736 // class X {
1737 // int X::member;
1738 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001739 if (DeclContext *DC = computeDeclContext(SS, false))
1740 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001741 else
1742 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1743 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001744
Douglas Gregor922fff22010-10-13 22:19:53 +00001745 SS.clear();
1746 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001747
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001748 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001749 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001750 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001751 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001752 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001753
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001754 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001755 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001756 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001757 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001758
1759 // Non-instance-fields can't have a bitfield.
1760 if (BitWidth) {
1761 if (Member->isInvalidDecl()) {
1762 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001763 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001764 // C++ 9.6p3: A bit-field shall not be a static member.
1765 // "static member 'A' cannot be a bit-field"
1766 Diag(Loc, diag::err_static_not_bitfield)
1767 << Name << BitWidth->getSourceRange();
1768 } else if (isa<TypedefDecl>(Member)) {
1769 // "typedef member 'x' cannot be a bit-field"
1770 Diag(Loc, diag::err_typedef_not_bitfield)
1771 << Name << BitWidth->getSourceRange();
1772 } else {
1773 // A function typedef ("typedef int f(); f a;").
1774 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1775 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001776 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001777 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001778 }
Mike Stump1eb44332009-09-09 15:08:12 +00001779
Chris Lattner8b963ef2009-03-05 23:01:03 +00001780 BitWidth = 0;
1781 Member->setInvalidDecl();
1782 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001783
1784 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Douglas Gregor37b372b2009-08-20 22:52:58 +00001786 // If we have declared a member function template, set the access of the
1787 // templated declaration as well.
1788 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1789 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001790 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001791
Richard Smitha4b39652012-08-06 03:25:17 +00001792 if (VS.isOverrideSpecified())
1793 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1794 if (VS.isFinalSpecified())
1795 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001796
Douglas Gregorf5251602011-03-08 17:10:18 +00001797 if (VS.getLastLocation().isValid()) {
1798 // Update the end location of a method that has a virt-specifiers.
1799 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1800 MD->setRangeEnd(VS.getLastLocation());
1801 }
Richard Smitha4b39652012-08-06 03:25:17 +00001802
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001803 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001804
Douglas Gregor10bd3682008-11-17 22:58:34 +00001805 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001806
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001807 if (isInstField) {
1808 FieldDecl *FD = cast<FieldDecl>(Member);
1809 FieldCollector->Add(FD);
1810
1811 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1812 FD->getLocation())
1813 != DiagnosticsEngine::Ignored) {
1814 // Remember all explicit private FieldDecls that have a name, no side
1815 // effects and are not part of a dependent type declaration.
1816 if (!FD->isImplicit() && FD->getDeclName() &&
1817 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001818 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001819 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001820 !InitializationHasSideEffects(*FD))
1821 UnusedPrivateFields.insert(FD);
1822 }
1823 }
1824
John McCalld226f652010-08-21 09:40:31 +00001825 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001826}
1827
Hans Wennborg471f9852012-09-18 15:58:06 +00001828namespace {
1829 class UninitializedFieldVisitor
1830 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1831 Sema &S;
1832 ValueDecl *VD;
1833 public:
1834 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1835 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001836 S(S) {
1837 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1838 this->VD = IFD->getAnonField();
1839 else
1840 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001841 }
1842
1843 void HandleExpr(Expr *E) {
1844 if (!E) return;
1845
1846 // Expressions like x(x) sometimes lack the surrounding expressions
1847 // but need to be checked anyways.
1848 HandleValue(E);
1849 Visit(E);
1850 }
1851
1852 void HandleValue(Expr *E) {
1853 E = E->IgnoreParens();
1854
1855 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1856 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001857 return;
1858
1859 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1860 // or union.
1861 MemberExpr *FieldME = ME;
1862
Hans Wennborg471f9852012-09-18 15:58:06 +00001863 Expr *Base = E;
1864 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001865 ME = cast<MemberExpr>(Base);
1866
1867 if (isa<VarDecl>(ME->getMemberDecl()))
1868 return;
1869
1870 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1871 if (!FD->isAnonymousStructOrUnion())
1872 FieldME = ME;
1873
Hans Wennborg471f9852012-09-18 15:58:06 +00001874 Base = ME->getBase();
1875 }
1876
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001877 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00001878 unsigned diag = VD->getType()->isReferenceType()
1879 ? diag::warn_reference_field_is_uninit
1880 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001881 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001882 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001883 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00001884 }
1885
1886 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1887 HandleValue(CO->getTrueExpr());
1888 HandleValue(CO->getFalseExpr());
1889 return;
1890 }
1891
1892 if (BinaryConditionalOperator *BCO =
1893 dyn_cast<BinaryConditionalOperator>(E)) {
1894 HandleValue(BCO->getCommon());
1895 HandleValue(BCO->getFalseExpr());
1896 return;
1897 }
1898
1899 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1900 switch (BO->getOpcode()) {
1901 default:
1902 return;
1903 case(BO_PtrMemD):
1904 case(BO_PtrMemI):
1905 HandleValue(BO->getLHS());
1906 return;
1907 case(BO_Comma):
1908 HandleValue(BO->getRHS());
1909 return;
1910 }
1911 }
1912 }
1913
1914 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1915 if (E->getCastKind() == CK_LValueToRValue)
1916 HandleValue(E->getSubExpr());
1917
1918 Inherited::VisitImplicitCastExpr(E);
1919 }
1920
1921 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1922 Expr *Callee = E->getCallee();
1923 if (isa<MemberExpr>(Callee))
1924 HandleValue(Callee);
1925
1926 Inherited::VisitCXXMemberCallExpr(E);
1927 }
1928 };
1929 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1930 ValueDecl *VD) {
1931 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1932 }
1933} // namespace
1934
Richard Smith7a614d82011-06-11 17:19:42 +00001935/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001936/// in-class initializer for a non-static C++ class member, and after
1937/// instantiating an in-class initializer in a class template. Such actions
1938/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001939void
Richard Smithca523302012-06-10 03:12:00 +00001940Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001941 Expr *InitExpr) {
1942 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001943 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1944 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001945
1946 if (!InitExpr) {
1947 FD->setInvalidDecl();
1948 FD->removeInClassInitializer();
1949 return;
1950 }
1951
Peter Collingbournefef21892011-10-23 18:59:44 +00001952 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1953 FD->setInvalidDecl();
1954 FD->removeInClassInitializer();
1955 return;
1956 }
1957
Hans Wennborg471f9852012-09-18 15:58:06 +00001958 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1959 != DiagnosticsEngine::Ignored) {
1960 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1961 }
1962
Richard Smith7a614d82011-06-11 17:19:42 +00001963 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00001964 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001965 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001966 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001967 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1968 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001969 Expr **Inits = &InitExpr;
1970 unsigned NumInits = 1;
1971 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00001972 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00001973 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00001974 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00001975 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1976 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001977 if (Init.isInvalid()) {
1978 FD->setInvalidDecl();
1979 return;
1980 }
Richard Smith7a614d82011-06-11 17:19:42 +00001981 }
1982
Richard Smith41956372013-01-14 22:39:08 +00001983 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00001984 // The initialization of each base and member constitutes a
1985 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00001986 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00001987 if (Init.isInvalid()) {
1988 FD->setInvalidDecl();
1989 return;
1990 }
1991
1992 InitExpr = Init.release();
1993
1994 FD->setInClassInitializer(InitExpr);
1995}
1996
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001997/// \brief Find the direct and/or virtual base specifiers that
1998/// correspond to the given base type, for use in base initialization
1999/// within a constructor.
2000static bool FindBaseInitializer(Sema &SemaRef,
2001 CXXRecordDecl *ClassDecl,
2002 QualType BaseType,
2003 const CXXBaseSpecifier *&DirectBaseSpec,
2004 const CXXBaseSpecifier *&VirtualBaseSpec) {
2005 // First, check for a direct base class.
2006 DirectBaseSpec = 0;
2007 for (CXXRecordDecl::base_class_const_iterator Base
2008 = ClassDecl->bases_begin();
2009 Base != ClassDecl->bases_end(); ++Base) {
2010 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2011 // We found a direct base of this type. That's what we're
2012 // initializing.
2013 DirectBaseSpec = &*Base;
2014 break;
2015 }
2016 }
2017
2018 // Check for a virtual base class.
2019 // FIXME: We might be able to short-circuit this if we know in advance that
2020 // there are no virtual bases.
2021 VirtualBaseSpec = 0;
2022 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2023 // We haven't found a base yet; search the class hierarchy for a
2024 // virtual base class.
2025 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2026 /*DetectVirtual=*/false);
2027 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2028 BaseType, Paths)) {
2029 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2030 Path != Paths.end(); ++Path) {
2031 if (Path->back().Base->isVirtual()) {
2032 VirtualBaseSpec = Path->back().Base;
2033 break;
2034 }
2035 }
2036 }
2037 }
2038
2039 return DirectBaseSpec || VirtualBaseSpec;
2040}
2041
Sebastian Redl6df65482011-09-24 17:48:25 +00002042/// \brief Handle a C++ member initializer using braced-init-list syntax.
2043MemInitResult
2044Sema::ActOnMemInitializer(Decl *ConstructorD,
2045 Scope *S,
2046 CXXScopeSpec &SS,
2047 IdentifierInfo *MemberOrBase,
2048 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002049 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002050 SourceLocation IdLoc,
2051 Expr *InitList,
2052 SourceLocation EllipsisLoc) {
2053 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002054 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002055 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002056}
2057
2058/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002059MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002060Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002061 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002062 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002063 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002064 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002065 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002066 SourceLocation IdLoc,
2067 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002068 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002069 SourceLocation RParenLoc,
2070 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002071 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2072 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002073 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002074 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002075 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002076}
2077
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002078namespace {
2079
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002080// Callback to only accept typo corrections that can be a valid C++ member
2081// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002082class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2083 public:
2084 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2085 : ClassDecl(ClassDecl) {}
2086
2087 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2088 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2089 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2090 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2091 else
2092 return isa<TypeDecl>(ND);
2093 }
2094 return false;
2095 }
2096
2097 private:
2098 CXXRecordDecl *ClassDecl;
2099};
2100
2101}
2102
Sebastian Redl6df65482011-09-24 17:48:25 +00002103/// \brief Handle a C++ member initializer.
2104MemInitResult
2105Sema::BuildMemInitializer(Decl *ConstructorD,
2106 Scope *S,
2107 CXXScopeSpec &SS,
2108 IdentifierInfo *MemberOrBase,
2109 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002110 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002111 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002112 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002113 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002114 if (!ConstructorD)
2115 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002116
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002117 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002118
2119 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002120 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002121 if (!Constructor) {
2122 // The user wrote a constructor initializer on a function that is
2123 // not a C++ constructor. Ignore the error for now, because we may
2124 // have more member initializers coming; we'll diagnose it just
2125 // once in ActOnMemInitializers.
2126 return true;
2127 }
2128
2129 CXXRecordDecl *ClassDecl = Constructor->getParent();
2130
2131 // C++ [class.base.init]p2:
2132 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002133 // constructor's class and, if not found in that scope, are looked
2134 // up in the scope containing the constructor's definition.
2135 // [Note: if the constructor's class contains a member with the
2136 // same name as a direct or virtual base class of the class, a
2137 // mem-initializer-id naming the member or base class and composed
2138 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002139 // mem-initializer-id for the hidden base class may be specified
2140 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002141 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002142 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002143 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002144 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002145 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002146 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002147 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2148 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002149 if (EllipsisLoc.isValid())
2150 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002151 << MemberOrBase
2152 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002153
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002154 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002155 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002156 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002157 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002158 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002159 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002160 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002161
2162 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002163 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002164 } else if (DS.getTypeSpecType() == TST_decltype) {
2165 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002166 } else {
2167 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2168 LookupParsedName(R, S, &SS);
2169
2170 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2171 if (!TyD) {
2172 if (R.isAmbiguous()) return true;
2173
John McCallfd225442010-04-09 19:01:14 +00002174 // We don't want access-control diagnostics here.
2175 R.suppressDiagnostics();
2176
Douglas Gregor7a886e12010-01-19 06:46:48 +00002177 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2178 bool NotUnknownSpecialization = false;
2179 DeclContext *DC = computeDeclContext(SS, false);
2180 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2181 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2182
2183 if (!NotUnknownSpecialization) {
2184 // When the scope specifier can refer to a member of an unknown
2185 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002186 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2187 SS.getWithLocInContext(Context),
2188 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002189 if (BaseType.isNull())
2190 return true;
2191
Douglas Gregor7a886e12010-01-19 06:46:48 +00002192 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002193 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002194 }
2195 }
2196
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002197 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002198 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002199 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002200 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002201 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002202 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002203 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2204 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002205 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002206 // We have found a non-static data member with a similar
2207 // name to what was typed; complain and initialize that
2208 // member.
2209 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2210 << MemberOrBase << true << CorrectedQuotedStr
2211 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2212 Diag(Member->getLocation(), diag::note_previous_decl)
2213 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002214
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002215 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002216 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002217 const CXXBaseSpecifier *DirectBaseSpec;
2218 const CXXBaseSpecifier *VirtualBaseSpec;
2219 if (FindBaseInitializer(*this, ClassDecl,
2220 Context.getTypeDeclType(Type),
2221 DirectBaseSpec, VirtualBaseSpec)) {
2222 // We have found a direct or virtual base class with a
2223 // similar name to what was typed; complain and initialize
2224 // that base class.
2225 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002226 << MemberOrBase << false << CorrectedQuotedStr
2227 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002228
2229 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2230 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002231 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002232 diag::note_base_class_specified_here)
2233 << BaseSpec->getType()
2234 << BaseSpec->getSourceRange();
2235
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002236 TyD = Type;
2237 }
2238 }
2239 }
2240
Douglas Gregor7a886e12010-01-19 06:46:48 +00002241 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002242 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002243 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002244 return true;
2245 }
John McCall2b194412009-12-21 10:41:20 +00002246 }
2247
Douglas Gregor7a886e12010-01-19 06:46:48 +00002248 if (BaseType.isNull()) {
2249 BaseType = Context.getTypeDeclType(TyD);
2250 if (SS.isSet()) {
2251 NestedNameSpecifier *Qualifier =
2252 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002253
Douglas Gregor7a886e12010-01-19 06:46:48 +00002254 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002255 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002256 }
John McCall2b194412009-12-21 10:41:20 +00002257 }
2258 }
Mike Stump1eb44332009-09-09 15:08:12 +00002259
John McCalla93c9342009-12-07 02:54:59 +00002260 if (!TInfo)
2261 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002262
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002263 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002264}
2265
Chandler Carruth81c64772011-09-03 01:14:15 +00002266/// Checks a member initializer expression for cases where reference (or
2267/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002268static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2269 Expr *Init,
2270 SourceLocation IdLoc) {
2271 QualType MemberTy = Member->getType();
2272
2273 // We only handle pointers and references currently.
2274 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2275 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2276 return;
2277
2278 const bool IsPointer = MemberTy->isPointerType();
2279 if (IsPointer) {
2280 if (const UnaryOperator *Op
2281 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2282 // The only case we're worried about with pointers requires taking the
2283 // address.
2284 if (Op->getOpcode() != UO_AddrOf)
2285 return;
2286
2287 Init = Op->getSubExpr();
2288 } else {
2289 // We only handle address-of expression initializers for pointers.
2290 return;
2291 }
2292 }
2293
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002294 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2295 // Taking the address of a temporary will be diagnosed as a hard error.
2296 if (IsPointer)
2297 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002298
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002299 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2300 << Member << Init->getSourceRange();
2301 } else if (const DeclRefExpr *DRE
2302 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2303 // We only warn when referring to a non-reference parameter declaration.
2304 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2305 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002306 return;
2307
2308 S.Diag(Init->getExprLoc(),
2309 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2310 : diag::warn_bind_ref_member_to_parameter)
2311 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002312 } else {
2313 // Other initializers are fine.
2314 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002315 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002316
2317 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2318 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002319}
2320
John McCallf312b1e2010-08-26 23:41:50 +00002321MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002322Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002323 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002324 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2325 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2326 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002327 "Member must be a FieldDecl or IndirectFieldDecl");
2328
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002329 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002330 return true;
2331
Douglas Gregor464b2f02010-11-05 22:21:31 +00002332 if (Member->isInvalidDecl())
2333 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002334
John McCallb4190042009-11-04 23:02:40 +00002335 // Diagnose value-uses of fields to initialize themselves, e.g.
2336 // foo(foo)
2337 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002338 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002339 Expr **Args;
2340 unsigned NumArgs;
2341 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2342 Args = ParenList->getExprs();
2343 NumArgs = ParenList->getNumExprs();
Richard Smithc83c2302012-12-19 01:39:02 +00002344 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002345 Args = InitList->getInits();
2346 NumArgs = InitList->getNumInits();
Richard Smithc83c2302012-12-19 01:39:02 +00002347 } else {
2348 // Template instantiation doesn't reconstruct ParenListExprs for us.
2349 Args = &Init;
2350 NumArgs = 1;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002351 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002352
Richard Trieude5e75c2012-06-14 23:11:34 +00002353 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2354 != DiagnosticsEngine::Ignored)
2355 for (unsigned i = 0; i < NumArgs; ++i)
2356 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002357 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002358 // initializing the i'th field, throw a warning if any of the >= i'th
2359 // fields are used, as they are not yet initialized.
2360 // Right now we are only handling the case where the i'th field uses
2361 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002362 // Also need to take into account that some fields may be initialized by
2363 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002364 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002365
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002366 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002367
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002368 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002369 // Can't check initialization for a member of dependent type or when
2370 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002371 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002372 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002373 bool InitList = false;
2374 if (isa<InitListExpr>(Init)) {
2375 InitList = true;
2376 Args = &Init;
2377 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002378
2379 if (isStdInitializerList(Member->getType(), 0)) {
2380 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2381 << /*at end of ctor*/1 << InitRange;
2382 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002383 }
2384
Chandler Carruth894aed92010-12-06 09:23:57 +00002385 // Initialize the member.
2386 InitializedEntity MemberEntity =
2387 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2388 : InitializedEntity::InitializeMember(IndirectMember, 0);
2389 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002390 InitList ? InitializationKind::CreateDirectList(IdLoc)
2391 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2392 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002393
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002394 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2395 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002396 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002397 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002398 if (MemberInit.isInvalid())
2399 return true;
2400
Richard Smith41956372013-01-14 22:39:08 +00002401 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002402 // The initialization of each base and member constitutes a
2403 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002404 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002405 if (MemberInit.isInvalid())
2406 return true;
2407
Richard Smithc83c2302012-12-19 01:39:02 +00002408 Init = MemberInit.get();
2409 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002410 }
2411
Chandler Carruth894aed92010-12-06 09:23:57 +00002412 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002413 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2414 InitRange.getBegin(), Init,
2415 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002416 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002417 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2418 InitRange.getBegin(), Init,
2419 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002420 }
Eli Friedman59c04372009-07-29 19:44:27 +00002421}
2422
John McCallf312b1e2010-08-26 23:41:50 +00002423MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002424Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002425 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002426 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002427 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002428 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002429 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002430 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002431
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002432 bool InitList = true;
2433 Expr **Args = &Init;
2434 unsigned NumArgs = 1;
2435 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2436 InitList = false;
2437 Args = ParenList->getExprs();
2438 NumArgs = ParenList->getNumExprs();
2439 }
2440
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002441 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002442 // Initialize the object.
2443 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2444 QualType(ClassDecl->getTypeForDecl(), 0));
2445 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002446 InitList ? InitializationKind::CreateDirectList(NameLoc)
2447 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2448 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002449 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2450 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002451 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002452 0);
Sean Hunt41717662011-02-26 19:13:13 +00002453 if (DelegationInit.isInvalid())
2454 return true;
2455
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002456 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2457 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002458
Richard Smith41956372013-01-14 22:39:08 +00002459 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002460 // The initialization of each base and member constitutes a
2461 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002462 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2463 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002464 if (DelegationInit.isInvalid())
2465 return true;
2466
Eli Friedmand21016f2012-05-19 23:35:23 +00002467 // If we are in a dependent context, template instantiation will
2468 // perform this type-checking again. Just save the arguments that we
2469 // received in a ParenListExpr.
2470 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2471 // of the information that we have about the base
2472 // initializer. However, deconstructing the ASTs is a dicey process,
2473 // and this approach is far more likely to get the corner cases right.
2474 if (CurContext->isDependentContext())
2475 DelegationInit = Owned(Init);
2476
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002477 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002478 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002479 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002480}
2481
2482MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002483Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002484 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002485 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002486 SourceLocation BaseLoc
2487 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002488
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002489 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2490 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2491 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2492
2493 // C++ [class.base.init]p2:
2494 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002495 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002496 // of that class, the mem-initializer is ill-formed. A
2497 // mem-initializer-list can initialize a base class using any
2498 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002499 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002500
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002501 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002502 if (EllipsisLoc.isValid()) {
2503 // This is a pack expansion.
2504 if (!BaseType->containsUnexpandedParameterPack()) {
2505 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002506 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002507
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002508 EllipsisLoc = SourceLocation();
2509 }
2510 } else {
2511 // Check for any unexpanded parameter packs.
2512 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2513 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002514
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002515 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002516 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002517 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002518
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002519 // Check for direct and virtual base classes.
2520 const CXXBaseSpecifier *DirectBaseSpec = 0;
2521 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2522 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002523 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2524 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002525 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002526
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002527 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2528 VirtualBaseSpec);
2529
2530 // C++ [base.class.init]p2:
2531 // Unless the mem-initializer-id names a nonstatic data member of the
2532 // constructor's class or a direct or virtual base of that class, the
2533 // mem-initializer is ill-formed.
2534 if (!DirectBaseSpec && !VirtualBaseSpec) {
2535 // If the class has any dependent bases, then it's possible that
2536 // one of those types will resolve to the same type as
2537 // BaseType. Therefore, just treat this as a dependent base
2538 // class initialization. FIXME: Should we try to check the
2539 // initialization anyway? It seems odd.
2540 if (ClassDecl->hasAnyDependentBases())
2541 Dependent = true;
2542 else
2543 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2544 << BaseType << Context.getTypeDeclType(ClassDecl)
2545 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2546 }
2547 }
2548
2549 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002550 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002551
Sebastian Redl6df65482011-09-24 17:48:25 +00002552 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2553 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002554 InitRange.getBegin(), Init,
2555 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002556 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002557
2558 // C++ [base.class.init]p2:
2559 // If a mem-initializer-id is ambiguous because it designates both
2560 // a direct non-virtual base class and an inherited virtual base
2561 // class, the mem-initializer is ill-formed.
2562 if (DirectBaseSpec && VirtualBaseSpec)
2563 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002564 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002565
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002566 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002567 if (!BaseSpec)
2568 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2569
2570 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002571 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002572 Expr **Args = &Init;
2573 unsigned NumArgs = 1;
2574 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002575 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002576 Args = ParenList->getExprs();
2577 NumArgs = ParenList->getNumExprs();
2578 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002579
2580 InitializedEntity BaseEntity =
2581 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2582 InitializationKind Kind =
2583 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2584 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2585 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002586 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2587 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002588 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002589 if (BaseInit.isInvalid())
2590 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002591
Richard Smith41956372013-01-14 22:39:08 +00002592 // C++11 [class.base.init]p7:
2593 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002594 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002595 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002596 if (BaseInit.isInvalid())
2597 return true;
2598
2599 // If we are in a dependent context, template instantiation will
2600 // perform this type-checking again. Just save the arguments that we
2601 // received in a ParenListExpr.
2602 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2603 // of the information that we have about the base
2604 // initializer. However, deconstructing the ASTs is a dicey process,
2605 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002606 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002607 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002608
Sean Huntcbb67482011-01-08 20:30:50 +00002609 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002610 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002611 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002612 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002613 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002614}
2615
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002616// Create a static_cast\<T&&>(expr).
2617static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2618 QualType ExprType = E->getType();
2619 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2620 SourceLocation ExprLoc = E->getLocStart();
2621 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2622 TargetType, ExprLoc);
2623
2624 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2625 SourceRange(ExprLoc, ExprLoc),
2626 E->getSourceRange()).take();
2627}
2628
Anders Carlssone5ef7402010-04-23 03:10:23 +00002629/// ImplicitInitializerKind - How an implicit base or member initializer should
2630/// initialize its base or member.
2631enum ImplicitInitializerKind {
2632 IIK_Default,
2633 IIK_Copy,
2634 IIK_Move
2635};
2636
Anders Carlssondefefd22010-04-23 02:00:02 +00002637static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002638BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002639 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002640 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002641 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002642 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002643 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002644 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2645 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002646
John McCall60d7b3a2010-08-24 06:29:42 +00002647 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002648
2649 switch (ImplicitInitKind) {
2650 case IIK_Default: {
2651 InitializationKind InitKind
2652 = InitializationKind::CreateDefault(Constructor->getLocation());
2653 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002654 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002655 break;
2656 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002657
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002658 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002659 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002660 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002661 ParmVarDecl *Param = Constructor->getParamDecl(0);
2662 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002663
Anders Carlssone5ef7402010-04-23 03:10:23 +00002664 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002665 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002666 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002667 Constructor->getLocation(), ParamType,
2668 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002669
Eli Friedman5f2987c2012-02-02 03:46:19 +00002670 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2671
Anders Carlssonc7957502010-04-24 22:02:54 +00002672 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002673 QualType ArgTy =
2674 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2675 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002676
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002677 if (Moving) {
2678 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2679 }
2680
John McCallf871d0c2010-08-07 06:22:56 +00002681 CXXCastPath BasePath;
2682 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002683 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2684 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002685 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002686 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002687
Anders Carlssone5ef7402010-04-23 03:10:23 +00002688 InitializationKind InitKind
2689 = InitializationKind::CreateDirect(Constructor->getLocation(),
2690 SourceLocation(), SourceLocation());
2691 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2692 &CopyCtorArg, 1);
2693 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002694 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002695 break;
2696 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002697 }
John McCall9ae2f072010-08-23 23:25:46 +00002698
Douglas Gregor53c374f2010-12-07 00:41:46 +00002699 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002700 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002701 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002702
Anders Carlssondefefd22010-04-23 02:00:02 +00002703 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002704 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002705 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2706 SourceLocation()),
2707 BaseSpec->isVirtual(),
2708 SourceLocation(),
2709 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002710 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002711 SourceLocation());
2712
Anders Carlssondefefd22010-04-23 02:00:02 +00002713 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002714}
2715
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002716static bool RefersToRValueRef(Expr *MemRef) {
2717 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2718 return Referenced->getType()->isRValueReferenceType();
2719}
2720
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002721static bool
2722BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002723 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002724 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002725 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002726 if (Field->isInvalidDecl())
2727 return true;
2728
Chandler Carruthf186b542010-06-29 23:50:44 +00002729 SourceLocation Loc = Constructor->getLocation();
2730
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002731 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2732 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002733 ParmVarDecl *Param = Constructor->getParamDecl(0);
2734 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002735
2736 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002737 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2738 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002739
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002740 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002741 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002742 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002743 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002744
Eli Friedman5f2987c2012-02-02 03:46:19 +00002745 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2746
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002747 if (Moving) {
2748 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2749 }
2750
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002751 // Build a reference to this field within the parameter.
2752 CXXScopeSpec SS;
2753 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2754 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002755 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2756 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002757 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002758 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002759 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002760 ParamType, Loc,
2761 /*IsArrow=*/false,
2762 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002763 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002764 /*FirstQualifierInScope=*/0,
2765 MemberLookup,
2766 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002767 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002768 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002769
2770 // C++11 [class.copy]p15:
2771 // - if a member m has rvalue reference type T&&, it is direct-initialized
2772 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002773 if (RefersToRValueRef(CtorArg.get())) {
2774 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002775 }
2776
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002777 // When the field we are copying is an array, create index variables for
2778 // each dimension of the array. We use these index variables to subscript
2779 // the source array, and other clients (e.g., CodeGen) will perform the
2780 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002781 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002782 QualType BaseType = Field->getType();
2783 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002784 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002785 while (const ConstantArrayType *Array
2786 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002787 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002788 // Create the iteration variable for this array index.
2789 IdentifierInfo *IterationVarName = 0;
2790 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002791 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002792 llvm::raw_svector_ostream OS(Str);
2793 OS << "__i" << IndexVariables.size();
2794 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2795 }
2796 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002797 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002798 IterationVarName, SizeType,
2799 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002800 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002801 IndexVariables.push_back(IterationVar);
2802
2803 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002804 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002805 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002806 assert(!IterationVarRef.isInvalid() &&
2807 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002808 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2809 assert(!IterationVarRef.isInvalid() &&
2810 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002811
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002812 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002813 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002814 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002815 Loc);
2816 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002817 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002818
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002819 BaseType = Array->getElementType();
2820 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002821
2822 // The array subscript expression is an lvalue, which is wrong for moving.
2823 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002824 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002825
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002826 // Construct the entity that we will be initializing. For an array, this
2827 // will be first element in the array, which may require several levels
2828 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002829 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002830 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002831 if (Indirect)
2832 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2833 else
2834 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002835 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2836 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2837 0,
2838 Entities.back()));
2839
2840 // Direct-initialize to use the copy constructor.
2841 InitializationKind InitKind =
2842 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2843
Sebastian Redl74e611a2011-09-04 18:14:28 +00002844 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002845 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002846 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002847
John McCall60d7b3a2010-08-24 06:29:42 +00002848 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002849 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002850 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002851 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002852 if (MemberInit.isInvalid())
2853 return true;
2854
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002855 if (Indirect) {
2856 assert(IndexVariables.size() == 0 &&
2857 "Indirect field improperly initialized");
2858 CXXMemberInit
2859 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2860 Loc, Loc,
2861 MemberInit.takeAs<Expr>(),
2862 Loc);
2863 } else
2864 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2865 Loc, MemberInit.takeAs<Expr>(),
2866 Loc,
2867 IndexVariables.data(),
2868 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002869 return false;
2870 }
2871
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002872 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2873
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002874 QualType FieldBaseElementType =
2875 SemaRef.Context.getBaseElementType(Field->getType());
2876
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002877 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002878 InitializedEntity InitEntity
2879 = Indirect? InitializedEntity::InitializeMember(Indirect)
2880 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002881 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002882 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002883
2884 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002885 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002886 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002887
Douglas Gregor53c374f2010-12-07 00:41:46 +00002888 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002889 if (MemberInit.isInvalid())
2890 return true;
2891
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002892 if (Indirect)
2893 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2894 Indirect, Loc,
2895 Loc,
2896 MemberInit.get(),
2897 Loc);
2898 else
2899 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2900 Field, Loc, Loc,
2901 MemberInit.get(),
2902 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002903 return false;
2904 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002905
Sean Hunt1f2f3842011-05-17 00:19:05 +00002906 if (!Field->getParent()->isUnion()) {
2907 if (FieldBaseElementType->isReferenceType()) {
2908 SemaRef.Diag(Constructor->getLocation(),
2909 diag::err_uninitialized_member_in_ctor)
2910 << (int)Constructor->isImplicit()
2911 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2912 << 0 << Field->getDeclName();
2913 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2914 return true;
2915 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002916
Sean Hunt1f2f3842011-05-17 00:19:05 +00002917 if (FieldBaseElementType.isConstQualified()) {
2918 SemaRef.Diag(Constructor->getLocation(),
2919 diag::err_uninitialized_member_in_ctor)
2920 << (int)Constructor->isImplicit()
2921 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2922 << 1 << Field->getDeclName();
2923 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2924 return true;
2925 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002926 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002927
David Blaikie4e4d0842012-03-11 07:00:24 +00002928 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002929 FieldBaseElementType->isObjCRetainableType() &&
2930 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2931 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002932 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002933 // Default-initialize Objective-C pointers to NULL.
2934 CXXMemberInit
2935 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2936 Loc, Loc,
2937 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2938 Loc);
2939 return false;
2940 }
2941
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002942 // Nothing to initialize.
2943 CXXMemberInit = 0;
2944 return false;
2945}
John McCallf1860e52010-05-20 23:23:51 +00002946
2947namespace {
2948struct BaseAndFieldInfo {
2949 Sema &S;
2950 CXXConstructorDecl *Ctor;
2951 bool AnyErrorsInInits;
2952 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002953 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002954 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002955
2956 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2957 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002958 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2959 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002960 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002961 else if (Generated && Ctor->isMoveConstructor())
2962 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002963 else
2964 IIK = IIK_Default;
2965 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002966
2967 bool isImplicitCopyOrMove() const {
2968 switch (IIK) {
2969 case IIK_Copy:
2970 case IIK_Move:
2971 return true;
2972
2973 case IIK_Default:
2974 return false;
2975 }
David Blaikie30263482012-01-20 21:50:17 +00002976
2977 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002978 }
Richard Smith0b8220a2012-08-07 21:30:42 +00002979
2980 bool addFieldInitializer(CXXCtorInitializer *Init) {
2981 AllToInit.push_back(Init);
2982
2983 // Check whether this initializer makes the field "used".
2984 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2985 S.UnusedPrivateFields.remove(Init->getAnyMember());
2986
2987 return false;
2988 }
John McCallf1860e52010-05-20 23:23:51 +00002989};
2990}
2991
Richard Smitha4950662011-09-19 13:34:43 +00002992/// \brief Determine whether the given indirect field declaration is somewhere
2993/// within an anonymous union.
2994static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2995 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2996 CEnd = F->chain_end();
2997 C != CEnd; ++C)
2998 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2999 if (Record->isUnion())
3000 return true;
3001
3002 return false;
3003}
3004
Douglas Gregorddb21472011-11-02 23:04:16 +00003005/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3006/// array type.
3007static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3008 if (T->isIncompleteArrayType())
3009 return true;
3010
3011 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3012 if (!ArrayT->getSize())
3013 return true;
3014
3015 T = ArrayT->getElementType();
3016 }
3017
3018 return false;
3019}
3020
Richard Smith7a614d82011-06-11 17:19:42 +00003021static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003022 FieldDecl *Field,
3023 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003024
Chandler Carruthe861c602010-06-30 02:59:29 +00003025 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003026 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3027 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003028
Richard Smith0b8220a2012-08-07 21:30:42 +00003029 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003030 // has a brace-or-equal-initializer, the entity is initialized as specified
3031 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003032 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003033 CXXCtorInitializer *Init;
3034 if (Indirect)
3035 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3036 SourceLocation(),
3037 SourceLocation(), 0,
3038 SourceLocation());
3039 else
3040 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3041 SourceLocation(),
3042 SourceLocation(), 0,
3043 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003044 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003045 }
3046
Richard Smithc115f632011-09-18 11:14:50 +00003047 // Don't build an implicit initializer for union members if none was
3048 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003049 if (Field->getParent()->isUnion() ||
3050 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003051 return false;
3052
Douglas Gregorddb21472011-11-02 23:04:16 +00003053 // Don't initialize incomplete or zero-length arrays.
3054 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3055 return false;
3056
John McCallf1860e52010-05-20 23:23:51 +00003057 // Don't try to build an implicit initializer if there were semantic
3058 // errors in any of the initializers (and therefore we might be
3059 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003060 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003061 return false;
3062
Sean Huntcbb67482011-01-08 20:30:50 +00003063 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003064 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3065 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003066 return true;
John McCallf1860e52010-05-20 23:23:51 +00003067
Richard Smith0b8220a2012-08-07 21:30:42 +00003068 if (!Init)
3069 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003070
Richard Smith0b8220a2012-08-07 21:30:42 +00003071 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003072}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003073
3074bool
3075Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3076 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003077 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003078 Constructor->setNumCtorInitializers(1);
3079 CXXCtorInitializer **initializer =
3080 new (Context) CXXCtorInitializer*[1];
3081 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3082 Constructor->setCtorInitializers(initializer);
3083
Sean Huntb76af9c2011-05-03 23:05:34 +00003084 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003085 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003086 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3087 }
3088
Sean Huntc1598702011-05-05 00:05:47 +00003089 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003090
Sean Hunt059ce0d2011-05-01 07:04:31 +00003091 return false;
3092}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003093
David Blaikie93c86172013-01-17 05:26:25 +00003094bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3095 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003096 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003097 // Just store the initializers as written, they will be checked during
3098 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003099 if (!Initializers.empty()) {
3100 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003101 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003102 new (Context) CXXCtorInitializer*[Initializers.size()];
3103 memcpy(baseOrMemberInitializers, Initializers.data(),
3104 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003105 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003106 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003107
3108 // Let template instantiation know whether we had errors.
3109 if (AnyErrors)
3110 Constructor->setInvalidDecl();
3111
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003112 return false;
3113 }
3114
John McCallf1860e52010-05-20 23:23:51 +00003115 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003116
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003117 // We need to build the initializer AST according to order of construction
3118 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003119 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003120 if (!ClassDecl)
3121 return true;
3122
Eli Friedman80c30da2009-11-09 19:20:36 +00003123 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003124
David Blaikie93c86172013-01-17 05:26:25 +00003125 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003126 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003127
3128 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003129 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003130 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003131 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003132 }
3133
Anders Carlsson711f34a2010-04-21 19:52:01 +00003134 // Keep track of the direct virtual bases.
3135 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3136 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3137 E = ClassDecl->bases_end(); I != E; ++I) {
3138 if (I->isVirtual())
3139 DirectVBases.insert(I);
3140 }
3141
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003142 // Push virtual bases before others.
3143 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3144 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3145
Sean Huntcbb67482011-01-08 20:30:50 +00003146 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003147 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3148 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003149 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003150 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003151 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003152 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003153 VBase, IsInheritedVirtualBase,
3154 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003155 HadError = true;
3156 continue;
3157 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003158
John McCallf1860e52010-05-20 23:23:51 +00003159 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003160 }
3161 }
Mike Stump1eb44332009-09-09 15:08:12 +00003162
John McCallf1860e52010-05-20 23:23:51 +00003163 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003164 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3165 E = ClassDecl->bases_end(); Base != E; ++Base) {
3166 // Virtuals are in the virtual base list and already constructed.
3167 if (Base->isVirtual())
3168 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003169
Sean Huntcbb67482011-01-08 20:30:50 +00003170 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003171 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3172 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003173 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003174 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003175 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003176 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003177 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003178 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003179 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003180 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003181
John McCallf1860e52010-05-20 23:23:51 +00003182 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003183 }
3184 }
Mike Stump1eb44332009-09-09 15:08:12 +00003185
John McCallf1860e52010-05-20 23:23:51 +00003186 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003187 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3188 MemEnd = ClassDecl->decls_end();
3189 Mem != MemEnd; ++Mem) {
3190 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003191 // C++ [class.bit]p2:
3192 // A declaration for a bit-field that omits the identifier declares an
3193 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3194 // initialized.
3195 if (F->isUnnamedBitfield())
3196 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003197
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003198 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003199 // handle anonymous struct/union fields based on their individual
3200 // indirect fields.
3201 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3202 continue;
3203
3204 if (CollectFieldInitializer(*this, Info, F))
3205 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003206 continue;
3207 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003208
3209 // Beyond this point, we only consider default initialization.
3210 if (Info.IIK != IIK_Default)
3211 continue;
3212
3213 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3214 if (F->getType()->isIncompleteArrayType()) {
3215 assert(ClassDecl->hasFlexibleArrayMember() &&
3216 "Incomplete array type is not valid");
3217 continue;
3218 }
3219
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003220 // Initialize each field of an anonymous struct individually.
3221 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3222 HadError = true;
3223
3224 continue;
3225 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003226 }
Mike Stump1eb44332009-09-09 15:08:12 +00003227
David Blaikie93c86172013-01-17 05:26:25 +00003228 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003229 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003230 Constructor->setNumCtorInitializers(NumInitializers);
3231 CXXCtorInitializer **baseOrMemberInitializers =
3232 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003233 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003234 NumInitializers * sizeof(CXXCtorInitializer*));
3235 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003236
John McCallef027fe2010-03-16 21:39:52 +00003237 // Constructors implicitly reference the base and member
3238 // destructors.
3239 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3240 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003241 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003242
3243 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003244}
3245
David Blaikieee000bb2013-01-17 08:49:22 +00003246static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003247 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003248 const RecordDecl *RD = RT->getDecl();
3249 if (RD->isAnonymousStructOrUnion()) {
3250 for (RecordDecl::field_iterator Field = RD->field_begin(),
3251 E = RD->field_end(); Field != E; ++Field)
3252 PopulateKeysForFields(*Field, IdealInits);
3253 return;
3254 }
Eli Friedman6347f422009-07-21 19:28:10 +00003255 }
David Blaikieee000bb2013-01-17 08:49:22 +00003256 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003257}
3258
Anders Carlssonea356fb2010-04-02 05:42:15 +00003259static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003260 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003261}
3262
Anders Carlssonea356fb2010-04-02 05:42:15 +00003263static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003264 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003265 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003266 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003267
David Blaikieee000bb2013-01-17 08:49:22 +00003268 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003269}
3270
David Blaikie93c86172013-01-17 05:26:25 +00003271static void DiagnoseBaseOrMemInitializerOrder(
3272 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3273 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003274 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003275 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003276
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003277 // Don't check initializers order unless the warning is enabled at the
3278 // location of at least one initializer.
3279 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003280 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003281 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003282 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3283 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003284 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003285 ShouldCheckOrder = true;
3286 break;
3287 }
3288 }
3289 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003290 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003291
John McCalld6ca8da2010-04-10 07:37:23 +00003292 // Build the list of bases and members in the order that they'll
3293 // actually be initialized. The explicit initializers should be in
3294 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003295 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003296
Anders Carlsson071d6102010-04-02 03:38:04 +00003297 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3298
John McCalld6ca8da2010-04-10 07:37:23 +00003299 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003300 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003301 ClassDecl->vbases_begin(),
3302 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003303 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003304
John McCalld6ca8da2010-04-10 07:37:23 +00003305 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003306 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003307 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003308 if (Base->isVirtual())
3309 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003310 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003311 }
Mike Stump1eb44332009-09-09 15:08:12 +00003312
John McCalld6ca8da2010-04-10 07:37:23 +00003313 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003314 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003315 E = ClassDecl->field_end(); Field != E; ++Field) {
3316 if (Field->isUnnamedBitfield())
3317 continue;
3318
David Blaikieee000bb2013-01-17 08:49:22 +00003319 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003320 }
3321
John McCalld6ca8da2010-04-10 07:37:23 +00003322 unsigned NumIdealInits = IdealInitKeys.size();
3323 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003324
Sean Huntcbb67482011-01-08 20:30:50 +00003325 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003326 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003327 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003328 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003329
3330 // Scan forward to try to find this initializer in the idealized
3331 // initializers list.
3332 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3333 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003334 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003335
3336 // If we didn't find this initializer, it must be because we
3337 // scanned past it on a previous iteration. That can only
3338 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003339 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003340 Sema::SemaDiagnosticBuilder D =
3341 SemaRef.Diag(PrevInit->getSourceLocation(),
3342 diag::warn_initializer_out_of_order);
3343
Francois Pichet00eb3f92010-12-04 09:14:42 +00003344 if (PrevInit->isAnyMemberInitializer())
3345 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003346 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003347 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003348
Francois Pichet00eb3f92010-12-04 09:14:42 +00003349 if (Init->isAnyMemberInitializer())
3350 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003351 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003352 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003353
3354 // Move back to the initializer's location in the ideal list.
3355 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3356 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003357 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003358
3359 assert(IdealIndex != NumIdealInits &&
3360 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003361 }
John McCalld6ca8da2010-04-10 07:37:23 +00003362
3363 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003364 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003365}
3366
John McCall3c3ccdb2010-04-10 09:28:51 +00003367namespace {
3368bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003369 CXXCtorInitializer *Init,
3370 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003371 if (!PrevInit) {
3372 PrevInit = Init;
3373 return false;
3374 }
3375
3376 if (FieldDecl *Field = Init->getMember())
3377 S.Diag(Init->getSourceLocation(),
3378 diag::err_multiple_mem_initialization)
3379 << Field->getDeclName()
3380 << Init->getSourceRange();
3381 else {
John McCallf4c73712011-01-19 06:33:43 +00003382 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003383 assert(BaseClass && "neither field nor base");
3384 S.Diag(Init->getSourceLocation(),
3385 diag::err_multiple_base_initialization)
3386 << QualType(BaseClass, 0)
3387 << Init->getSourceRange();
3388 }
3389 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3390 << 0 << PrevInit->getSourceRange();
3391
3392 return true;
3393}
3394
Sean Huntcbb67482011-01-08 20:30:50 +00003395typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003396typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3397
3398bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003399 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003400 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003401 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003402 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003403 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003404
3405 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003406 if (Parent->isUnion()) {
3407 UnionEntry &En = Unions[Parent];
3408 if (En.first && En.first != Child) {
3409 S.Diag(Init->getSourceLocation(),
3410 diag::err_multiple_mem_union_initialization)
3411 << Field->getDeclName()
3412 << Init->getSourceRange();
3413 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3414 << 0 << En.second->getSourceRange();
3415 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003416 }
3417 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003418 En.first = Child;
3419 En.second = Init;
3420 }
David Blaikie6fe29652011-11-17 06:01:57 +00003421 if (!Parent->isAnonymousStructOrUnion())
3422 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003423 }
3424
3425 Child = Parent;
3426 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003427 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003428
3429 return false;
3430}
3431}
3432
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003433/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003434void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003435 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003436 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003437 bool AnyErrors) {
3438 if (!ConstructorDecl)
3439 return;
3440
3441 AdjustDeclIfTemplate(ConstructorDecl);
3442
3443 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003444 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003445
3446 if (!Constructor) {
3447 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3448 return;
3449 }
3450
John McCall3c3ccdb2010-04-10 09:28:51 +00003451 // Mapping for the duplicate initializers check.
3452 // For member initializers, this is keyed with a FieldDecl*.
3453 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003454 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003455
3456 // Mapping for the inconsistent anonymous-union initializers check.
3457 RedundantUnionMap MemberUnions;
3458
Anders Carlssonea356fb2010-04-02 05:42:15 +00003459 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003460 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003461 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003462
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003463 // Set the source order index.
3464 Init->setSourceOrder(i);
3465
Francois Pichet00eb3f92010-12-04 09:14:42 +00003466 if (Init->isAnyMemberInitializer()) {
3467 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003468 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3469 CheckRedundantUnionInit(*this, Init, MemberUnions))
3470 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003471 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003472 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3473 if (CheckRedundantInit(*this, Init, Members[Key]))
3474 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003475 } else {
3476 assert(Init->isDelegatingInitializer());
3477 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003478 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003479 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003480 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003481 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003482 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003483 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003484 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003485 // Return immediately as the initializer is set.
3486 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003487 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003488 }
3489
Anders Carlssonea356fb2010-04-02 05:42:15 +00003490 if (HadError)
3491 return;
3492
David Blaikie93c86172013-01-17 05:26:25 +00003493 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003494
David Blaikie93c86172013-01-17 05:26:25 +00003495 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003496}
3497
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003498void
John McCallef027fe2010-03-16 21:39:52 +00003499Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3500 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003501 // Ignore dependent contexts. Also ignore unions, since their members never
3502 // have destructors implicitly called.
3503 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003504 return;
John McCall58e6f342010-03-16 05:22:47 +00003505
3506 // FIXME: all the access-control diagnostics are positioned on the
3507 // field/base declaration. That's probably good; that said, the
3508 // user might reasonably want to know why the destructor is being
3509 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003510
Anders Carlsson9f853df2009-11-17 04:44:12 +00003511 // Non-static data members.
3512 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3513 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003514 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003515 if (Field->isInvalidDecl())
3516 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003517
3518 // Don't destroy incomplete or zero-length arrays.
3519 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3520 continue;
3521
Anders Carlsson9f853df2009-11-17 04:44:12 +00003522 QualType FieldType = Context.getBaseElementType(Field->getType());
3523
3524 const RecordType* RT = FieldType->getAs<RecordType>();
3525 if (!RT)
3526 continue;
3527
3528 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003529 if (FieldClassDecl->isInvalidDecl())
3530 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003531 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003532 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003533 // The destructor for an implicit anonymous union member is never invoked.
3534 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3535 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003536
Douglas Gregordb89f282010-07-01 22:47:18 +00003537 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003538 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003539 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003540 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003541 << Field->getDeclName()
3542 << FieldType);
3543
Eli Friedman5f2987c2012-02-02 03:46:19 +00003544 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003545 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003546 }
3547
John McCall58e6f342010-03-16 05:22:47 +00003548 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3549
Anders Carlsson9f853df2009-11-17 04:44:12 +00003550 // Bases.
3551 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3552 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003553 // Bases are always records in a well-formed non-dependent class.
3554 const RecordType *RT = Base->getType()->getAs<RecordType>();
3555
3556 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003557 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003558 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003559
John McCall58e6f342010-03-16 05:22:47 +00003560 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003561 // If our base class is invalid, we probably can't get its dtor anyway.
3562 if (BaseClassDecl->isInvalidDecl())
3563 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003564 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003565 continue;
John McCall58e6f342010-03-16 05:22:47 +00003566
Douglas Gregordb89f282010-07-01 22:47:18 +00003567 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003568 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003569
3570 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003571 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003572 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003573 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003574 << Base->getSourceRange(),
3575 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003576
Eli Friedman5f2987c2012-02-02 03:46:19 +00003577 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003578 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003579 }
3580
3581 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003582 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3583 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003584
3585 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003586 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003587
3588 // Ignore direct virtual bases.
3589 if (DirectVirtualBases.count(RT))
3590 continue;
3591
John McCall58e6f342010-03-16 05:22:47 +00003592 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003593 // If our base class is invalid, we probably can't get its dtor anyway.
3594 if (BaseClassDecl->isInvalidDecl())
3595 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003596 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003597 continue;
John McCall58e6f342010-03-16 05:22:47 +00003598
Douglas Gregordb89f282010-07-01 22:47:18 +00003599 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003600 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003601 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003602 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003603 << VBase->getType(),
3604 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003605
Eli Friedman5f2987c2012-02-02 03:46:19 +00003606 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003607 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003608 }
3609}
3610
John McCalld226f652010-08-21 09:40:31 +00003611void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003612 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003613 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003614
Mike Stump1eb44332009-09-09 15:08:12 +00003615 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003616 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003617 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003618}
3619
Mike Stump1eb44332009-09-09 15:08:12 +00003620bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003621 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003622 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3623 unsigned DiagID;
3624 AbstractDiagSelID SelID;
3625
3626 public:
3627 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3628 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3629
3630 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003631 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003632 if (SelID == -1)
3633 S.Diag(Loc, DiagID) << T;
3634 else
3635 S.Diag(Loc, DiagID) << SelID << T;
3636 }
3637 } Diagnoser(DiagID, SelID);
3638
3639 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003640}
3641
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003642bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003643 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003644 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003645 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003646
Anders Carlsson11f21a02009-03-23 19:10:31 +00003647 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003648 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003649
Ted Kremenek6217b802009-07-29 21:53:49 +00003650 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003651 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003652 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003653 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003654
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003655 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003656 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003657 }
Mike Stump1eb44332009-09-09 15:08:12 +00003658
Ted Kremenek6217b802009-07-29 21:53:49 +00003659 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003660 if (!RT)
3661 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003662
John McCall86ff3082010-02-04 22:26:26 +00003663 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003664
John McCall94c3b562010-08-18 09:41:07 +00003665 // We can't answer whether something is abstract until it has a
3666 // definition. If it's currently being defined, we'll walk back
3667 // over all the declarations when we have a full definition.
3668 const CXXRecordDecl *Def = RD->getDefinition();
3669 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003670 return false;
3671
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003672 if (!RD->isAbstract())
3673 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003674
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003675 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003676 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003677
John McCall94c3b562010-08-18 09:41:07 +00003678 return true;
3679}
3680
3681void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3682 // Check if we've already emitted the list of pure virtual functions
3683 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003684 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003685 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003686
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003687 CXXFinalOverriderMap FinalOverriders;
3688 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003689
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003690 // Keep a set of seen pure methods so we won't diagnose the same method
3691 // more than once.
3692 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3693
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003694 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3695 MEnd = FinalOverriders.end();
3696 M != MEnd;
3697 ++M) {
3698 for (OverridingMethods::iterator SO = M->second.begin(),
3699 SOEnd = M->second.end();
3700 SO != SOEnd; ++SO) {
3701 // C++ [class.abstract]p4:
3702 // A class is abstract if it contains or inherits at least one
3703 // pure virtual function for which the final overrider is pure
3704 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003705
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003706 //
3707 if (SO->second.size() != 1)
3708 continue;
3709
3710 if (!SO->second.front().Method->isPure())
3711 continue;
3712
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003713 if (!SeenPureMethods.insert(SO->second.front().Method))
3714 continue;
3715
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003716 Diag(SO->second.front().Method->getLocation(),
3717 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003718 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003719 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003720 }
3721
3722 if (!PureVirtualClassDiagSet)
3723 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3724 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003725}
3726
Anders Carlsson8211eff2009-03-24 01:19:16 +00003727namespace {
John McCall94c3b562010-08-18 09:41:07 +00003728struct AbstractUsageInfo {
3729 Sema &S;
3730 CXXRecordDecl *Record;
3731 CanQualType AbstractType;
3732 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003733
John McCall94c3b562010-08-18 09:41:07 +00003734 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3735 : S(S), Record(Record),
3736 AbstractType(S.Context.getCanonicalType(
3737 S.Context.getTypeDeclType(Record))),
3738 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003739
John McCall94c3b562010-08-18 09:41:07 +00003740 void DiagnoseAbstractType() {
3741 if (Invalid) return;
3742 S.DiagnoseAbstractType(Record);
3743 Invalid = true;
3744 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003745
John McCall94c3b562010-08-18 09:41:07 +00003746 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3747};
3748
3749struct CheckAbstractUsage {
3750 AbstractUsageInfo &Info;
3751 const NamedDecl *Ctx;
3752
3753 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3754 : Info(Info), Ctx(Ctx) {}
3755
3756 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3757 switch (TL.getTypeLocClass()) {
3758#define ABSTRACT_TYPELOC(CLASS, PARENT)
3759#define TYPELOC(CLASS, PARENT) \
3760 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3761#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003762 }
John McCall94c3b562010-08-18 09:41:07 +00003763 }
Mike Stump1eb44332009-09-09 15:08:12 +00003764
John McCall94c3b562010-08-18 09:41:07 +00003765 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3766 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3767 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003768 if (!TL.getArg(I))
3769 continue;
3770
John McCall94c3b562010-08-18 09:41:07 +00003771 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3772 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003773 }
John McCall94c3b562010-08-18 09:41:07 +00003774 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003775
John McCall94c3b562010-08-18 09:41:07 +00003776 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3777 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3778 }
Mike Stump1eb44332009-09-09 15:08:12 +00003779
John McCall94c3b562010-08-18 09:41:07 +00003780 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3781 // Visit the type parameters from a permissive context.
3782 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3783 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3784 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3785 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3786 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3787 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003788 }
John McCall94c3b562010-08-18 09:41:07 +00003789 }
Mike Stump1eb44332009-09-09 15:08:12 +00003790
John McCall94c3b562010-08-18 09:41:07 +00003791 // Visit pointee types from a permissive context.
3792#define CheckPolymorphic(Type) \
3793 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3794 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3795 }
3796 CheckPolymorphic(PointerTypeLoc)
3797 CheckPolymorphic(ReferenceTypeLoc)
3798 CheckPolymorphic(MemberPointerTypeLoc)
3799 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003800 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003801
John McCall94c3b562010-08-18 09:41:07 +00003802 /// Handle all the types we haven't given a more specific
3803 /// implementation for above.
3804 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3805 // Every other kind of type that we haven't called out already
3806 // that has an inner type is either (1) sugar or (2) contains that
3807 // inner type in some way as a subobject.
3808 if (TypeLoc Next = TL.getNextTypeLoc())
3809 return Visit(Next, Sel);
3810
3811 // If there's no inner type and we're in a permissive context,
3812 // don't diagnose.
3813 if (Sel == Sema::AbstractNone) return;
3814
3815 // Check whether the type matches the abstract type.
3816 QualType T = TL.getType();
3817 if (T->isArrayType()) {
3818 Sel = Sema::AbstractArrayType;
3819 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003820 }
John McCall94c3b562010-08-18 09:41:07 +00003821 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3822 if (CT != Info.AbstractType) return;
3823
3824 // It matched; do some magic.
3825 if (Sel == Sema::AbstractArrayType) {
3826 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3827 << T << TL.getSourceRange();
3828 } else {
3829 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3830 << Sel << T << TL.getSourceRange();
3831 }
3832 Info.DiagnoseAbstractType();
3833 }
3834};
3835
3836void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3837 Sema::AbstractDiagSelID Sel) {
3838 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3839}
3840
3841}
3842
3843/// Check for invalid uses of an abstract type in a method declaration.
3844static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3845 CXXMethodDecl *MD) {
3846 // No need to do the check on definitions, which require that
3847 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003848 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003849 return;
3850
3851 // For safety's sake, just ignore it if we don't have type source
3852 // information. This should never happen for non-implicit methods,
3853 // but...
3854 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3855 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3856}
3857
3858/// Check for invalid uses of an abstract type within a class definition.
3859static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3860 CXXRecordDecl *RD) {
3861 for (CXXRecordDecl::decl_iterator
3862 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3863 Decl *D = *I;
3864 if (D->isImplicit()) continue;
3865
3866 // Methods and method templates.
3867 if (isa<CXXMethodDecl>(D)) {
3868 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3869 } else if (isa<FunctionTemplateDecl>(D)) {
3870 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3871 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3872
3873 // Fields and static variables.
3874 } else if (isa<FieldDecl>(D)) {
3875 FieldDecl *FD = cast<FieldDecl>(D);
3876 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3877 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3878 } else if (isa<VarDecl>(D)) {
3879 VarDecl *VD = cast<VarDecl>(D);
3880 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3881 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3882
3883 // Nested classes and class templates.
3884 } else if (isa<CXXRecordDecl>(D)) {
3885 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3886 } else if (isa<ClassTemplateDecl>(D)) {
3887 CheckAbstractClassUsage(Info,
3888 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3889 }
3890 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003891}
3892
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003893/// \brief Perform semantic checks on a class definition that has been
3894/// completing, introducing implicitly-declared members, checking for
3895/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003896void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003897 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003898 return;
3899
John McCall94c3b562010-08-18 09:41:07 +00003900 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3901 AbstractUsageInfo Info(*this, Record);
3902 CheckAbstractClassUsage(Info, Record);
3903 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003904
3905 // If this is not an aggregate type and has no user-declared constructor,
3906 // complain about any non-static data members of reference or const scalar
3907 // type, since they will never get initializers.
3908 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003909 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3910 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003911 bool Complained = false;
3912 for (RecordDecl::field_iterator F = Record->field_begin(),
3913 FEnd = Record->field_end();
3914 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003915 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003916 continue;
3917
Douglas Gregor325e5932010-04-15 00:00:53 +00003918 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003919 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003920 if (!Complained) {
3921 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3922 << Record->getTagKind() << Record;
3923 Complained = true;
3924 }
3925
3926 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3927 << F->getType()->isReferenceType()
3928 << F->getDeclName();
3929 }
3930 }
3931 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003932
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003933 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003934 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003935
3936 if (Record->getIdentifier()) {
3937 // C++ [class.mem]p13:
3938 // If T is the name of a class, then each of the following shall have a
3939 // name different from T:
3940 // - every member of every anonymous union that is a member of class T.
3941 //
3942 // C++ [class.mem]p14:
3943 // In addition, if class T has a user-declared constructor (12.1), every
3944 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00003945 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3946 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3947 ++I) {
3948 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00003949 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3950 isa<IndirectFieldDecl>(D)) {
3951 Diag(D->getLocation(), diag::err_member_name_of_class)
3952 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003953 break;
3954 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003955 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003956 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003957
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003958 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003959 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003960 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003961 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003962 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3963 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3964 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003965
David Blaikieb6b5b972012-09-21 03:21:07 +00003966 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
3967 Diag(Record->getLocation(), diag::warn_abstract_final_class);
3968 DiagnoseAbstractType(Record);
3969 }
3970
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003971 if (!Record->isDependentType()) {
3972 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3973 MEnd = Record->method_end();
3974 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00003975 // See if a method overloads virtual methods in a base
3976 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00003977 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003978 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00003979
3980 // Check whether the explicitly-defaulted special members are valid.
3981 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
3982 CheckExplicitlyDefaultedSpecialMember(*M);
3983
3984 // For an explicitly defaulted or deleted special member, we defer
3985 // determining triviality until the class is complete. That time is now!
3986 if (!M->isImplicit() && !M->isUserProvided()) {
3987 CXXSpecialMember CSM = getSpecialMember(*M);
3988 if (CSM != CXXInvalid) {
3989 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
3990
3991 // Inform the class that we've finished declaring this member.
3992 Record->finishedDefaultedOrDeletedMember(*M);
3993 }
3994 }
3995 }
3996 }
3997
3998 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
3999 // function that is not a constructor declares that member function to be
4000 // const. [...] The class of which that function is a member shall be
4001 // a literal type.
4002 //
4003 // If the class has virtual bases, any constexpr members will already have
4004 // been diagnosed by the checks performed on the member declaration, so
4005 // suppress this (less useful) diagnostic.
4006 //
4007 // We delay this until we know whether an explicitly-defaulted (or deleted)
4008 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004009 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004010 !Record->isLiteral() && !Record->getNumVBases()) {
4011 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4012 MEnd = Record->method_end();
4013 M != MEnd; ++M) {
4014 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4015 switch (Record->getTemplateSpecializationKind()) {
4016 case TSK_ImplicitInstantiation:
4017 case TSK_ExplicitInstantiationDeclaration:
4018 case TSK_ExplicitInstantiationDefinition:
4019 // If a template instantiates to a non-literal type, but its members
4020 // instantiate to constexpr functions, the template is technically
4021 // ill-formed, but we allow it for sanity.
4022 continue;
4023
4024 case TSK_Undeclared:
4025 case TSK_ExplicitSpecialization:
4026 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4027 diag::err_constexpr_method_non_literal);
4028 break;
4029 }
4030
4031 // Only produce one error per class.
4032 break;
4033 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004034 }
4035 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004036
4037 // Declare inherited constructors. We do this eagerly here because:
4038 // - The standard requires an eager diagnostic for conflicting inherited
4039 // constructors from different classes.
4040 // - The lazy declaration of the other implicit constructors is so as to not
4041 // waste space and performance on classes that are not meant to be
4042 // instantiated (e.g. meta-functions). This doesn't apply to classes that
4043 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004044 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004045}
4046
Richard Smith7756afa2012-06-10 05:43:50 +00004047/// Is the special member function which would be selected to perform the
4048/// specified operation on the specified class type a constexpr constructor?
4049static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4050 Sema::CXXSpecialMember CSM,
4051 bool ConstArg) {
4052 Sema::SpecialMemberOverloadResult *SMOR =
4053 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4054 false, false, false, false);
4055 if (!SMOR || !SMOR->getMethod())
4056 // A constructor we wouldn't select can't be "involved in initializing"
4057 // anything.
4058 return true;
4059 return SMOR->getMethod()->isConstexpr();
4060}
4061
4062/// Determine whether the specified special member function would be constexpr
4063/// if it were implicitly defined.
4064static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4065 Sema::CXXSpecialMember CSM,
4066 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004067 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004068 return false;
4069
4070 // C++11 [dcl.constexpr]p4:
4071 // In the definition of a constexpr constructor [...]
4072 switch (CSM) {
4073 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004074 // Since default constructor lookup is essentially trivial (and cannot
4075 // involve, for instance, template instantiation), we compute whether a
4076 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4077 //
4078 // This is important for performance; we need to know whether the default
4079 // constructor is constexpr to determine whether the type is a literal type.
4080 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4081
Richard Smith7756afa2012-06-10 05:43:50 +00004082 case Sema::CXXCopyConstructor:
4083 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004084 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004085 break;
4086
4087 case Sema::CXXCopyAssignment:
4088 case Sema::CXXMoveAssignment:
4089 case Sema::CXXDestructor:
4090 case Sema::CXXInvalid:
4091 return false;
4092 }
4093
4094 // -- if the class is a non-empty union, or for each non-empty anonymous
4095 // union member of a non-union class, exactly one non-static data member
4096 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004097 //
4098 // If we squint, this is guaranteed, since exactly one non-static data member
4099 // will be initialized (if the constructor isn't deleted), we just don't know
4100 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004101 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004102 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004103
4104 // -- the class shall not have any virtual base classes;
4105 if (ClassDecl->getNumVBases())
4106 return false;
4107
4108 // -- every constructor involved in initializing [...] base class
4109 // sub-objects shall be a constexpr constructor;
4110 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4111 BEnd = ClassDecl->bases_end();
4112 B != BEnd; ++B) {
4113 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4114 if (!BaseType) continue;
4115
4116 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4117 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4118 return false;
4119 }
4120
4121 // -- every constructor involved in initializing non-static data members
4122 // [...] shall be a constexpr constructor;
4123 // -- every non-static data member and base class sub-object shall be
4124 // initialized
4125 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4126 FEnd = ClassDecl->field_end();
4127 F != FEnd; ++F) {
4128 if (F->isInvalidDecl())
4129 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004130 if (const RecordType *RecordTy =
4131 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004132 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4133 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4134 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004135 }
4136 }
4137
4138 // All OK, it's constexpr!
4139 return true;
4140}
4141
Richard Smithb9d0b762012-07-27 04:22:15 +00004142static Sema::ImplicitExceptionSpecification
4143computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4144 switch (S.getSpecialMember(MD)) {
4145 case Sema::CXXDefaultConstructor:
4146 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4147 case Sema::CXXCopyConstructor:
4148 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4149 case Sema::CXXCopyAssignment:
4150 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4151 case Sema::CXXMoveConstructor:
4152 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4153 case Sema::CXXMoveAssignment:
4154 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4155 case Sema::CXXDestructor:
4156 return S.ComputeDefaultedDtorExceptionSpec(MD);
4157 case Sema::CXXInvalid:
4158 break;
4159 }
4160 llvm_unreachable("only special members have implicit exception specs");
4161}
4162
Richard Smithdd25e802012-07-30 23:48:14 +00004163static void
4164updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4165 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4166 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4167 ExceptSpec.getEPI(EPI);
4168 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4169 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4170 FPT->getNumArgs(), EPI));
4171 FD->setType(QualType(NewFPT, 0));
4172}
4173
Richard Smithb9d0b762012-07-27 04:22:15 +00004174void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4175 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4176 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4177 return;
4178
Richard Smithdd25e802012-07-30 23:48:14 +00004179 // Evaluate the exception specification.
4180 ImplicitExceptionSpecification ExceptSpec =
4181 computeImplicitExceptionSpec(*this, Loc, MD);
4182
4183 // Update the type of the special member to use it.
4184 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4185
4186 // A user-provided destructor can be defined outside the class. When that
4187 // happens, be sure to update the exception specification on both
4188 // declarations.
4189 const FunctionProtoType *CanonicalFPT =
4190 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4191 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4192 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4193 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004194}
4195
Richard Smith3003e1d2012-05-15 04:39:51 +00004196void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4197 CXXRecordDecl *RD = MD->getParent();
4198 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004199
Richard Smith3003e1d2012-05-15 04:39:51 +00004200 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4201 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004202
4203 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004204 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004205 bool First = MD == MD->getCanonicalDecl();
4206
4207 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004208
4209 // C++11 [dcl.fct.def.default]p1:
4210 // A function that is explicitly defaulted shall
4211 // -- be a special member function (checked elsewhere),
4212 // -- have the same type (except for ref-qualifiers, and except that a
4213 // copy operation can take a non-const reference) as an implicit
4214 // declaration, and
4215 // -- not have default arguments.
4216 unsigned ExpectedParams = 1;
4217 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4218 ExpectedParams = 0;
4219 if (MD->getNumParams() != ExpectedParams) {
4220 // This also checks for default arguments: a copy or move constructor with a
4221 // default argument is classified as a default constructor, and assignment
4222 // operations and destructors can't have default arguments.
4223 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4224 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004225 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004226 } else if (MD->isVariadic()) {
4227 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4228 << CSM << MD->getSourceRange();
4229 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004230 }
4231
Richard Smith3003e1d2012-05-15 04:39:51 +00004232 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004233
Richard Smith7756afa2012-06-10 05:43:50 +00004234 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004235 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004236 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004237 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004238 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004239
Richard Smith3003e1d2012-05-15 04:39:51 +00004240 QualType ReturnType = Context.VoidTy;
4241 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4242 // Check for return type matching.
4243 ReturnType = Type->getResultType();
4244 QualType ExpectedReturnType =
4245 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4246 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4247 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4248 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4249 HadError = true;
4250 }
4251
4252 // A defaulted special member cannot have cv-qualifiers.
4253 if (Type->getTypeQuals()) {
4254 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4255 << (CSM == CXXMoveAssignment);
4256 HadError = true;
4257 }
4258 }
4259
4260 // Check for parameter type matching.
4261 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004262 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004263 if (ExpectedParams && ArgType->isReferenceType()) {
4264 // Argument must be reference to possibly-const T.
4265 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004266 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004267
4268 if (ReferentType.isVolatileQualified()) {
4269 Diag(MD->getLocation(),
4270 diag::err_defaulted_special_member_volatile_param) << CSM;
4271 HadError = true;
4272 }
4273
Richard Smith7756afa2012-06-10 05:43:50 +00004274 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004275 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4276 Diag(MD->getLocation(),
4277 diag::err_defaulted_special_member_copy_const_param)
4278 << (CSM == CXXCopyAssignment);
4279 // FIXME: Explain why this special member can't be const.
4280 } else {
4281 Diag(MD->getLocation(),
4282 diag::err_defaulted_special_member_move_const_param)
4283 << (CSM == CXXMoveAssignment);
4284 }
4285 HadError = true;
4286 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004287 } else if (ExpectedParams) {
4288 // A copy assignment operator can take its argument by value, but a
4289 // defaulted one cannot.
4290 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004291 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004292 HadError = true;
4293 }
Sean Huntbe631222011-05-17 20:44:43 +00004294
Richard Smith61802452011-12-22 02:22:31 +00004295 // C++11 [dcl.fct.def.default]p2:
4296 // An explicitly-defaulted function may be declared constexpr only if it
4297 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004298 // Do not apply this rule to members of class templates, since core issue 1358
4299 // makes such functions always instantiate to constexpr functions. For
4300 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004301 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4302 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004303 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4304 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4305 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004306 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004307 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004308 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004309
Richard Smith61802452011-12-22 02:22:31 +00004310 // and may have an explicit exception-specification only if it is compatible
4311 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004312 if (Type->hasExceptionSpec()) {
4313 // Delay the check if this is the first declaration of the special member,
4314 // since we may not have parsed some necessary in-class initializers yet.
4315 if (First)
4316 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4317 else
4318 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4319 }
Richard Smith61802452011-12-22 02:22:31 +00004320
4321 // If a function is explicitly defaulted on its first declaration,
4322 if (First) {
4323 // -- it is implicitly considered to be constexpr if the implicit
4324 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004325 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004326
Richard Smith3003e1d2012-05-15 04:39:51 +00004327 // -- it is implicitly considered to have the same exception-specification
4328 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004329 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4330 EPI.ExceptionSpecType = EST_Unevaluated;
4331 EPI.ExceptionSpecDecl = MD;
4332 MD->setType(Context.getFunctionType(ReturnType, &ArgType,
4333 ExpectedParams, EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004334 }
4335
Richard Smith3003e1d2012-05-15 04:39:51 +00004336 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004337 if (First) {
4338 MD->setDeletedAsWritten();
4339 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004340 // C++11 [dcl.fct.def.default]p4:
4341 // [For a] user-provided explicitly-defaulted function [...] if such a
4342 // function is implicitly defined as deleted, the program is ill-formed.
4343 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4344 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004345 }
4346 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004347
Richard Smith3003e1d2012-05-15 04:39:51 +00004348 if (HadError)
4349 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004350}
4351
Richard Smith1d28caf2012-12-11 01:14:52 +00004352/// Check whether the exception specification provided for an
4353/// explicitly-defaulted special member matches the exception specification
4354/// that would have been generated for an implicit special member, per
4355/// C++11 [dcl.fct.def.default]p2.
4356void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4357 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4358 // Compute the implicit exception specification.
4359 FunctionProtoType::ExtProtoInfo EPI;
4360 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4361 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4362 Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4363
4364 // Ensure that it matches.
4365 CheckEquivalentExceptionSpec(
4366 PDiag(diag::err_incorrect_defaulted_exception_spec)
4367 << getSpecialMember(MD), PDiag(),
4368 ImplicitType, SourceLocation(),
4369 SpecifiedType, MD->getLocation());
4370}
4371
4372void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4373 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4374 I != N; ++I)
4375 CheckExplicitlyDefaultedMemberExceptionSpec(
4376 DelayedDefaultedMemberExceptionSpecs[I].first,
4377 DelayedDefaultedMemberExceptionSpecs[I].second);
4378
4379 DelayedDefaultedMemberExceptionSpecs.clear();
4380}
4381
Richard Smith7d5088a2012-02-18 02:02:13 +00004382namespace {
4383struct SpecialMemberDeletionInfo {
4384 Sema &S;
4385 CXXMethodDecl *MD;
4386 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004387 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004388
4389 // Properties of the special member, computed for convenience.
4390 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4391 SourceLocation Loc;
4392
4393 bool AllFieldsAreConst;
4394
4395 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004396 Sema::CXXSpecialMember CSM, bool Diagnose)
4397 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004398 IsConstructor(false), IsAssignment(false), IsMove(false),
4399 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4400 AllFieldsAreConst(true) {
4401 switch (CSM) {
4402 case Sema::CXXDefaultConstructor:
4403 case Sema::CXXCopyConstructor:
4404 IsConstructor = true;
4405 break;
4406 case Sema::CXXMoveConstructor:
4407 IsConstructor = true;
4408 IsMove = true;
4409 break;
4410 case Sema::CXXCopyAssignment:
4411 IsAssignment = true;
4412 break;
4413 case Sema::CXXMoveAssignment:
4414 IsAssignment = true;
4415 IsMove = true;
4416 break;
4417 case Sema::CXXDestructor:
4418 break;
4419 case Sema::CXXInvalid:
4420 llvm_unreachable("invalid special member kind");
4421 }
4422
4423 if (MD->getNumParams()) {
4424 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4425 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4426 }
4427 }
4428
4429 bool inUnion() const { return MD->getParent()->isUnion(); }
4430
4431 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004432 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4433 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004434 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004435 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4436 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4437 Quals = 0;
4438 return S.LookupSpecialMember(Class, CSM,
4439 ConstArg || (Quals & Qualifiers::Const),
4440 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004441 MD->getRefQualifier() == RQ_RValue,
4442 TQ & Qualifiers::Const,
4443 TQ & Qualifiers::Volatile);
4444 }
4445
Richard Smith6c4c36c2012-03-30 20:53:28 +00004446 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004447
Richard Smith6c4c36c2012-03-30 20:53:28 +00004448 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004449 bool shouldDeleteForField(FieldDecl *FD);
4450 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004451
Richard Smith517bb842012-07-18 03:51:16 +00004452 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4453 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004454 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4455 Sema::SpecialMemberOverloadResult *SMOR,
4456 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004457
4458 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004459};
4460}
4461
John McCall12d8d802012-04-09 20:53:23 +00004462/// Is the given special member inaccessible when used on the given
4463/// sub-object.
4464bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4465 CXXMethodDecl *target) {
4466 /// If we're operating on a base class, the object type is the
4467 /// type of this special member.
4468 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004469 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004470 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4471 objectTy = S.Context.getTypeDeclType(MD->getParent());
4472 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4473
4474 // If we're operating on a field, the object type is the type of the field.
4475 } else {
4476 objectTy = S.Context.getTypeDeclType(target->getParent());
4477 }
4478
4479 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4480}
4481
Richard Smith6c4c36c2012-03-30 20:53:28 +00004482/// Check whether we should delete a special member due to the implicit
4483/// definition containing a call to a special member of a subobject.
4484bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4485 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4486 bool IsDtorCallInCtor) {
4487 CXXMethodDecl *Decl = SMOR->getMethod();
4488 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4489
4490 int DiagKind = -1;
4491
4492 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4493 DiagKind = !Decl ? 0 : 1;
4494 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4495 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004496 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004497 DiagKind = 3;
4498 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4499 !Decl->isTrivial()) {
4500 // A member of a union must have a trivial corresponding special member.
4501 // As a weird special case, a destructor call from a union's constructor
4502 // must be accessible and non-deleted, but need not be trivial. Such a
4503 // destructor is never actually called, but is semantically checked as
4504 // if it were.
4505 DiagKind = 4;
4506 }
4507
4508 if (DiagKind == -1)
4509 return false;
4510
4511 if (Diagnose) {
4512 if (Field) {
4513 S.Diag(Field->getLocation(),
4514 diag::note_deleted_special_member_class_subobject)
4515 << CSM << MD->getParent() << /*IsField*/true
4516 << Field << DiagKind << IsDtorCallInCtor;
4517 } else {
4518 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4519 S.Diag(Base->getLocStart(),
4520 diag::note_deleted_special_member_class_subobject)
4521 << CSM << MD->getParent() << /*IsField*/false
4522 << Base->getType() << DiagKind << IsDtorCallInCtor;
4523 }
4524
4525 if (DiagKind == 1)
4526 S.NoteDeletedFunction(Decl);
4527 // FIXME: Explain inaccessibility if DiagKind == 3.
4528 }
4529
4530 return true;
4531}
4532
Richard Smith9a561d52012-02-26 09:11:52 +00004533/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004534/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004535bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004536 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004537 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004538
4539 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004540 // -- any direct or virtual base class, or non-static data member with no
4541 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004542 // either M has no default constructor or overload resolution as applied
4543 // to M's default constructor results in an ambiguity or in a function
4544 // that is deleted or inaccessible
4545 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4546 // -- a direct or virtual base class B that cannot be copied/moved because
4547 // overload resolution, as applied to B's corresponding special member,
4548 // results in an ambiguity or a function that is deleted or inaccessible
4549 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004550 // C++11 [class.dtor]p5:
4551 // -- any direct or virtual base class [...] has a type with a destructor
4552 // that is deleted or inaccessible
4553 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004554 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004555 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004556 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004557
Richard Smith6c4c36c2012-03-30 20:53:28 +00004558 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4559 // -- any direct or virtual base class or non-static data member has a
4560 // type with a destructor that is deleted or inaccessible
4561 if (IsConstructor) {
4562 Sema::SpecialMemberOverloadResult *SMOR =
4563 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4564 false, false, false, false, false);
4565 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4566 return true;
4567 }
4568
Richard Smith9a561d52012-02-26 09:11:52 +00004569 return false;
4570}
4571
4572/// Check whether we should delete a special member function due to the class
4573/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004574bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004575 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004576 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004577}
4578
4579/// Check whether we should delete a special member function due to the class
4580/// having a particular non-static data member.
4581bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4582 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4583 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4584
4585 if (CSM == Sema::CXXDefaultConstructor) {
4586 // For a default constructor, all references must be initialized in-class
4587 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004588 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4589 if (Diagnose)
4590 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4591 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004592 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004593 }
Richard Smith79363f52012-02-27 06:07:25 +00004594 // C++11 [class.ctor]p5: any non-variant non-static data member of
4595 // const-qualified type (or array thereof) with no
4596 // brace-or-equal-initializer does not have a user-provided default
4597 // constructor.
4598 if (!inUnion() && FieldType.isConstQualified() &&
4599 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004600 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4601 if (Diagnose)
4602 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004603 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004604 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004605 }
4606
4607 if (inUnion() && !FieldType.isConstQualified())
4608 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004609 } else if (CSM == Sema::CXXCopyConstructor) {
4610 // For a copy constructor, data members must not be of rvalue reference
4611 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004612 if (FieldType->isRValueReferenceType()) {
4613 if (Diagnose)
4614 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4615 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004616 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004617 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004618 } else if (IsAssignment) {
4619 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004620 if (FieldType->isReferenceType()) {
4621 if (Diagnose)
4622 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4623 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004624 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004625 }
4626 if (!FieldRecord && FieldType.isConstQualified()) {
4627 // C++11 [class.copy]p23:
4628 // -- a non-static data member of const non-class type (or array thereof)
4629 if (Diagnose)
4630 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004631 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004632 return true;
4633 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004634 }
4635
4636 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004637 // Some additional restrictions exist on the variant members.
4638 if (!inUnion() && FieldRecord->isUnion() &&
4639 FieldRecord->isAnonymousStructOrUnion()) {
4640 bool AllVariantFieldsAreConst = true;
4641
Richard Smithdf8dc862012-03-29 19:00:10 +00004642 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004643 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4644 UE = FieldRecord->field_end();
4645 UI != UE; ++UI) {
4646 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004647
4648 if (!UnionFieldType.isConstQualified())
4649 AllVariantFieldsAreConst = false;
4650
Richard Smith9a561d52012-02-26 09:11:52 +00004651 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4652 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004653 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4654 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004655 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004656 }
4657
4658 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004659 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004660 FieldRecord->field_begin() != FieldRecord->field_end()) {
4661 if (Diagnose)
4662 S.Diag(FieldRecord->getLocation(),
4663 diag::note_deleted_default_ctor_all_const)
4664 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004665 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004666 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004667
Richard Smithdf8dc862012-03-29 19:00:10 +00004668 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004669 // This is technically non-conformant, but sanity demands it.
4670 return false;
4671 }
4672
Richard Smith517bb842012-07-18 03:51:16 +00004673 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4674 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004675 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004676 }
4677
4678 return false;
4679}
4680
4681/// C++11 [class.ctor] p5:
4682/// A defaulted default constructor for a class X is defined as deleted if
4683/// X is a union and all of its variant members are of const-qualified type.
4684bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004685 // This is a silly definition, because it gives an empty union a deleted
4686 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004687 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4688 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4689 if (Diagnose)
4690 S.Diag(MD->getParent()->getLocation(),
4691 diag::note_deleted_default_ctor_all_const)
4692 << MD->getParent() << /*not anonymous union*/0;
4693 return true;
4694 }
4695 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004696}
4697
4698/// Determine whether a defaulted special member function should be defined as
4699/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4700/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004701bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4702 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004703 if (MD->isInvalidDecl())
4704 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004705 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004706 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004707 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004708 return false;
4709
Richard Smith7d5088a2012-02-18 02:02:13 +00004710 // C++11 [expr.lambda.prim]p19:
4711 // The closure type associated with a lambda-expression has a
4712 // deleted (8.4.3) default constructor and a deleted copy
4713 // assignment operator.
4714 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004715 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4716 if (Diagnose)
4717 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004718 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004719 }
4720
Richard Smith5bdaac52012-04-02 20:59:25 +00004721 // For an anonymous struct or union, the copy and assignment special members
4722 // will never be used, so skip the check. For an anonymous union declared at
4723 // namespace scope, the constructor and destructor are used.
4724 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4725 RD->isAnonymousStructOrUnion())
4726 return false;
4727
Richard Smith6c4c36c2012-03-30 20:53:28 +00004728 // C++11 [class.copy]p7, p18:
4729 // If the class definition declares a move constructor or move assignment
4730 // operator, an implicitly declared copy constructor or copy assignment
4731 // operator is defined as deleted.
4732 if (MD->isImplicit() &&
4733 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4734 CXXMethodDecl *UserDeclaredMove = 0;
4735
4736 // In Microsoft mode, a user-declared move only causes the deletion of the
4737 // corresponding copy operation, not both copy operations.
4738 if (RD->hasUserDeclaredMoveConstructor() &&
4739 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4740 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004741
4742 // Find any user-declared move constructor.
4743 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4744 E = RD->ctor_end(); I != E; ++I) {
4745 if (I->isMoveConstructor()) {
4746 UserDeclaredMove = *I;
4747 break;
4748 }
4749 }
Richard Smith1c931be2012-04-02 18:40:40 +00004750 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004751 } else if (RD->hasUserDeclaredMoveAssignment() &&
4752 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4753 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004754
4755 // Find any user-declared move assignment operator.
4756 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4757 E = RD->method_end(); I != E; ++I) {
4758 if (I->isMoveAssignmentOperator()) {
4759 UserDeclaredMove = *I;
4760 break;
4761 }
4762 }
Richard Smith1c931be2012-04-02 18:40:40 +00004763 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004764 }
4765
4766 if (UserDeclaredMove) {
4767 Diag(UserDeclaredMove->getLocation(),
4768 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004769 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004770 << UserDeclaredMove->isMoveAssignmentOperator();
4771 return true;
4772 }
4773 }
Sean Hunte16da072011-10-10 06:18:57 +00004774
Richard Smith5bdaac52012-04-02 20:59:25 +00004775 // Do access control from the special member function
4776 ContextRAII MethodContext(*this, MD);
4777
Richard Smith9a561d52012-02-26 09:11:52 +00004778 // C++11 [class.dtor]p5:
4779 // -- for a virtual destructor, lookup of the non-array deallocation function
4780 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004781 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004782 FunctionDecl *OperatorDelete = 0;
4783 DeclarationName Name =
4784 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4785 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004786 OperatorDelete, false)) {
4787 if (Diagnose)
4788 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004789 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004790 }
Richard Smith9a561d52012-02-26 09:11:52 +00004791 }
4792
Richard Smith6c4c36c2012-03-30 20:53:28 +00004793 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004794
Sean Huntcdee3fe2011-05-11 22:34:38 +00004795 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004796 BE = RD->bases_end(); BI != BE; ++BI)
4797 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004798 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004799 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004800
4801 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004802 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004803 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004804 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004805
4806 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004807 FE = RD->field_end(); FI != FE; ++FI)
4808 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004809 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004810 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004811
Richard Smith7d5088a2012-02-18 02:02:13 +00004812 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004813 return true;
4814
4815 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004816}
4817
Richard Smithac713512012-12-08 02:53:02 +00004818/// Perform lookup for a special member of the specified kind, and determine
4819/// whether it is trivial. If the triviality can be determined without the
4820/// lookup, skip it. This is intended for use when determining whether a
4821/// special member of a containing object is trivial, and thus does not ever
4822/// perform overload resolution for default constructors.
4823///
4824/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4825/// member that was most likely to be intended to be trivial, if any.
4826static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4827 Sema::CXXSpecialMember CSM, unsigned Quals,
4828 CXXMethodDecl **Selected) {
4829 if (Selected)
4830 *Selected = 0;
4831
4832 switch (CSM) {
4833 case Sema::CXXInvalid:
4834 llvm_unreachable("not a special member");
4835
4836 case Sema::CXXDefaultConstructor:
4837 // C++11 [class.ctor]p5:
4838 // A default constructor is trivial if:
4839 // - all the [direct subobjects] have trivial default constructors
4840 //
4841 // Note, no overload resolution is performed in this case.
4842 if (RD->hasTrivialDefaultConstructor())
4843 return true;
4844
4845 if (Selected) {
4846 // If there's a default constructor which could have been trivial, dig it
4847 // out. Otherwise, if there's any user-provided default constructor, point
4848 // to that as an example of why there's not a trivial one.
4849 CXXConstructorDecl *DefCtor = 0;
4850 if (RD->needsImplicitDefaultConstructor())
4851 S.DeclareImplicitDefaultConstructor(RD);
4852 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4853 CE = RD->ctor_end(); CI != CE; ++CI) {
4854 if (!CI->isDefaultConstructor())
4855 continue;
4856 DefCtor = *CI;
4857 if (!DefCtor->isUserProvided())
4858 break;
4859 }
4860
4861 *Selected = DefCtor;
4862 }
4863
4864 return false;
4865
4866 case Sema::CXXDestructor:
4867 // C++11 [class.dtor]p5:
4868 // A destructor is trivial if:
4869 // - all the direct [subobjects] have trivial destructors
4870 if (RD->hasTrivialDestructor())
4871 return true;
4872
4873 if (Selected) {
4874 if (RD->needsImplicitDestructor())
4875 S.DeclareImplicitDestructor(RD);
4876 *Selected = RD->getDestructor();
4877 }
4878
4879 return false;
4880
4881 case Sema::CXXCopyConstructor:
4882 // C++11 [class.copy]p12:
4883 // A copy constructor is trivial if:
4884 // - the constructor selected to copy each direct [subobject] is trivial
4885 if (RD->hasTrivialCopyConstructor()) {
4886 if (Quals == Qualifiers::Const)
4887 // We must either select the trivial copy constructor or reach an
4888 // ambiguity; no need to actually perform overload resolution.
4889 return true;
4890 } else if (!Selected) {
4891 return false;
4892 }
4893 // In C++98, we are not supposed to perform overload resolution here, but we
4894 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4895 // cases like B as having a non-trivial copy constructor:
4896 // struct A { template<typename T> A(T&); };
4897 // struct B { mutable A a; };
4898 goto NeedOverloadResolution;
4899
4900 case Sema::CXXCopyAssignment:
4901 // C++11 [class.copy]p25:
4902 // A copy assignment operator is trivial if:
4903 // - the assignment operator selected to copy each direct [subobject] is
4904 // trivial
4905 if (RD->hasTrivialCopyAssignment()) {
4906 if (Quals == Qualifiers::Const)
4907 return true;
4908 } else if (!Selected) {
4909 return false;
4910 }
4911 // In C++98, we are not supposed to perform overload resolution here, but we
4912 // treat that as a language defect.
4913 goto NeedOverloadResolution;
4914
4915 case Sema::CXXMoveConstructor:
4916 case Sema::CXXMoveAssignment:
4917 NeedOverloadResolution:
4918 Sema::SpecialMemberOverloadResult *SMOR =
4919 S.LookupSpecialMember(RD, CSM,
4920 Quals & Qualifiers::Const,
4921 Quals & Qualifiers::Volatile,
4922 /*RValueThis*/false, /*ConstThis*/false,
4923 /*VolatileThis*/false);
4924
4925 // The standard doesn't describe how to behave if the lookup is ambiguous.
4926 // We treat it as not making the member non-trivial, just like the standard
4927 // mandates for the default constructor. This should rarely matter, because
4928 // the member will also be deleted.
4929 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4930 return true;
4931
4932 if (!SMOR->getMethod()) {
4933 assert(SMOR->getKind() ==
4934 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
4935 return false;
4936 }
4937
4938 // We deliberately don't check if we found a deleted special member. We're
4939 // not supposed to!
4940 if (Selected)
4941 *Selected = SMOR->getMethod();
4942 return SMOR->getMethod()->isTrivial();
4943 }
4944
4945 llvm_unreachable("unknown special method kind");
4946}
4947
4948CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
4949 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
4950 CI != CE; ++CI)
4951 if (!CI->isImplicit())
4952 return *CI;
4953
4954 // Look for constructor templates.
4955 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
4956 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
4957 if (CXXConstructorDecl *CD =
4958 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
4959 return CD;
4960 }
4961
4962 return 0;
4963}
4964
4965/// The kind of subobject we are checking for triviality. The values of this
4966/// enumeration are used in diagnostics.
4967enum TrivialSubobjectKind {
4968 /// The subobject is a base class.
4969 TSK_BaseClass,
4970 /// The subobject is a non-static data member.
4971 TSK_Field,
4972 /// The object is actually the complete object.
4973 TSK_CompleteObject
4974};
4975
4976/// Check whether the special member selected for a given type would be trivial.
4977static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
4978 QualType SubType,
4979 Sema::CXXSpecialMember CSM,
4980 TrivialSubobjectKind Kind,
4981 bool Diagnose) {
4982 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
4983 if (!SubRD)
4984 return true;
4985
4986 CXXMethodDecl *Selected;
4987 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
4988 Diagnose ? &Selected : 0))
4989 return true;
4990
4991 if (Diagnose) {
4992 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
4993 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
4994 << Kind << SubType.getUnqualifiedType();
4995 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
4996 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
4997 } else if (!Selected)
4998 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
4999 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5000 else if (Selected->isUserProvided()) {
5001 if (Kind == TSK_CompleteObject)
5002 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5003 << Kind << SubType.getUnqualifiedType() << CSM;
5004 else {
5005 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5006 << Kind << SubType.getUnqualifiedType() << CSM;
5007 S.Diag(Selected->getLocation(), diag::note_declared_at);
5008 }
5009 } else {
5010 if (Kind != TSK_CompleteObject)
5011 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5012 << Kind << SubType.getUnqualifiedType() << CSM;
5013
5014 // Explain why the defaulted or deleted special member isn't trivial.
5015 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5016 }
5017 }
5018
5019 return false;
5020}
5021
5022/// Check whether the members of a class type allow a special member to be
5023/// trivial.
5024static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5025 Sema::CXXSpecialMember CSM,
5026 bool ConstArg, bool Diagnose) {
5027 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5028 FE = RD->field_end(); FI != FE; ++FI) {
5029 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5030 continue;
5031
5032 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5033
5034 // Pretend anonymous struct or union members are members of this class.
5035 if (FI->isAnonymousStructOrUnion()) {
5036 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5037 CSM, ConstArg, Diagnose))
5038 return false;
5039 continue;
5040 }
5041
5042 // C++11 [class.ctor]p5:
5043 // A default constructor is trivial if [...]
5044 // -- no non-static data member of its class has a
5045 // brace-or-equal-initializer
5046 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5047 if (Diagnose)
5048 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5049 return false;
5050 }
5051
5052 // Objective C ARC 4.3.5:
5053 // [...] nontrivally ownership-qualified types are [...] not trivially
5054 // default constructible, copy constructible, move constructible, copy
5055 // assignable, move assignable, or destructible [...]
5056 if (S.getLangOpts().ObjCAutoRefCount &&
5057 FieldType.hasNonTrivialObjCLifetime()) {
5058 if (Diagnose)
5059 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5060 << RD << FieldType.getObjCLifetime();
5061 return false;
5062 }
5063
5064 if (ConstArg && !FI->isMutable())
5065 FieldType.addConst();
5066 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5067 TSK_Field, Diagnose))
5068 return false;
5069 }
5070
5071 return true;
5072}
5073
5074/// Diagnose why the specified class does not have a trivial special member of
5075/// the given kind.
5076void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5077 QualType Ty = Context.getRecordType(RD);
5078 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5079 Ty.addConst();
5080
5081 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5082 TSK_CompleteObject, /*Diagnose*/true);
5083}
5084
5085/// Determine whether a defaulted or deleted special member function is trivial,
5086/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5087/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5088bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5089 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005090 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5091
5092 CXXRecordDecl *RD = MD->getParent();
5093
5094 bool ConstArg = false;
5095 ParmVarDecl *Param0 = MD->getNumParams() ? MD->getParamDecl(0) : 0;
5096
5097 // C++11 [class.copy]p12, p25:
5098 // A [special member] is trivial if its declared parameter type is the same
5099 // as if it had been implicitly declared [...]
5100 switch (CSM) {
5101 case CXXDefaultConstructor:
5102 case CXXDestructor:
5103 // Trivial default constructors and destructors cannot have parameters.
5104 break;
5105
5106 case CXXCopyConstructor:
5107 case CXXCopyAssignment: {
5108 // Trivial copy operations always have const, non-volatile parameter types.
5109 ConstArg = true;
5110 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5111 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5112 if (Diagnose)
5113 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5114 << Param0->getSourceRange() << Param0->getType()
5115 << Context.getLValueReferenceType(
5116 Context.getRecordType(RD).withConst());
5117 return false;
5118 }
5119 break;
5120 }
5121
5122 case CXXMoveConstructor:
5123 case CXXMoveAssignment: {
5124 // Trivial move operations always have non-cv-qualified parameters.
5125 const RValueReferenceType *RT =
5126 Param0->getType()->getAs<RValueReferenceType>();
5127 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5128 if (Diagnose)
5129 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5130 << Param0->getSourceRange() << Param0->getType()
5131 << Context.getRValueReferenceType(Context.getRecordType(RD));
5132 return false;
5133 }
5134 break;
5135 }
5136
5137 case CXXInvalid:
5138 llvm_unreachable("not a special member");
5139 }
5140
5141 // FIXME: We require that the parameter-declaration-clause is equivalent to
5142 // that of an implicit declaration, not just that the declared parameter type
5143 // matches, in order to prevent absuridities like a function simultaneously
5144 // being a trivial copy constructor and a non-trivial default constructor.
5145 // This issue has not yet been assigned a core issue number.
5146 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5147 if (Diagnose)
5148 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5149 diag::note_nontrivial_default_arg)
5150 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5151 return false;
5152 }
5153 if (MD->isVariadic()) {
5154 if (Diagnose)
5155 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5156 return false;
5157 }
5158
5159 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5160 // A copy/move [constructor or assignment operator] is trivial if
5161 // -- the [member] selected to copy/move each direct base class subobject
5162 // is trivial
5163 //
5164 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5165 // A [default constructor or destructor] is trivial if
5166 // -- all the direct base classes have trivial [default constructors or
5167 // destructors]
5168 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5169 BE = RD->bases_end(); BI != BE; ++BI)
5170 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5171 ConstArg ? BI->getType().withConst()
5172 : BI->getType(),
5173 CSM, TSK_BaseClass, Diagnose))
5174 return false;
5175
5176 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5177 // A copy/move [constructor or assignment operator] for a class X is
5178 // trivial if
5179 // -- for each non-static data member of X that is of class type (or array
5180 // thereof), the constructor selected to copy/move that member is
5181 // trivial
5182 //
5183 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5184 // A [default constructor or destructor] is trivial if
5185 // -- for all of the non-static data members of its class that are of class
5186 // type (or array thereof), each such class has a trivial [default
5187 // constructor or destructor]
5188 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5189 return false;
5190
5191 // C++11 [class.dtor]p5:
5192 // A destructor is trivial if [...]
5193 // -- the destructor is not virtual
5194 if (CSM == CXXDestructor && MD->isVirtual()) {
5195 if (Diagnose)
5196 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5197 return false;
5198 }
5199
5200 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5201 // A [special member] for class X is trivial if [...]
5202 // -- class X has no virtual functions and no virtual base classes
5203 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5204 if (!Diagnose)
5205 return false;
5206
5207 if (RD->getNumVBases()) {
5208 // Check for virtual bases. We already know that the corresponding
5209 // member in all bases is trivial, so vbases must all be direct.
5210 CXXBaseSpecifier &BS = *RD->vbases_begin();
5211 assert(BS.isVirtual());
5212 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5213 return false;
5214 }
5215
5216 // Must have a virtual method.
5217 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5218 ME = RD->method_end(); MI != ME; ++MI) {
5219 if (MI->isVirtual()) {
5220 SourceLocation MLoc = MI->getLocStart();
5221 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5222 return false;
5223 }
5224 }
5225
5226 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5227 }
5228
5229 // Looks like it's trivial!
5230 return true;
5231}
5232
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005233/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005234namespace {
5235 struct FindHiddenVirtualMethodData {
5236 Sema *S;
5237 CXXMethodDecl *Method;
5238 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005239 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005240 };
5241}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005242
David Blaikie5f750682012-10-19 00:53:08 +00005243/// \brief Check whether any most overriden method from MD in Methods
5244static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5245 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5246 if (MD->size_overridden_methods() == 0)
5247 return Methods.count(MD->getCanonicalDecl());
5248 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5249 E = MD->end_overridden_methods();
5250 I != E; ++I)
5251 if (CheckMostOverridenMethods(*I, Methods))
5252 return true;
5253 return false;
5254}
5255
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005256/// \brief Member lookup function that determines whether a given C++
5257/// method overloads virtual methods in a base class without overriding any,
5258/// to be used with CXXRecordDecl::lookupInBases().
5259static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5260 CXXBasePath &Path,
5261 void *UserData) {
5262 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5263
5264 FindHiddenVirtualMethodData &Data
5265 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5266
5267 DeclarationName Name = Data.Method->getDeclName();
5268 assert(Name.getNameKind() == DeclarationName::Identifier);
5269
5270 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005271 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005272 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005273 !Path.Decls.empty();
5274 Path.Decls = Path.Decls.slice(1)) {
5275 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005276 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005277 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005278 foundSameNameMethod = true;
5279 // Interested only in hidden virtual methods.
5280 if (!MD->isVirtual())
5281 continue;
5282 // If the method we are checking overrides a method from its base
5283 // don't warn about the other overloaded methods.
5284 if (!Data.S->IsOverload(Data.Method, MD, false))
5285 return true;
5286 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005287 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005288 overloadedMethods.push_back(MD);
5289 }
5290 }
5291
5292 if (foundSameNameMethod)
5293 Data.OverloadedMethods.append(overloadedMethods.begin(),
5294 overloadedMethods.end());
5295 return foundSameNameMethod;
5296}
5297
David Blaikie5f750682012-10-19 00:53:08 +00005298/// \brief Add the most overriden methods from MD to Methods
5299static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5300 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5301 if (MD->size_overridden_methods() == 0)
5302 Methods.insert(MD->getCanonicalDecl());
5303 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5304 E = MD->end_overridden_methods();
5305 I != E; ++I)
5306 AddMostOverridenMethods(*I, Methods);
5307}
5308
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005309/// \brief See if a method overloads virtual methods in a base class without
5310/// overriding any.
5311void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5312 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005313 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005314 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005315 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005316 return;
5317
5318 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5319 /*bool RecordPaths=*/false,
5320 /*bool DetectVirtual=*/false);
5321 FindHiddenVirtualMethodData Data;
5322 Data.Method = MD;
5323 Data.S = this;
5324
5325 // Keep the base methods that were overriden or introduced in the subclass
5326 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005327 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5328 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5329 NamedDecl *ND = *I;
5330 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005331 ND = shad->getTargetDecl();
5332 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5333 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005334 }
5335
5336 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5337 !Data.OverloadedMethods.empty()) {
5338 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5339 << MD << (Data.OverloadedMethods.size() > 1);
5340
5341 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5342 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5343 Diag(overloadedMD->getLocation(),
5344 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5345 }
5346 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005347}
5348
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005349void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005350 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005351 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005352 SourceLocation RBrac,
5353 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005354 if (!TagDecl)
5355 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005356
Douglas Gregor42af25f2009-05-11 19:58:34 +00005357 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005358
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005359 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5360 if (l->getKind() != AttributeList::AT_Visibility)
5361 continue;
5362 l->setInvalid();
5363 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5364 l->getName();
5365 }
5366
David Blaikie77b6de02011-09-22 02:58:26 +00005367 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005368 // strict aliasing violation!
5369 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005370 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005371
Douglas Gregor23c94db2010-07-02 17:43:08 +00005372 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005373 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005374}
5375
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005376/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5377/// special functions, such as the default constructor, copy
5378/// constructor, or destructor, to the given C++ class (C++
5379/// [special]p1). This routine can only be executed just before the
5380/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005381void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005382 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005383 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005384
Richard Smithbc2a35d2012-12-08 08:32:28 +00005385 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005386 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005387
Richard Smithbc2a35d2012-12-08 08:32:28 +00005388 // If the properties or semantics of the copy constructor couldn't be
5389 // determined while the class was being declared, force a declaration
5390 // of it now.
5391 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5392 DeclareImplicitCopyConstructor(ClassDecl);
5393 }
5394
Richard Smith80ad52f2013-01-02 11:42:31 +00005395 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005396 ++ASTContext::NumImplicitMoveConstructors;
5397
Richard Smithbc2a35d2012-12-08 08:32:28 +00005398 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5399 DeclareImplicitMoveConstructor(ClassDecl);
5400 }
5401
Douglas Gregora376d102010-07-02 21:50:04 +00005402 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5403 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005404
5405 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005406 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005407 // it shows up in the right place in the vtable and that we diagnose
5408 // problems with the implicit exception specification.
5409 if (ClassDecl->isDynamicClass() ||
5410 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005411 DeclareImplicitCopyAssignment(ClassDecl);
5412 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005413
Richard Smith80ad52f2013-01-02 11:42:31 +00005414 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005415 ++ASTContext::NumImplicitMoveAssignmentOperators;
5416
5417 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005418 if (ClassDecl->isDynamicClass() ||
5419 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005420 DeclareImplicitMoveAssignment(ClassDecl);
5421 }
5422
Douglas Gregor4923aa22010-07-02 20:37:36 +00005423 if (!ClassDecl->hasUserDeclaredDestructor()) {
5424 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005425
5426 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005427 // have to declare the destructor immediately. This ensures that, e.g., it
5428 // shows up in the right place in the vtable and that we diagnose problems
5429 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005430 if (ClassDecl->isDynamicClass() ||
5431 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005432 DeclareImplicitDestructor(ClassDecl);
5433 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005434}
5435
Francois Pichet8387e2a2011-04-22 22:18:13 +00005436void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5437 if (!D)
5438 return;
5439
5440 int NumParamList = D->getNumTemplateParameterLists();
5441 for (int i = 0; i < NumParamList; i++) {
5442 TemplateParameterList* Params = D->getTemplateParameterList(i);
5443 for (TemplateParameterList::iterator Param = Params->begin(),
5444 ParamEnd = Params->end();
5445 Param != ParamEnd; ++Param) {
5446 NamedDecl *Named = cast<NamedDecl>(*Param);
5447 if (Named->getDeclName()) {
5448 S->AddDecl(Named);
5449 IdResolver.AddDecl(Named);
5450 }
5451 }
5452 }
5453}
5454
John McCalld226f652010-08-21 09:40:31 +00005455void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005456 if (!D)
5457 return;
5458
5459 TemplateParameterList *Params = 0;
5460 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5461 Params = Template->getTemplateParameters();
5462 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5463 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5464 Params = PartialSpec->getTemplateParameters();
5465 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005466 return;
5467
Douglas Gregor6569d682009-05-27 23:11:45 +00005468 for (TemplateParameterList::iterator Param = Params->begin(),
5469 ParamEnd = Params->end();
5470 Param != ParamEnd; ++Param) {
5471 NamedDecl *Named = cast<NamedDecl>(*Param);
5472 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005473 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005474 IdResolver.AddDecl(Named);
5475 }
5476 }
5477}
5478
John McCalld226f652010-08-21 09:40:31 +00005479void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005480 if (!RecordD) return;
5481 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005482 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005483 PushDeclContext(S, Record);
5484}
5485
John McCalld226f652010-08-21 09:40:31 +00005486void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005487 if (!RecordD) return;
5488 PopDeclContext();
5489}
5490
Douglas Gregor72b505b2008-12-16 21:30:33 +00005491/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5492/// parsing a top-level (non-nested) C++ class, and we are now
5493/// parsing those parts of the given Method declaration that could
5494/// not be parsed earlier (C++ [class.mem]p2), such as default
5495/// arguments. This action should enter the scope of the given
5496/// Method declaration as if we had just parsed the qualified method
5497/// name. However, it should not bring the parameters into scope;
5498/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005499void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005500}
5501
5502/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5503/// C++ method declaration. We're (re-)introducing the given
5504/// function parameter into scope for use in parsing later parts of
5505/// the method declaration. For example, we could see an
5506/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005507void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005508 if (!ParamD)
5509 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005510
John McCalld226f652010-08-21 09:40:31 +00005511 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005512
5513 // If this parameter has an unparsed default argument, clear it out
5514 // to make way for the parsed default argument.
5515 if (Param->hasUnparsedDefaultArg())
5516 Param->setDefaultArg(0);
5517
John McCalld226f652010-08-21 09:40:31 +00005518 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005519 if (Param->getDeclName())
5520 IdResolver.AddDecl(Param);
5521}
5522
5523/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5524/// processing the delayed method declaration for Method. The method
5525/// declaration is now considered finished. There may be a separate
5526/// ActOnStartOfFunctionDef action later (not necessarily
5527/// immediately!) for this method, if it was also defined inside the
5528/// class body.
John McCalld226f652010-08-21 09:40:31 +00005529void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005530 if (!MethodD)
5531 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005532
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005533 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005534
John McCalld226f652010-08-21 09:40:31 +00005535 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005536
5537 // Now that we have our default arguments, check the constructor
5538 // again. It could produce additional diagnostics or affect whether
5539 // the class has implicitly-declared destructors, among other
5540 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005541 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5542 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005543
5544 // Check the default arguments, which we may have added.
5545 if (!Method->isInvalidDecl())
5546 CheckCXXDefaultArguments(Method);
5547}
5548
Douglas Gregor42a552f2008-11-05 20:51:48 +00005549/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005550/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005551/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005552/// emit diagnostics and set the invalid bit to true. In any case, the type
5553/// will be updated to reflect a well-formed type for the constructor and
5554/// returned.
5555QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005556 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005557 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005558
5559 // C++ [class.ctor]p3:
5560 // A constructor shall not be virtual (10.3) or static (9.4). A
5561 // constructor can be invoked for a const, volatile or const
5562 // volatile object. A constructor shall not be declared const,
5563 // volatile, or const volatile (9.3.2).
5564 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005565 if (!D.isInvalidType())
5566 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5567 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5568 << SourceRange(D.getIdentifierLoc());
5569 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005570 }
John McCalld931b082010-08-26 03:08:43 +00005571 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005572 if (!D.isInvalidType())
5573 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5574 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5575 << SourceRange(D.getIdentifierLoc());
5576 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005577 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005578 }
Mike Stump1eb44332009-09-09 15:08:12 +00005579
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005580 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005581 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005582 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005583 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5584 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005585 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005586 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5587 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005588 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005589 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5590 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005591 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005592 }
Mike Stump1eb44332009-09-09 15:08:12 +00005593
Douglas Gregorc938c162011-01-26 05:01:58 +00005594 // C++0x [class.ctor]p4:
5595 // A constructor shall not be declared with a ref-qualifier.
5596 if (FTI.hasRefQualifier()) {
5597 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5598 << FTI.RefQualifierIsLValueRef
5599 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5600 D.setInvalidType();
5601 }
5602
Douglas Gregor42a552f2008-11-05 20:51:48 +00005603 // Rebuild the function type "R" without any type qualifiers (in
5604 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005605 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005606 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005607 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5608 return R;
5609
5610 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5611 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005612 EPI.RefQualifier = RQ_None;
5613
Chris Lattner65401802009-04-25 08:28:21 +00005614 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005615 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005616}
5617
Douglas Gregor72b505b2008-12-16 21:30:33 +00005618/// CheckConstructor - Checks a fully-formed constructor for
5619/// well-formedness, issuing any diagnostics required. Returns true if
5620/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005621void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005622 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005623 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5624 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005625 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005626
5627 // C++ [class.copy]p3:
5628 // A declaration of a constructor for a class X is ill-formed if
5629 // its first parameter is of type (optionally cv-qualified) X and
5630 // either there are no other parameters or else all other
5631 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005632 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005633 ((Constructor->getNumParams() == 1) ||
5634 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005635 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5636 Constructor->getTemplateSpecializationKind()
5637 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005638 QualType ParamType = Constructor->getParamDecl(0)->getType();
5639 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5640 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005641 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005642 const char *ConstRef
5643 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5644 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005645 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005646 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005647
5648 // FIXME: Rather that making the constructor invalid, we should endeavor
5649 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005650 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005651 }
5652 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005653}
5654
John McCall15442822010-08-04 01:04:25 +00005655/// CheckDestructor - Checks a fully-formed destructor definition for
5656/// well-formedness, issuing any diagnostics required. Returns true
5657/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005658bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005659 CXXRecordDecl *RD = Destructor->getParent();
5660
5661 if (Destructor->isVirtual()) {
5662 SourceLocation Loc;
5663
5664 if (!Destructor->isImplicit())
5665 Loc = Destructor->getLocation();
5666 else
5667 Loc = RD->getLocation();
5668
5669 // If we have a virtual destructor, look up the deallocation function
5670 FunctionDecl *OperatorDelete = 0;
5671 DeclarationName Name =
5672 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005673 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005674 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005675
Eli Friedman5f2987c2012-02-02 03:46:19 +00005676 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005677
5678 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005679 }
Anders Carlsson37909802009-11-30 21:24:50 +00005680
5681 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005682}
5683
Mike Stump1eb44332009-09-09 15:08:12 +00005684static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005685FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5686 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5687 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005688 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005689}
5690
Douglas Gregor42a552f2008-11-05 20:51:48 +00005691/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5692/// the well-formednes of the destructor declarator @p D with type @p
5693/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005694/// emit diagnostics and set the declarator to invalid. Even if this happens,
5695/// will be updated to reflect a well-formed type for the destructor and
5696/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005697QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005698 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005699 // C++ [class.dtor]p1:
5700 // [...] A typedef-name that names a class is a class-name
5701 // (7.1.3); however, a typedef-name that names a class shall not
5702 // be used as the identifier in the declarator for a destructor
5703 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005704 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005705 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005706 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005707 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005708 else if (const TemplateSpecializationType *TST =
5709 DeclaratorType->getAs<TemplateSpecializationType>())
5710 if (TST->isTypeAlias())
5711 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5712 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005713
5714 // C++ [class.dtor]p2:
5715 // A destructor is used to destroy objects of its class type. A
5716 // destructor takes no parameters, and no return type can be
5717 // specified for it (not even void). The address of a destructor
5718 // shall not be taken. A destructor shall not be static. A
5719 // destructor can be invoked for a const, volatile or const
5720 // volatile object. A destructor shall not be declared const,
5721 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005722 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005723 if (!D.isInvalidType())
5724 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5725 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005726 << SourceRange(D.getIdentifierLoc())
5727 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5728
John McCalld931b082010-08-26 03:08:43 +00005729 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005730 }
Chris Lattner65401802009-04-25 08:28:21 +00005731 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005732 // Destructors don't have return types, but the parser will
5733 // happily parse something like:
5734 //
5735 // class X {
5736 // float ~X();
5737 // };
5738 //
5739 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005740 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5741 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5742 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005743 }
Mike Stump1eb44332009-09-09 15:08:12 +00005744
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005745 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005746 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005747 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005748 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5749 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005750 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005751 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5752 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005753 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005754 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5755 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005756 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005757 }
5758
Douglas Gregorc938c162011-01-26 05:01:58 +00005759 // C++0x [class.dtor]p2:
5760 // A destructor shall not be declared with a ref-qualifier.
5761 if (FTI.hasRefQualifier()) {
5762 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5763 << FTI.RefQualifierIsLValueRef
5764 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5765 D.setInvalidType();
5766 }
5767
Douglas Gregor42a552f2008-11-05 20:51:48 +00005768 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005769 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005770 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5771
5772 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005773 FTI.freeArgs();
5774 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005775 }
5776
Mike Stump1eb44332009-09-09 15:08:12 +00005777 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005778 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005779 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005780 D.setInvalidType();
5781 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005782
5783 // Rebuild the function type "R" without any type qualifiers or
5784 // parameters (in case any of the errors above fired) and with
5785 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005786 // types.
John McCalle23cf432010-12-14 08:05:40 +00005787 if (!D.isInvalidType())
5788 return R;
5789
Douglas Gregord92ec472010-07-01 05:10:53 +00005790 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005791 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5792 EPI.Variadic = false;
5793 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005794 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005795 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005796}
5797
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005798/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5799/// well-formednes of the conversion function declarator @p D with
5800/// type @p R. If there are any errors in the declarator, this routine
5801/// will emit diagnostics and return true. Otherwise, it will return
5802/// false. Either way, the type @p R will be updated to reflect a
5803/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005804void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005805 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005806 // C++ [class.conv.fct]p1:
5807 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005808 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005809 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005810 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005811 if (!D.isInvalidType())
5812 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5813 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5814 << SourceRange(D.getIdentifierLoc());
5815 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005816 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005817 }
John McCalla3f81372010-04-13 00:04:31 +00005818
5819 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5820
Chris Lattner6e475012009-04-25 08:35:12 +00005821 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005822 // Conversion functions don't have return types, but the parser will
5823 // happily parse something like:
5824 //
5825 // class X {
5826 // float operator bool();
5827 // };
5828 //
5829 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005830 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5831 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5832 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005833 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005834 }
5835
John McCalla3f81372010-04-13 00:04:31 +00005836 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5837
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005838 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005839 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005840 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5841
5842 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005843 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005844 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005845 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005846 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005847 D.setInvalidType();
5848 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005849
John McCalla3f81372010-04-13 00:04:31 +00005850 // Diagnose "&operator bool()" and other such nonsense. This
5851 // is actually a gcc extension which we don't support.
5852 if (Proto->getResultType() != ConvType) {
5853 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5854 << Proto->getResultType();
5855 D.setInvalidType();
5856 ConvType = Proto->getResultType();
5857 }
5858
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005859 // C++ [class.conv.fct]p4:
5860 // The conversion-type-id shall not represent a function type nor
5861 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005862 if (ConvType->isArrayType()) {
5863 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5864 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005865 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005866 } else if (ConvType->isFunctionType()) {
5867 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5868 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005869 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005870 }
5871
5872 // Rebuild the function type "R" without any parameters (in case any
5873 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005874 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005875 if (D.isInvalidType())
5876 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005877
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005878 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005879 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005880 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005881 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005882 diag::warn_cxx98_compat_explicit_conversion_functions :
5883 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005884 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005885}
5886
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005887/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5888/// the declaration of the given C++ conversion function. This routine
5889/// is responsible for recording the conversion function in the C++
5890/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005891Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005892 assert(Conversion && "Expected to receive a conversion function declaration");
5893
Douglas Gregor9d350972008-12-12 08:25:50 +00005894 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005895
5896 // Make sure we aren't redeclaring the conversion function.
5897 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005898
5899 // C++ [class.conv.fct]p1:
5900 // [...] A conversion function is never used to convert a
5901 // (possibly cv-qualified) object to the (possibly cv-qualified)
5902 // same object type (or a reference to it), to a (possibly
5903 // cv-qualified) base class of that type (or a reference to it),
5904 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005905 // FIXME: Suppress this warning if the conversion function ends up being a
5906 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005907 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005908 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005909 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005910 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005911 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5912 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005913 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005914 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005915 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5916 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005917 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005918 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005919 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005920 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005921 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005922 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005923 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005924 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005925 }
5926
Douglas Gregore80622f2010-09-29 04:25:11 +00005927 if (FunctionTemplateDecl *ConversionTemplate
5928 = Conversion->getDescribedFunctionTemplate())
5929 return ConversionTemplate;
5930
John McCalld226f652010-08-21 09:40:31 +00005931 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005932}
5933
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005934//===----------------------------------------------------------------------===//
5935// Namespace Handling
5936//===----------------------------------------------------------------------===//
5937
Richard Smithd1a55a62012-10-04 22:13:39 +00005938/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
5939/// reopened.
5940static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
5941 SourceLocation Loc,
5942 IdentifierInfo *II, bool *IsInline,
5943 NamespaceDecl *PrevNS) {
5944 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00005945
Richard Smithc969e6a2012-10-05 01:46:25 +00005946 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
5947 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
5948 // inline namespaces, with the intention of bringing names into namespace std.
5949 //
5950 // We support this just well enough to get that case working; this is not
5951 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00005952 if (*IsInline && II && II->getName().startswith("__atomic") &&
5953 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00005954 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00005955 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
5956 NS = NS->getPreviousDecl())
5957 NS->setInline(*IsInline);
5958 // Patch up the lookup table for the containing namespace. This isn't really
5959 // correct, but it's good enough for this particular case.
5960 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
5961 E = PrevNS->decls_end(); I != E; ++I)
5962 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
5963 PrevNS->getParent()->makeDeclVisibleInContext(ND);
5964 return;
5965 }
5966
5967 if (PrevNS->isInline())
5968 // The user probably just forgot the 'inline', so suggest that it
5969 // be added back.
5970 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5971 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
5972 else
5973 S.Diag(Loc, diag::err_inline_namespace_mismatch)
5974 << IsInline;
5975
5976 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
5977 *IsInline = PrevNS->isInline();
5978}
John McCallea318642010-08-26 09:15:37 +00005979
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005980/// ActOnStartNamespaceDef - This is called at the start of a namespace
5981/// definition.
John McCalld226f652010-08-21 09:40:31 +00005982Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005983 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005984 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005985 SourceLocation IdentLoc,
5986 IdentifierInfo *II,
5987 SourceLocation LBrace,
5988 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005989 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5990 // For anonymous namespace, take the location of the left brace.
5991 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005992 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005993 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005994 bool IsStd = false;
5995 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005996 Scope *DeclRegionScope = NamespcScope->getParent();
5997
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005998 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005999 if (II) {
6000 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006001 // The identifier in an original-namespace-definition shall not
6002 // have been previously defined in the declarative region in
6003 // which the original-namespace-definition appears. The
6004 // identifier in an original-namespace-definition is the name of
6005 // the namespace. Subsequently in that declarative region, it is
6006 // treated as an original-namespace-name.
6007 //
6008 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006009 // look through using directives, just look for any ordinary names.
6010
6011 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006012 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6013 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006014 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006015 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6016 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6017 ++I) {
6018 if ((*I)->getIdentifierNamespace() & IDNS) {
6019 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006020 break;
6021 }
6022 }
6023
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006024 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6025
6026 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006027 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006028 if (IsInline != PrevNS->isInline())
6029 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6030 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006031 } else if (PrevDecl) {
6032 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006033 Diag(Loc, diag::err_redefinition_different_kind)
6034 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006035 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006036 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006037 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006038 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006039 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006040 // This is the first "real" definition of the namespace "std", so update
6041 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006042 PrevNS = getStdNamespace();
6043 IsStd = true;
6044 AddToKnown = !IsInline;
6045 } else {
6046 // We've seen this namespace for the first time.
6047 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006048 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006049 } else {
John McCall9aeed322009-10-01 00:25:31 +00006050 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006051
6052 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006053 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006054 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006055 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006056 } else {
6057 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006058 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006059 }
6060
Richard Smithd1a55a62012-10-04 22:13:39 +00006061 if (PrevNS && IsInline != PrevNS->isInline())
6062 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6063 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006064 }
6065
6066 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6067 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006068 if (IsInvalid)
6069 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006070
6071 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006072
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006073 // FIXME: Should we be merging attributes?
6074 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006075 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006076
6077 if (IsStd)
6078 StdNamespace = Namespc;
6079 if (AddToKnown)
6080 KnownNamespaces[Namespc] = false;
6081
6082 if (II) {
6083 PushOnScopeChains(Namespc, DeclRegionScope);
6084 } else {
6085 // Link the anonymous namespace into its parent.
6086 DeclContext *Parent = CurContext->getRedeclContext();
6087 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6088 TU->setAnonymousNamespace(Namespc);
6089 } else {
6090 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006091 }
John McCall9aeed322009-10-01 00:25:31 +00006092
Douglas Gregora4181472010-03-24 00:46:35 +00006093 CurContext->addDecl(Namespc);
6094
John McCall9aeed322009-10-01 00:25:31 +00006095 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6096 // behaves as if it were replaced by
6097 // namespace unique { /* empty body */ }
6098 // using namespace unique;
6099 // namespace unique { namespace-body }
6100 // where all occurrences of 'unique' in a translation unit are
6101 // replaced by the same identifier and this identifier differs
6102 // from all other identifiers in the entire program.
6103
6104 // We just create the namespace with an empty name and then add an
6105 // implicit using declaration, just like the standard suggests.
6106 //
6107 // CodeGen enforces the "universally unique" aspect by giving all
6108 // declarations semantically contained within an anonymous
6109 // namespace internal linkage.
6110
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006111 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006112 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006113 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006114 /* 'using' */ LBrace,
6115 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006116 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006117 /* identifier */ SourceLocation(),
6118 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006119 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006120 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006121 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006122 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006123 }
6124
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006125 ActOnDocumentableDecl(Namespc);
6126
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006127 // Although we could have an invalid decl (i.e. the namespace name is a
6128 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006129 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6130 // for the namespace has the declarations that showed up in that particular
6131 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006132 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006133 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006134}
6135
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006136/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6137/// is a namespace alias, returns the namespace it points to.
6138static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6139 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6140 return AD->getNamespace();
6141 return dyn_cast_or_null<NamespaceDecl>(D);
6142}
6143
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006144/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6145/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006146void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006147 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6148 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006149 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006150 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006151 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006152 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006153}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006154
John McCall384aff82010-08-25 07:42:41 +00006155CXXRecordDecl *Sema::getStdBadAlloc() const {
6156 return cast_or_null<CXXRecordDecl>(
6157 StdBadAlloc.get(Context.getExternalSource()));
6158}
6159
6160NamespaceDecl *Sema::getStdNamespace() const {
6161 return cast_or_null<NamespaceDecl>(
6162 StdNamespace.get(Context.getExternalSource()));
6163}
6164
Douglas Gregor66992202010-06-29 17:53:46 +00006165/// \brief Retrieve the special "std" namespace, which may require us to
6166/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006167NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006168 if (!StdNamespace) {
6169 // The "std" namespace has not yet been defined, so build one implicitly.
6170 StdNamespace = NamespaceDecl::Create(Context,
6171 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006172 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006173 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006174 &PP.getIdentifierTable().get("std"),
6175 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006176 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006177 }
6178
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006179 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006180}
6181
Sebastian Redl395e04d2012-01-17 22:49:33 +00006182bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006183 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006184 "Looking for std::initializer_list outside of C++.");
6185
6186 // We're looking for implicit instantiations of
6187 // template <typename E> class std::initializer_list.
6188
6189 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6190 return false;
6191
Sebastian Redl84760e32012-01-17 22:49:58 +00006192 ClassTemplateDecl *Template = 0;
6193 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006194
Sebastian Redl84760e32012-01-17 22:49:58 +00006195 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006196
Sebastian Redl84760e32012-01-17 22:49:58 +00006197 ClassTemplateSpecializationDecl *Specialization =
6198 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6199 if (!Specialization)
6200 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006201
Sebastian Redl84760e32012-01-17 22:49:58 +00006202 Template = Specialization->getSpecializedTemplate();
6203 Arguments = Specialization->getTemplateArgs().data();
6204 } else if (const TemplateSpecializationType *TST =
6205 Ty->getAs<TemplateSpecializationType>()) {
6206 Template = dyn_cast_or_null<ClassTemplateDecl>(
6207 TST->getTemplateName().getAsTemplateDecl());
6208 Arguments = TST->getArgs();
6209 }
6210 if (!Template)
6211 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006212
6213 if (!StdInitializerList) {
6214 // Haven't recognized std::initializer_list yet, maybe this is it.
6215 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6216 if (TemplateClass->getIdentifier() !=
6217 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006218 !getStdNamespace()->InEnclosingNamespaceSetOf(
6219 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006220 return false;
6221 // This is a template called std::initializer_list, but is it the right
6222 // template?
6223 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006224 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006225 return false;
6226 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6227 return false;
6228
6229 // It's the right template.
6230 StdInitializerList = Template;
6231 }
6232
6233 if (Template != StdInitializerList)
6234 return false;
6235
6236 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006237 if (Element)
6238 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006239 return true;
6240}
6241
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006242static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6243 NamespaceDecl *Std = S.getStdNamespace();
6244 if (!Std) {
6245 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6246 return 0;
6247 }
6248
6249 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6250 Loc, Sema::LookupOrdinaryName);
6251 if (!S.LookupQualifiedName(Result, Std)) {
6252 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6253 return 0;
6254 }
6255 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6256 if (!Template) {
6257 Result.suppressDiagnostics();
6258 // We found something weird. Complain about the first thing we found.
6259 NamedDecl *Found = *Result.begin();
6260 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6261 return 0;
6262 }
6263
6264 // We found some template called std::initializer_list. Now verify that it's
6265 // correct.
6266 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006267 if (Params->getMinRequiredArguments() != 1 ||
6268 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006269 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6270 return 0;
6271 }
6272
6273 return Template;
6274}
6275
6276QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6277 if (!StdInitializerList) {
6278 StdInitializerList = LookupStdInitializerList(*this, Loc);
6279 if (!StdInitializerList)
6280 return QualType();
6281 }
6282
6283 TemplateArgumentListInfo Args(Loc, Loc);
6284 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6285 Context.getTrivialTypeSourceInfo(Element,
6286 Loc)));
6287 return Context.getCanonicalType(
6288 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6289}
6290
Sebastian Redl98d36062012-01-17 22:50:14 +00006291bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6292 // C++ [dcl.init.list]p2:
6293 // A constructor is an initializer-list constructor if its first parameter
6294 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6295 // std::initializer_list<E> for some type E, and either there are no other
6296 // parameters or else all other parameters have default arguments.
6297 if (Ctor->getNumParams() < 1 ||
6298 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6299 return false;
6300
6301 QualType ArgType = Ctor->getParamDecl(0)->getType();
6302 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6303 ArgType = RT->getPointeeType().getUnqualifiedType();
6304
6305 return isStdInitializerList(ArgType, 0);
6306}
6307
Douglas Gregor9172aa62011-03-26 22:25:30 +00006308/// \brief Determine whether a using statement is in a context where it will be
6309/// apply in all contexts.
6310static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6311 switch (CurContext->getDeclKind()) {
6312 case Decl::TranslationUnit:
6313 return true;
6314 case Decl::LinkageSpec:
6315 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6316 default:
6317 return false;
6318 }
6319}
6320
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006321namespace {
6322
6323// Callback to only accept typo corrections that are namespaces.
6324class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6325 public:
6326 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6327 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6328 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6329 }
6330 return false;
6331 }
6332};
6333
6334}
6335
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006336static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6337 CXXScopeSpec &SS,
6338 SourceLocation IdentLoc,
6339 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006340 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006341 R.clear();
6342 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006343 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006344 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006345 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6346 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006347 if (DeclContext *DC = S.computeDeclContext(SS, false))
6348 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6349 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006350 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6351 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006352 else
6353 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6354 << Ident << CorrectedQuotedStr
6355 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006356
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006357 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6358 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006359
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006360 R.addDecl(Corrected.getCorrectionDecl());
6361 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006362 }
6363 return false;
6364}
6365
John McCalld226f652010-08-21 09:40:31 +00006366Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006367 SourceLocation UsingLoc,
6368 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006369 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006370 SourceLocation IdentLoc,
6371 IdentifierInfo *NamespcName,
6372 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006373 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6374 assert(NamespcName && "Invalid NamespcName.");
6375 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006376
6377 // This can only happen along a recovery path.
6378 while (S->getFlags() & Scope::TemplateParamScope)
6379 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006380 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006381
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006382 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006383 NestedNameSpecifier *Qualifier = 0;
6384 if (SS.isSet())
6385 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6386
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006387 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006388 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6389 LookupParsedName(R, S, &SS);
6390 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006391 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006392
Douglas Gregor66992202010-06-29 17:53:46 +00006393 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006394 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006395 // Allow "using namespace std;" or "using namespace ::std;" even if
6396 // "std" hasn't been defined yet, for GCC compatibility.
6397 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6398 NamespcName->isStr("std")) {
6399 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006400 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006401 R.resolveKind();
6402 }
6403 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006404 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006405 }
6406
John McCallf36e02d2009-10-09 21:13:30 +00006407 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006408 NamedDecl *Named = R.getFoundDecl();
6409 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6410 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006411 // C++ [namespace.udir]p1:
6412 // A using-directive specifies that the names in the nominated
6413 // namespace can be used in the scope in which the
6414 // using-directive appears after the using-directive. During
6415 // unqualified name lookup (3.4.1), the names appear as if they
6416 // were declared in the nearest enclosing namespace which
6417 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006418 // namespace. [Note: in this context, "contains" means "contains
6419 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006420
6421 // Find enclosing context containing both using-directive and
6422 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006423 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006424 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6425 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6426 CommonAncestor = CommonAncestor->getParent();
6427
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006428 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006429 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006430 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006431
Douglas Gregor9172aa62011-03-26 22:25:30 +00006432 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006433 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006434 Diag(IdentLoc, diag::warn_using_directive_in_header);
6435 }
6436
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006437 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006438 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006439 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006440 }
6441
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006442 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006443 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006444}
6445
6446void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006447 // If the scope has an associated entity and the using directive is at
6448 // namespace or translation unit scope, add the UsingDirectiveDecl into
6449 // its lookup structure so qualified name lookup can find it.
6450 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6451 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006452 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006453 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006454 // Otherwise, it is at block sope. The using-directives will affect lookup
6455 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006456 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006457}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006458
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006459
John McCalld226f652010-08-21 09:40:31 +00006460Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006461 AccessSpecifier AS,
6462 bool HasUsingKeyword,
6463 SourceLocation UsingLoc,
6464 CXXScopeSpec &SS,
6465 UnqualifiedId &Name,
6466 AttributeList *AttrList,
6467 bool IsTypeName,
6468 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006469 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006470
Douglas Gregor12c118a2009-11-04 16:30:06 +00006471 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006472 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006473 case UnqualifiedId::IK_Identifier:
6474 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006475 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006476 case UnqualifiedId::IK_ConversionFunctionId:
6477 break;
6478
6479 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006480 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006481 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006482 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006483 getLangOpts().CPlusPlus11 ?
Richard Smitha1366cb2012-04-27 19:33:05 +00006484 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
6485 // instead once inheriting constructors work.
6486 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00006487 diag::err_using_decl_constructor)
6488 << SS.getRange();
6489
Richard Smith80ad52f2013-01-02 11:42:31 +00006490 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006491
John McCalld226f652010-08-21 09:40:31 +00006492 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006493
6494 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006495 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006496 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006497 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006498
6499 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006500 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006501 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006502 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006503 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006504
6505 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6506 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006507 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006508 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006509
John McCall60fa3cf2009-12-11 02:10:03 +00006510 // Warn about using declarations.
6511 // TODO: store that the declaration was written without 'using' and
6512 // talk about access decls instead of using decls in the
6513 // diagnostics.
6514 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006515 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006516
6517 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006518 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006519 }
6520
Douglas Gregor56c04582010-12-16 00:46:58 +00006521 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6522 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6523 return 0;
6524
John McCall9488ea12009-11-17 05:59:44 +00006525 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006526 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006527 /* IsInstantiation */ false,
6528 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006529 if (UD)
6530 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006531
John McCalld226f652010-08-21 09:40:31 +00006532 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006533}
6534
Douglas Gregor09acc982010-07-07 23:08:52 +00006535/// \brief Determine whether a using declaration considers the given
6536/// declarations as "equivalent", e.g., if they are redeclarations of
6537/// the same entity or are both typedefs of the same type.
6538static bool
6539IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6540 bool &SuppressRedeclaration) {
6541 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6542 SuppressRedeclaration = false;
6543 return true;
6544 }
6545
Richard Smith162e1c12011-04-15 14:24:37 +00006546 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6547 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006548 SuppressRedeclaration = true;
6549 return Context.hasSameType(TD1->getUnderlyingType(),
6550 TD2->getUnderlyingType());
6551 }
6552
6553 return false;
6554}
6555
6556
John McCall9f54ad42009-12-10 09:41:52 +00006557/// Determines whether to create a using shadow decl for a particular
6558/// decl, given the set of decls existing prior to this using lookup.
6559bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6560 const LookupResult &Previous) {
6561 // Diagnose finding a decl which is not from a base class of the
6562 // current class. We do this now because there are cases where this
6563 // function will silently decide not to build a shadow decl, which
6564 // will pre-empt further diagnostics.
6565 //
6566 // We don't need to do this in C++0x because we do the check once on
6567 // the qualifier.
6568 //
6569 // FIXME: diagnose the following if we care enough:
6570 // struct A { int foo; };
6571 // struct B : A { using A::foo; };
6572 // template <class T> struct C : A {};
6573 // template <class T> struct D : C<T> { using B::foo; } // <---
6574 // This is invalid (during instantiation) in C++03 because B::foo
6575 // resolves to the using decl in B, which is not a base class of D<T>.
6576 // We can't diagnose it immediately because C<T> is an unknown
6577 // specialization. The UsingShadowDecl in D<T> then points directly
6578 // to A::foo, which will look well-formed when we instantiate.
6579 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006580 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006581 DeclContext *OrigDC = Orig->getDeclContext();
6582
6583 // Handle enums and anonymous structs.
6584 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6585 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6586 while (OrigRec->isAnonymousStructOrUnion())
6587 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6588
6589 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6590 if (OrigDC == CurContext) {
6591 Diag(Using->getLocation(),
6592 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006593 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006594 Diag(Orig->getLocation(), diag::note_using_decl_target);
6595 return true;
6596 }
6597
Douglas Gregordc355712011-02-25 00:36:19 +00006598 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006599 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006600 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006601 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006602 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006603 Diag(Orig->getLocation(), diag::note_using_decl_target);
6604 return true;
6605 }
6606 }
6607
6608 if (Previous.empty()) return false;
6609
6610 NamedDecl *Target = Orig;
6611 if (isa<UsingShadowDecl>(Target))
6612 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6613
John McCalld7533ec2009-12-11 02:33:26 +00006614 // If the target happens to be one of the previous declarations, we
6615 // don't have a conflict.
6616 //
6617 // FIXME: but we might be increasing its access, in which case we
6618 // should redeclare it.
6619 NamedDecl *NonTag = 0, *Tag = 0;
6620 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6621 I != E; ++I) {
6622 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006623 bool Result;
6624 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6625 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006626
6627 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6628 }
6629
John McCall9f54ad42009-12-10 09:41:52 +00006630 if (Target->isFunctionOrFunctionTemplate()) {
6631 FunctionDecl *FD;
6632 if (isa<FunctionTemplateDecl>(Target))
6633 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6634 else
6635 FD = cast<FunctionDecl>(Target);
6636
6637 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006638 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006639 case Ovl_Overload:
6640 return false;
6641
6642 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006643 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006644 break;
6645
6646 // We found a decl with the exact signature.
6647 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006648 // If we're in a record, we want to hide the target, so we
6649 // return true (without a diagnostic) to tell the caller not to
6650 // build a shadow decl.
6651 if (CurContext->isRecord())
6652 return true;
6653
6654 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006655 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006656 break;
6657 }
6658
6659 Diag(Target->getLocation(), diag::note_using_decl_target);
6660 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6661 return true;
6662 }
6663
6664 // Target is not a function.
6665
John McCall9f54ad42009-12-10 09:41:52 +00006666 if (isa<TagDecl>(Target)) {
6667 // No conflict between a tag and a non-tag.
6668 if (!Tag) return false;
6669
John McCall41ce66f2009-12-10 19:51:03 +00006670 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006671 Diag(Target->getLocation(), diag::note_using_decl_target);
6672 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6673 return true;
6674 }
6675
6676 // No conflict between a tag and a non-tag.
6677 if (!NonTag) return false;
6678
John McCall41ce66f2009-12-10 19:51:03 +00006679 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006680 Diag(Target->getLocation(), diag::note_using_decl_target);
6681 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6682 return true;
6683}
6684
John McCall9488ea12009-11-17 05:59:44 +00006685/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006686UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006687 UsingDecl *UD,
6688 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006689
6690 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006691 NamedDecl *Target = Orig;
6692 if (isa<UsingShadowDecl>(Target)) {
6693 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6694 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006695 }
6696
6697 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006698 = UsingShadowDecl::Create(Context, CurContext,
6699 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006700 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006701
6702 Shadow->setAccess(UD->getAccess());
6703 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6704 Shadow->setInvalidDecl();
6705
John McCall9488ea12009-11-17 05:59:44 +00006706 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006707 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006708 else
John McCall604e7f12009-12-08 07:46:18 +00006709 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006710
John McCall604e7f12009-12-08 07:46:18 +00006711
John McCall9f54ad42009-12-10 09:41:52 +00006712 return Shadow;
6713}
John McCall604e7f12009-12-08 07:46:18 +00006714
John McCall9f54ad42009-12-10 09:41:52 +00006715/// Hides a using shadow declaration. This is required by the current
6716/// using-decl implementation when a resolvable using declaration in a
6717/// class is followed by a declaration which would hide or override
6718/// one or more of the using decl's targets; for example:
6719///
6720/// struct Base { void foo(int); };
6721/// struct Derived : Base {
6722/// using Base::foo;
6723/// void foo(int);
6724/// };
6725///
6726/// The governing language is C++03 [namespace.udecl]p12:
6727///
6728/// When a using-declaration brings names from a base class into a
6729/// derived class scope, member functions in the derived class
6730/// override and/or hide member functions with the same name and
6731/// parameter types in a base class (rather than conflicting).
6732///
6733/// There are two ways to implement this:
6734/// (1) optimistically create shadow decls when they're not hidden
6735/// by existing declarations, or
6736/// (2) don't create any shadow decls (or at least don't make them
6737/// visible) until we've fully parsed/instantiated the class.
6738/// The problem with (1) is that we might have to retroactively remove
6739/// a shadow decl, which requires several O(n) operations because the
6740/// decl structures are (very reasonably) not designed for removal.
6741/// (2) avoids this but is very fiddly and phase-dependent.
6742void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006743 if (Shadow->getDeclName().getNameKind() ==
6744 DeclarationName::CXXConversionFunctionName)
6745 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6746
John McCall9f54ad42009-12-10 09:41:52 +00006747 // Remove it from the DeclContext...
6748 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006749
John McCall9f54ad42009-12-10 09:41:52 +00006750 // ...and the scope, if applicable...
6751 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006752 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006753 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006754 }
6755
John McCall9f54ad42009-12-10 09:41:52 +00006756 // ...and the using decl.
6757 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6758
6759 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006760 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006761}
6762
John McCall7ba107a2009-11-18 02:36:19 +00006763/// Builds a using declaration.
6764///
6765/// \param IsInstantiation - Whether this call arises from an
6766/// instantiation of an unresolved using declaration. We treat
6767/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006768NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6769 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006770 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006771 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006772 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006773 bool IsInstantiation,
6774 bool IsTypeName,
6775 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006776 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006777 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006778 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006779
Anders Carlsson550b14b2009-08-28 05:49:21 +00006780 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006781
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006782 if (SS.isEmpty()) {
6783 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006784 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006785 }
Mike Stump1eb44332009-09-09 15:08:12 +00006786
John McCall9f54ad42009-12-10 09:41:52 +00006787 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006788 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006789 ForRedeclaration);
6790 Previous.setHideTags(false);
6791 if (S) {
6792 LookupName(Previous, S);
6793
6794 // It is really dumb that we have to do this.
6795 LookupResult::Filter F = Previous.makeFilter();
6796 while (F.hasNext()) {
6797 NamedDecl *D = F.next();
6798 if (!isDeclInScope(D, CurContext, S))
6799 F.erase();
6800 }
6801 F.done();
6802 } else {
6803 assert(IsInstantiation && "no scope in non-instantiation");
6804 assert(CurContext->isRecord() && "scope not record in instantiation");
6805 LookupQualifiedName(Previous, CurContext);
6806 }
6807
John McCall9f54ad42009-12-10 09:41:52 +00006808 // Check for invalid redeclarations.
6809 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6810 return 0;
6811
6812 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006813 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6814 return 0;
6815
John McCallaf8e6ed2009-11-12 03:15:40 +00006816 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006817 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006818 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006819 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006820 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006821 // FIXME: not all declaration name kinds are legal here
6822 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6823 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006824 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006825 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006826 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006827 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6828 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006829 }
John McCalled976492009-12-04 22:46:56 +00006830 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006831 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6832 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006833 }
John McCalled976492009-12-04 22:46:56 +00006834 D->setAccess(AS);
6835 CurContext->addDecl(D);
6836
6837 if (!LookupContext) return D;
6838 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006839
John McCall77bb1aa2010-05-01 00:40:08 +00006840 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006841 UD->setInvalidDecl();
6842 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006843 }
6844
Richard Smithc5a89a12012-04-02 01:30:27 +00006845 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006846 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006847 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006848 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006849 return UD;
6850 }
6851
6852 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006853
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006854 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006855
John McCall604e7f12009-12-08 07:46:18 +00006856 // Unlike most lookups, we don't always want to hide tag
6857 // declarations: tag names are visible through the using declaration
6858 // even if hidden by ordinary names, *except* in a dependent context
6859 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006860 if (!IsInstantiation)
6861 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006862
John McCallb9abd8722012-04-07 03:04:20 +00006863 // For the purposes of this lookup, we have a base object type
6864 // equal to that of the current context.
6865 if (CurContext->isRecord()) {
6866 R.setBaseObjectType(
6867 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6868 }
6869
John McCalla24dc2e2009-11-17 02:14:36 +00006870 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006871
John McCallf36e02d2009-10-09 21:13:30 +00006872 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006873 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006874 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006875 UD->setInvalidDecl();
6876 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006877 }
6878
John McCalled976492009-12-04 22:46:56 +00006879 if (R.isAmbiguous()) {
6880 UD->setInvalidDecl();
6881 return UD;
6882 }
Mike Stump1eb44332009-09-09 15:08:12 +00006883
John McCall7ba107a2009-11-18 02:36:19 +00006884 if (IsTypeName) {
6885 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006886 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006887 Diag(IdentLoc, diag::err_using_typename_non_type);
6888 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6889 Diag((*I)->getUnderlyingDecl()->getLocation(),
6890 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006891 UD->setInvalidDecl();
6892 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006893 }
6894 } else {
6895 // If we asked for a non-typename and we got a type, error out,
6896 // but only if this is an instantiation of an unresolved using
6897 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006898 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006899 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6900 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006901 UD->setInvalidDecl();
6902 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006903 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006904 }
6905
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006906 // C++0x N2914 [namespace.udecl]p6:
6907 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006908 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006909 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6910 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006911 UD->setInvalidDecl();
6912 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006913 }
Mike Stump1eb44332009-09-09 15:08:12 +00006914
John McCall9f54ad42009-12-10 09:41:52 +00006915 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6916 if (!CheckUsingShadowDecl(UD, *I, Previous))
6917 BuildUsingShadowDecl(S, UD, *I);
6918 }
John McCall9488ea12009-11-17 05:59:44 +00006919
6920 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006921}
6922
Sebastian Redlf677ea32011-02-05 19:23:19 +00006923/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006924bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6925 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006926
Douglas Gregordc355712011-02-25 00:36:19 +00006927 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006928 assert(SourceType &&
6929 "Using decl naming constructor doesn't have type in scope spec.");
6930 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6931
6932 // Check whether the named type is a direct base class.
6933 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6934 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6935 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6936 BaseIt != BaseE; ++BaseIt) {
6937 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6938 if (CanonicalSourceType == BaseType)
6939 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006940 if (BaseIt->getType()->isDependentType())
6941 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006942 }
6943
6944 if (BaseIt == BaseE) {
6945 // Did not find SourceType in the bases.
6946 Diag(UD->getUsingLocation(),
6947 diag::err_using_decl_constructor_not_in_direct_base)
6948 << UD->getNameInfo().getSourceRange()
6949 << QualType(SourceType, 0) << TargetClass;
6950 return true;
6951 }
6952
Richard Smithc5a89a12012-04-02 01:30:27 +00006953 if (!CurContext->isDependentContext())
6954 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006955
6956 return false;
6957}
6958
John McCall9f54ad42009-12-10 09:41:52 +00006959/// Checks that the given using declaration is not an invalid
6960/// redeclaration. Note that this is checking only for the using decl
6961/// itself, not for any ill-formedness among the UsingShadowDecls.
6962bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6963 bool isTypeName,
6964 const CXXScopeSpec &SS,
6965 SourceLocation NameLoc,
6966 const LookupResult &Prev) {
6967 // C++03 [namespace.udecl]p8:
6968 // C++0x [namespace.udecl]p10:
6969 // A using-declaration is a declaration and can therefore be used
6970 // repeatedly where (and only where) multiple declarations are
6971 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006972 //
John McCall8a726212010-11-29 18:01:58 +00006973 // That's in non-member contexts.
6974 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006975 return false;
6976
6977 NestedNameSpecifier *Qual
6978 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6979
6980 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6981 NamedDecl *D = *I;
6982
6983 bool DTypename;
6984 NestedNameSpecifier *DQual;
6985 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6986 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006987 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006988 } else if (UnresolvedUsingValueDecl *UD
6989 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6990 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006991 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006992 } else if (UnresolvedUsingTypenameDecl *UD
6993 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6994 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006995 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006996 } else continue;
6997
6998 // using decls differ if one says 'typename' and the other doesn't.
6999 // FIXME: non-dependent using decls?
7000 if (isTypeName != DTypename) continue;
7001
7002 // using decls differ if they name different scopes (but note that
7003 // template instantiation can cause this check to trigger when it
7004 // didn't before instantiation).
7005 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7006 Context.getCanonicalNestedNameSpecifier(DQual))
7007 continue;
7008
7009 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007010 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007011 return true;
7012 }
7013
7014 return false;
7015}
7016
John McCall604e7f12009-12-08 07:46:18 +00007017
John McCalled976492009-12-04 22:46:56 +00007018/// Checks that the given nested-name qualifier used in a using decl
7019/// in the current context is appropriately related to the current
7020/// scope. If an error is found, diagnoses it and returns true.
7021bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7022 const CXXScopeSpec &SS,
7023 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007024 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007025
John McCall604e7f12009-12-08 07:46:18 +00007026 if (!CurContext->isRecord()) {
7027 // C++03 [namespace.udecl]p3:
7028 // C++0x [namespace.udecl]p8:
7029 // A using-declaration for a class member shall be a member-declaration.
7030
7031 // If we weren't able to compute a valid scope, it must be a
7032 // dependent class scope.
7033 if (!NamedContext || NamedContext->isRecord()) {
7034 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7035 << SS.getRange();
7036 return true;
7037 }
7038
7039 // Otherwise, everything is known to be fine.
7040 return false;
7041 }
7042
7043 // The current scope is a record.
7044
7045 // If the named context is dependent, we can't decide much.
7046 if (!NamedContext) {
7047 // FIXME: in C++0x, we can diagnose if we can prove that the
7048 // nested-name-specifier does not refer to a base class, which is
7049 // still possible in some cases.
7050
7051 // Otherwise we have to conservatively report that things might be
7052 // okay.
7053 return false;
7054 }
7055
7056 if (!NamedContext->isRecord()) {
7057 // Ideally this would point at the last name in the specifier,
7058 // but we don't have that level of source info.
7059 Diag(SS.getRange().getBegin(),
7060 diag::err_using_decl_nested_name_specifier_is_not_class)
7061 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7062 return true;
7063 }
7064
Douglas Gregor6fb07292010-12-21 07:41:49 +00007065 if (!NamedContext->isDependentContext() &&
7066 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7067 return true;
7068
Richard Smith80ad52f2013-01-02 11:42:31 +00007069 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007070 // C++0x [namespace.udecl]p3:
7071 // In a using-declaration used as a member-declaration, the
7072 // nested-name-specifier shall name a base class of the class
7073 // being defined.
7074
7075 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7076 cast<CXXRecordDecl>(NamedContext))) {
7077 if (CurContext == NamedContext) {
7078 Diag(NameLoc,
7079 diag::err_using_decl_nested_name_specifier_is_current_class)
7080 << SS.getRange();
7081 return true;
7082 }
7083
7084 Diag(SS.getRange().getBegin(),
7085 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7086 << (NestedNameSpecifier*) SS.getScopeRep()
7087 << cast<CXXRecordDecl>(CurContext)
7088 << SS.getRange();
7089 return true;
7090 }
7091
7092 return false;
7093 }
7094
7095 // C++03 [namespace.udecl]p4:
7096 // A using-declaration used as a member-declaration shall refer
7097 // to a member of a base class of the class being defined [etc.].
7098
7099 // Salient point: SS doesn't have to name a base class as long as
7100 // lookup only finds members from base classes. Therefore we can
7101 // diagnose here only if we can prove that that can't happen,
7102 // i.e. if the class hierarchies provably don't intersect.
7103
7104 // TODO: it would be nice if "definitely valid" results were cached
7105 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7106 // need to be repeated.
7107
7108 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007109 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007110
7111 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7112 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7113 Data->Bases.insert(Base);
7114 return true;
7115 }
7116
7117 bool hasDependentBases(const CXXRecordDecl *Class) {
7118 return !Class->forallBases(collect, this);
7119 }
7120
7121 /// Returns true if the base is dependent or is one of the
7122 /// accumulated base classes.
7123 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7124 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7125 return !Data->Bases.count(Base);
7126 }
7127
7128 bool mightShareBases(const CXXRecordDecl *Class) {
7129 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7130 }
7131 };
7132
7133 UserData Data;
7134
7135 // Returns false if we find a dependent base.
7136 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7137 return false;
7138
7139 // Returns false if the class has a dependent base or if it or one
7140 // of its bases is present in the base set of the current context.
7141 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7142 return false;
7143
7144 Diag(SS.getRange().getBegin(),
7145 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7146 << (NestedNameSpecifier*) SS.getScopeRep()
7147 << cast<CXXRecordDecl>(CurContext)
7148 << SS.getRange();
7149
7150 return true;
John McCalled976492009-12-04 22:46:56 +00007151}
7152
Richard Smith162e1c12011-04-15 14:24:37 +00007153Decl *Sema::ActOnAliasDeclaration(Scope *S,
7154 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007155 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007156 SourceLocation UsingLoc,
7157 UnqualifiedId &Name,
7158 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007159 // Skip up to the relevant declaration scope.
7160 while (S->getFlags() & Scope::TemplateParamScope)
7161 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007162 assert((S->getFlags() & Scope::DeclScope) &&
7163 "got alias-declaration outside of declaration scope");
7164
7165 if (Type.isInvalid())
7166 return 0;
7167
7168 bool Invalid = false;
7169 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7170 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007171 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007172
7173 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7174 return 0;
7175
7176 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007177 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007178 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007179 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7180 TInfo->getTypeLoc().getBeginLoc());
7181 }
Richard Smith162e1c12011-04-15 14:24:37 +00007182
7183 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7184 LookupName(Previous, S);
7185
7186 // Warn about shadowing the name of a template parameter.
7187 if (Previous.isSingleResult() &&
7188 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007189 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007190 Previous.clear();
7191 }
7192
7193 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7194 "name in alias declaration must be an identifier");
7195 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7196 Name.StartLocation,
7197 Name.Identifier, TInfo);
7198
7199 NewTD->setAccess(AS);
7200
7201 if (Invalid)
7202 NewTD->setInvalidDecl();
7203
Richard Smith3e4c6c42011-05-05 21:57:07 +00007204 CheckTypedefForVariablyModifiedType(S, NewTD);
7205 Invalid |= NewTD->isInvalidDecl();
7206
Richard Smith162e1c12011-04-15 14:24:37 +00007207 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007208
7209 NamedDecl *NewND;
7210 if (TemplateParamLists.size()) {
7211 TypeAliasTemplateDecl *OldDecl = 0;
7212 TemplateParameterList *OldTemplateParams = 0;
7213
7214 if (TemplateParamLists.size() != 1) {
7215 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007216 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7217 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007218 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007219 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007220
7221 // Only consider previous declarations in the same scope.
7222 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7223 /*ExplicitInstantiationOrSpecialization*/false);
7224 if (!Previous.empty()) {
7225 Redeclaration = true;
7226
7227 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7228 if (!OldDecl && !Invalid) {
7229 Diag(UsingLoc, diag::err_redefinition_different_kind)
7230 << Name.Identifier;
7231
7232 NamedDecl *OldD = Previous.getRepresentativeDecl();
7233 if (OldD->getLocation().isValid())
7234 Diag(OldD->getLocation(), diag::note_previous_definition);
7235
7236 Invalid = true;
7237 }
7238
7239 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7240 if (TemplateParameterListsAreEqual(TemplateParams,
7241 OldDecl->getTemplateParameters(),
7242 /*Complain=*/true,
7243 TPL_TemplateMatch))
7244 OldTemplateParams = OldDecl->getTemplateParameters();
7245 else
7246 Invalid = true;
7247
7248 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7249 if (!Invalid &&
7250 !Context.hasSameType(OldTD->getUnderlyingType(),
7251 NewTD->getUnderlyingType())) {
7252 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7253 // but we can't reasonably accept it.
7254 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7255 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7256 if (OldTD->getLocation().isValid())
7257 Diag(OldTD->getLocation(), diag::note_previous_definition);
7258 Invalid = true;
7259 }
7260 }
7261 }
7262
7263 // Merge any previous default template arguments into our parameters,
7264 // and check the parameter list.
7265 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7266 TPC_TypeAliasTemplate))
7267 return 0;
7268
7269 TypeAliasTemplateDecl *NewDecl =
7270 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7271 Name.Identifier, TemplateParams,
7272 NewTD);
7273
7274 NewDecl->setAccess(AS);
7275
7276 if (Invalid)
7277 NewDecl->setInvalidDecl();
7278 else if (OldDecl)
7279 NewDecl->setPreviousDeclaration(OldDecl);
7280
7281 NewND = NewDecl;
7282 } else {
7283 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7284 NewND = NewTD;
7285 }
Richard Smith162e1c12011-04-15 14:24:37 +00007286
7287 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007288 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007289
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007290 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007291 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007292}
7293
John McCalld226f652010-08-21 09:40:31 +00007294Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007295 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007296 SourceLocation AliasLoc,
7297 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007298 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007299 SourceLocation IdentLoc,
7300 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007301
Anders Carlsson81c85c42009-03-28 23:53:49 +00007302 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007303 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7304 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007305
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007306 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007307 NamedDecl *PrevDecl
7308 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7309 ForRedeclaration);
7310 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7311 PrevDecl = 0;
7312
7313 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007314 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007315 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007316 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007317 // FIXME: At some point, we'll want to create the (redundant)
7318 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007319 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007320 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007321 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007322 }
Mike Stump1eb44332009-09-09 15:08:12 +00007323
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007324 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7325 diag::err_redefinition_different_kind;
7326 Diag(AliasLoc, DiagID) << Alias;
7327 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007328 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007329 }
7330
John McCalla24dc2e2009-11-17 02:14:36 +00007331 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007332 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007333
John McCallf36e02d2009-10-09 21:13:30 +00007334 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007335 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007336 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007337 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007338 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007339 }
Mike Stump1eb44332009-09-09 15:08:12 +00007340
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007341 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007342 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007343 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007344 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007345
John McCall3dbd3d52010-02-16 06:53:13 +00007346 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007347 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007348}
7349
Sean Hunt001cad92011-05-10 00:49:42 +00007350Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007351Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7352 CXXMethodDecl *MD) {
7353 CXXRecordDecl *ClassDecl = MD->getParent();
7354
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007355 // C++ [except.spec]p14:
7356 // An implicitly declared special member function (Clause 12) shall have an
7357 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007358 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007359 if (ClassDecl->isInvalidDecl())
7360 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007361
Sebastian Redl60618fa2011-03-12 11:50:43 +00007362 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007363 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7364 BEnd = ClassDecl->bases_end();
7365 B != BEnd; ++B) {
7366 if (B->isVirtual()) // Handled below.
7367 continue;
7368
Douglas Gregor18274032010-07-03 00:47:00 +00007369 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7370 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007371 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7372 // If this is a deleted function, add it anyway. This might be conformant
7373 // with the standard. This might not. I'm not sure. It might not matter.
7374 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007375 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007376 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007377 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007378
7379 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007380 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7381 BEnd = ClassDecl->vbases_end();
7382 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007383 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7384 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007385 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7386 // If this is a deleted function, add it anyway. This might be conformant
7387 // with the standard. This might not. I'm not sure. It might not matter.
7388 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007389 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007390 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007391 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007392
7393 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007394 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7395 FEnd = ClassDecl->field_end();
7396 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007397 if (F->hasInClassInitializer()) {
7398 if (Expr *E = F->getInClassInitializer())
7399 ExceptSpec.CalledExpr(E);
7400 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007401 // DR1351:
7402 // If the brace-or-equal-initializer of a non-static data member
7403 // invokes a defaulted default constructor of its class or of an
7404 // enclosing class in a potentially evaluated subexpression, the
7405 // program is ill-formed.
7406 //
7407 // This resolution is unworkable: the exception specification of the
7408 // default constructor can be needed in an unevaluated context, in
7409 // particular, in the operand of a noexcept-expression, and we can be
7410 // unable to compute an exception specification for an enclosed class.
7411 //
7412 // We do not allow an in-class initializer to require the evaluation
7413 // of the exception specification for any in-class initializer whose
7414 // definition is not lexically complete.
7415 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007416 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007417 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007418 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7419 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7420 // If this is a deleted function, add it anyway. This might be conformant
7421 // with the standard. This might not. I'm not sure. It might not matter.
7422 // In particular, the problem is that this function never gets called. It
7423 // might just be ill-formed because this function attempts to refer to
7424 // a deleted function here.
7425 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007426 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007427 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007428 }
John McCalle23cf432010-12-14 08:05:40 +00007429
Sean Hunt001cad92011-05-10 00:49:42 +00007430 return ExceptSpec;
7431}
7432
Richard Smithafb49182012-11-29 01:34:07 +00007433namespace {
7434/// RAII object to register a special member as being currently declared.
7435struct DeclaringSpecialMember {
7436 Sema &S;
7437 Sema::SpecialMemberDecl D;
7438 bool WasAlreadyBeingDeclared;
7439
7440 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7441 : S(S), D(RD, CSM) {
7442 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7443 if (WasAlreadyBeingDeclared)
7444 // This almost never happens, but if it does, ensure that our cache
7445 // doesn't contain a stale result.
7446 S.SpecialMemberCache.clear();
7447
7448 // FIXME: Register a note to be produced if we encounter an error while
7449 // declaring the special member.
7450 }
7451 ~DeclaringSpecialMember() {
7452 if (!WasAlreadyBeingDeclared)
7453 S.SpecialMembersBeingDeclared.erase(D);
7454 }
7455
7456 /// \brief Are we already trying to declare this special member?
7457 bool isAlreadyBeingDeclared() const {
7458 return WasAlreadyBeingDeclared;
7459 }
7460};
7461}
7462
Sean Hunt001cad92011-05-10 00:49:42 +00007463CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7464 CXXRecordDecl *ClassDecl) {
7465 // C++ [class.ctor]p5:
7466 // A default constructor for a class X is a constructor of class X
7467 // that can be called without an argument. If there is no
7468 // user-declared constructor for class X, a default constructor is
7469 // implicitly declared. An implicitly-declared default constructor
7470 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007471 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007472 "Should not build implicit default constructor!");
7473
Richard Smithafb49182012-11-29 01:34:07 +00007474 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7475 if (DSM.isAlreadyBeingDeclared())
7476 return 0;
7477
Richard Smith7756afa2012-06-10 05:43:50 +00007478 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7479 CXXDefaultConstructor,
7480 false);
7481
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007482 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007483 CanQualType ClassType
7484 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007485 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007486 DeclarationName Name
7487 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007488 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007489 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007490 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007491 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007492 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007493 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007494 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007495 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007496
7497 // Build an exception specification pointing back at this constructor.
7498 FunctionProtoType::ExtProtoInfo EPI;
7499 EPI.ExceptionSpecType = EST_Unevaluated;
7500 EPI.ExceptionSpecDecl = DefaultCon;
7501 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7502
Richard Smithbc2a35d2012-12-08 08:32:28 +00007503 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7504 // constructors is easy to compute.
7505 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7506
7507 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7508 DefaultCon->setDeletedAsWritten();
7509
Douglas Gregor18274032010-07-03 00:47:00 +00007510 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007511 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007512
Douglas Gregor23c94db2010-07-02 17:43:08 +00007513 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007514 PushOnScopeChains(DefaultCon, S, false);
7515 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007516
Douglas Gregor32df23e2010-07-01 22:02:46 +00007517 return DefaultCon;
7518}
7519
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007520void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7521 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007522 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007523 !Constructor->doesThisDeclarationHaveABody() &&
7524 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007525 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007526
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007527 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007528 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007529
Eli Friedman9a14db32012-10-18 20:14:08 +00007530 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007531 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007532 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007533 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007534 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007535 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007536 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007537 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007538 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007539
7540 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007541 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007542
7543 Constructor->setUsed();
7544 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007545
7546 if (ASTMutationListener *L = getASTMutationListener()) {
7547 L->CompletedImplicitDefinition(Constructor);
7548 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007549}
7550
Richard Smith7a614d82011-06-11 17:19:42 +00007551void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007552 // Check that any explicitly-defaulted methods have exception specifications
7553 // compatible with their implicit exception specifications.
7554 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007555}
7556
Sebastian Redlf677ea32011-02-05 19:23:19 +00007557void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7558 // We start with an initial pass over the base classes to collect those that
7559 // inherit constructors from. If there are none, we can forgo all further
7560 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007561 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007562 BasesVector BasesToInheritFrom;
7563 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7564 BaseE = ClassDecl->bases_end();
7565 BaseIt != BaseE; ++BaseIt) {
7566 if (BaseIt->getInheritConstructors()) {
7567 QualType Base = BaseIt->getType();
7568 if (Base->isDependentType()) {
7569 // If we inherit constructors from anything that is dependent, just
7570 // abort processing altogether. We'll get another chance for the
7571 // instantiations.
7572 return;
7573 }
7574 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7575 }
7576 }
7577 if (BasesToInheritFrom.empty())
7578 return;
7579
7580 // Now collect the constructors that we already have in the current class.
7581 // Those take precedence over inherited constructors.
7582 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7583 // unless there is a user-declared constructor with the same signature in
7584 // the class where the using-declaration appears.
7585 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7586 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7587 CtorE = ClassDecl->ctor_end();
7588 CtorIt != CtorE; ++CtorIt) {
7589 ExistingConstructors.insert(
7590 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7591 }
7592
Sebastian Redlf677ea32011-02-05 19:23:19 +00007593 DeclarationName CreatedCtorName =
7594 Context.DeclarationNames.getCXXConstructorName(
7595 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7596
7597 // Now comes the true work.
7598 // First, we keep a map from constructor types to the base that introduced
7599 // them. Needed for finding conflicting constructors. We also keep the
7600 // actually inserted declarations in there, for pretty diagnostics.
7601 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7602 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7603 ConstructorToSourceMap InheritedConstructors;
7604 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7605 BaseE = BasesToInheritFrom.end();
7606 BaseIt != BaseE; ++BaseIt) {
7607 const RecordType *Base = *BaseIt;
7608 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7609 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7610 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7611 CtorE = BaseDecl->ctor_end();
7612 CtorIt != CtorE; ++CtorIt) {
7613 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00007614 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00007615 DeclarationName Name =
7616 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00007617 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7618 LookupQualifiedName(Result, CurContext);
7619 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007620 SourceLocation UsingLoc = UD ? UD->getLocation() :
7621 ClassDecl->getLocation();
7622
7623 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7624 // from the class X named in the using-declaration consists of actual
7625 // constructors and notional constructors that result from the
7626 // transformation of defaulted parameters as follows:
7627 // - all non-template default constructors of X, and
7628 // - for each non-template constructor of X that has at least one
7629 // parameter with a default argument, the set of constructors that
7630 // results from omitting any ellipsis parameter specification and
7631 // successively omitting parameters with a default argument from the
7632 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00007633 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007634 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7635 const FunctionProtoType *BaseCtorType =
7636 BaseCtor->getType()->getAs<FunctionProtoType>();
7637
7638 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7639 maxParams = BaseCtor->getNumParams();
7640 params <= maxParams; ++params) {
7641 // Skip default constructors. They're never inherited.
7642 if (params == 0)
7643 continue;
7644 // Skip copy and move constructors for the same reason.
7645 if (CanBeCopyOrMove && params == 1)
7646 continue;
7647
7648 // Build up a function type for this particular constructor.
7649 // FIXME: The working paper does not consider that the exception spec
7650 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007651 // source. This code doesn't yet, either. When it does, this code will
7652 // need to be delayed until after exception specifications and in-class
7653 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007654 const Type *NewCtorType;
7655 if (params == maxParams)
7656 NewCtorType = BaseCtorType;
7657 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007658 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007659 for (unsigned i = 0; i < params; ++i) {
7660 Args.push_back(BaseCtorType->getArgType(i));
7661 }
7662 FunctionProtoType::ExtProtoInfo ExtInfo =
7663 BaseCtorType->getExtProtoInfo();
7664 ExtInfo.Variadic = false;
7665 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7666 Args.data(), params, ExtInfo)
7667 .getTypePtr();
7668 }
7669 const Type *CanonicalNewCtorType =
7670 Context.getCanonicalType(NewCtorType);
7671
7672 // Now that we have the type, first check if the class already has a
7673 // constructor with this signature.
7674 if (ExistingConstructors.count(CanonicalNewCtorType))
7675 continue;
7676
7677 // Then we check if we have already declared an inherited constructor
7678 // with this signature.
7679 std::pair<ConstructorToSourceMap::iterator, bool> result =
7680 InheritedConstructors.insert(std::make_pair(
7681 CanonicalNewCtorType,
7682 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7683 if (!result.second) {
7684 // Already in the map. If it came from a different class, that's an
7685 // error. Not if it's from the same.
7686 CanQualType PreviousBase = result.first->second.first;
7687 if (CanonicalBase != PreviousBase) {
7688 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7689 const CXXConstructorDecl *PrevBaseCtor =
7690 PrevCtor->getInheritedConstructor();
7691 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7692
7693 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7694 Diag(BaseCtor->getLocation(),
7695 diag::note_using_decl_constructor_conflict_current_ctor);
7696 Diag(PrevBaseCtor->getLocation(),
7697 diag::note_using_decl_constructor_conflict_previous_ctor);
7698 Diag(PrevCtor->getLocation(),
7699 diag::note_using_decl_constructor_conflict_previous_using);
7700 }
7701 continue;
7702 }
7703
7704 // OK, we're there, now add the constructor.
7705 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007706 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007707 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7708 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007709 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7710 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007711 /*ImplicitlyDeclared=*/true,
7712 // FIXME: Due to a defect in the standard, we treat inherited
7713 // constructors as constexpr even if that makes them ill-formed.
7714 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007715 NewCtor->setAccess(BaseCtor->getAccess());
7716
7717 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007718 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007719 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007720 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7721 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007722 /*IdentifierInfo=*/0,
7723 BaseCtorType->getArgType(i),
7724 /*TInfo=*/0, SC_None,
7725 SC_None, /*DefaultArg=*/0));
7726 }
David Blaikie4278c652011-09-21 18:16:56 +00007727 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007728 NewCtor->setInheritedConstructor(BaseCtor);
7729
Sebastian Redlf677ea32011-02-05 19:23:19 +00007730 ClassDecl->addDecl(NewCtor);
7731 result.first->second.second = NewCtor;
7732 }
7733 }
7734 }
7735}
7736
Sean Huntcb45a0f2011-05-12 22:46:25 +00007737Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007738Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7739 CXXRecordDecl *ClassDecl = MD->getParent();
7740
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007741 // C++ [except.spec]p14:
7742 // An implicitly declared special member function (Clause 12) shall have
7743 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007744 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007745 if (ClassDecl->isInvalidDecl())
7746 return ExceptSpec;
7747
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007748 // Direct base-class destructors.
7749 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7750 BEnd = ClassDecl->bases_end();
7751 B != BEnd; ++B) {
7752 if (B->isVirtual()) // Handled below.
7753 continue;
7754
7755 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007756 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007757 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007758 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007759
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007760 // Virtual base-class destructors.
7761 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7762 BEnd = ClassDecl->vbases_end();
7763 B != BEnd; ++B) {
7764 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007765 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007766 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007767 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007768
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007769 // Field destructors.
7770 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7771 FEnd = ClassDecl->field_end();
7772 F != FEnd; ++F) {
7773 if (const RecordType *RecordTy
7774 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007775 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007776 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007777 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007778
Sean Huntcb45a0f2011-05-12 22:46:25 +00007779 return ExceptSpec;
7780}
7781
7782CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7783 // C++ [class.dtor]p2:
7784 // If a class has no user-declared destructor, a destructor is
7785 // declared implicitly. An implicitly-declared destructor is an
7786 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00007787 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00007788
Richard Smithafb49182012-11-29 01:34:07 +00007789 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7790 if (DSM.isAlreadyBeingDeclared())
7791 return 0;
7792
Douglas Gregor4923aa22010-07-02 20:37:36 +00007793 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007794 CanQualType ClassType
7795 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007796 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007797 DeclarationName Name
7798 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007799 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007800 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007801 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7802 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007803 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007804 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007805 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007806 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007807
7808 // Build an exception specification pointing back at this destructor.
7809 FunctionProtoType::ExtProtoInfo EPI;
7810 EPI.ExceptionSpecType = EST_Unevaluated;
7811 EPI.ExceptionSpecDecl = Destructor;
7812 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7813
Richard Smithbc2a35d2012-12-08 08:32:28 +00007814 AddOverriddenMethods(ClassDecl, Destructor);
7815
7816 // We don't need to use SpecialMemberIsTrivial here; triviality for
7817 // destructors is easy to compute.
7818 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7819
7820 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7821 Destructor->setDeletedAsWritten();
7822
Douglas Gregor4923aa22010-07-02 20:37:36 +00007823 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007824 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007825
Douglas Gregor4923aa22010-07-02 20:37:36 +00007826 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007827 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007828 PushOnScopeChains(Destructor, S, false);
7829 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007830
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007831 return Destructor;
7832}
7833
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007834void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007835 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007836 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007837 !Destructor->doesThisDeclarationHaveABody() &&
7838 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007839 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007840 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007841 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007842
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007843 if (Destructor->isInvalidDecl())
7844 return;
7845
Eli Friedman9a14db32012-10-18 20:14:08 +00007846 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007847
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007848 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007849 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7850 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007851
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007852 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007853 Diag(CurrentLocation, diag::note_member_synthesized_at)
7854 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7855
7856 Destructor->setInvalidDecl();
7857 return;
7858 }
7859
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007860 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007861 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007862 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007863 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007864 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007865
7866 if (ASTMutationListener *L = getASTMutationListener()) {
7867 L->CompletedImplicitDefinition(Destructor);
7868 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007869}
7870
Richard Smitha4156b82012-04-21 18:42:51 +00007871/// \brief Perform any semantic analysis which needs to be delayed until all
7872/// pending class member declarations have been parsed.
7873void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00007874 // If the context is an invalid C++ class, just suppress these checks.
7875 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
7876 if (Record->isInvalidDecl()) {
7877 DelayedDestructorExceptionSpecChecks.clear();
7878 return;
7879 }
7880 }
7881
Richard Smitha4156b82012-04-21 18:42:51 +00007882 // Perform any deferred checking of exception specifications for virtual
7883 // destructors.
7884 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7885 i != e; ++i) {
7886 const CXXDestructorDecl *Dtor =
7887 DelayedDestructorExceptionSpecChecks[i].first;
7888 assert(!Dtor->getParent()->isDependentType() &&
7889 "Should not ever add destructors of templates into the list.");
7890 CheckOverridingFunctionExceptionSpec(Dtor,
7891 DelayedDestructorExceptionSpecChecks[i].second);
7892 }
7893 DelayedDestructorExceptionSpecChecks.clear();
7894}
7895
Richard Smithb9d0b762012-07-27 04:22:15 +00007896void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7897 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00007898 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00007899 "adjusting dtor exception specs was introduced in c++11");
7900
Sebastian Redl0ee33912011-05-19 05:13:44 +00007901 // C++11 [class.dtor]p3:
7902 // A declaration of a destructor that does not have an exception-
7903 // specification is implicitly considered to have the same exception-
7904 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007905 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007906 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007907 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007908 return;
7909
Chandler Carruth3f224b22011-09-20 04:55:26 +00007910 // Replace the destructor's type, building off the existing one. Fortunately,
7911 // the only thing of interest in the destructor type is its extended info.
7912 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007913 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7914 EPI.ExceptionSpecType = EST_Unevaluated;
7915 EPI.ExceptionSpecDecl = Destructor;
7916 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007917
Sebastian Redl0ee33912011-05-19 05:13:44 +00007918 // FIXME: If the destructor has a body that could throw, and the newly created
7919 // spec doesn't allow exceptions, we should emit a warning, because this
7920 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007921 // However, we don't have a body or an exception specification yet, so it
7922 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007923}
7924
Richard Smith8c889532012-11-14 00:50:40 +00007925/// When generating a defaulted copy or move assignment operator, if a field
7926/// should be copied with __builtin_memcpy rather than via explicit assignments,
7927/// do so. This optimization only applies for arrays of scalars, and for arrays
7928/// of class type where the selected copy/move-assignment operator is trivial.
7929static StmtResult
7930buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
7931 Expr *To, Expr *From) {
7932 // Compute the size of the memory buffer to be copied.
7933 QualType SizeType = S.Context.getSizeType();
7934 llvm::APInt Size(S.Context.getTypeSize(SizeType),
7935 S.Context.getTypeSizeInChars(T).getQuantity());
7936
7937 // Take the address of the field references for "from" and "to". We
7938 // directly construct UnaryOperators here because semantic analysis
7939 // does not permit us to take the address of an xvalue.
7940 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
7941 S.Context.getPointerType(From->getType()),
7942 VK_RValue, OK_Ordinary, Loc);
7943 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
7944 S.Context.getPointerType(To->getType()),
7945 VK_RValue, OK_Ordinary, Loc);
7946
7947 const Type *E = T->getBaseElementTypeUnsafe();
7948 bool NeedsCollectableMemCpy =
7949 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
7950
7951 // Create a reference to the __builtin_objc_memmove_collectable function
7952 StringRef MemCpyName = NeedsCollectableMemCpy ?
7953 "__builtin_objc_memmove_collectable" :
7954 "__builtin_memcpy";
7955 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
7956 Sema::LookupOrdinaryName);
7957 S.LookupName(R, S.TUScope, true);
7958
7959 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
7960 if (!MemCpy)
7961 // Something went horribly wrong earlier, and we will have complained
7962 // about it.
7963 return StmtError();
7964
7965 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
7966 VK_RValue, Loc, 0);
7967 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
7968
7969 Expr *CallArgs[] = {
7970 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
7971 };
7972 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
7973 Loc, CallArgs, Loc);
7974
7975 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7976 return S.Owned(Call.takeAs<Stmt>());
7977}
7978
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007979/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007980/// \c To.
7981///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007982/// This routine is used to copy/move the members of a class with an
7983/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007984/// copied are arrays, this routine builds for loops to copy them.
7985///
7986/// \param S The Sema object used for type-checking.
7987///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007988/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007989///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007990/// \param T The type of the expressions being copied/moved. Both expressions
7991/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007992///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007993/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007994///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007995/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007996///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007997/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007998/// Otherwise, it's a non-static member subobject.
7999///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008000/// \param Copying Whether we're copying or moving.
8001///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008002/// \param Depth Internal parameter recording the depth of the recursion.
8003///
Richard Smith8c889532012-11-14 00:50:40 +00008004/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8005/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008006static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008007buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8008 Expr *To, Expr *From,
8009 bool CopyingBaseSubobject, bool Copying,
8010 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008011 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008012 // Each subobject is assigned in the manner appropriate to its type:
8013 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008014 // - if the subobject is of class type, as if by a call to operator= with
8015 // the subobject as the object expression and the corresponding
8016 // subobject of x as a single function argument (as if by explicit
8017 // qualification; that is, ignoring any possible virtual overriding
8018 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008019 //
8020 // C++03 [class.copy]p13:
8021 // - if the subobject is of class type, the copy assignment operator for
8022 // the class is used (as if by explicit qualification; that is,
8023 // ignoring any possible virtual overriding functions in more derived
8024 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008025 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8026 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008027
Douglas Gregor06a9f362010-05-01 20:49:11 +00008028 // Look for operator=.
8029 DeclarationName Name
8030 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8031 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8032 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008033
Richard Smith044c8aa2012-11-13 00:54:12 +00008034 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8035 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008036 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008037 LookupResult::Filter F = OpLookup.makeFilter();
8038 while (F.hasNext()) {
8039 NamedDecl *D = F.next();
8040 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8041 if (Method->isCopyAssignmentOperator() ||
8042 (!Copying && Method->isMoveAssignmentOperator()))
8043 continue;
8044
8045 F.erase();
8046 }
8047 F.done();
John McCallb0207482010-03-16 06:11:48 +00008048 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008049
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008050 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008051 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008052 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008053 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008054 // ambiguities), we need to cast "this" to that subobject type; to
8055 // ensure that we don't go through the virtual call mechanism, we need
8056 // to qualify the operator= name with the base class (see below). However,
8057 // this means that if the base class has a protected copy assignment
8058 // operator, the protected member access check will fail. So, we
8059 // rewrite "protected" access to "public" access in this case, since we
8060 // know by construction that we're calling from a derived class.
8061 if (CopyingBaseSubobject) {
8062 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8063 L != LEnd; ++L) {
8064 if (L.getAccess() == AS_protected)
8065 L.setAccess(AS_public);
8066 }
8067 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008068
Douglas Gregor06a9f362010-05-01 20:49:11 +00008069 // Create the nested-name-specifier that will be used to qualify the
8070 // reference to operator=; this is required to suppress the virtual
8071 // call mechanism.
8072 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008073 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008074 SS.MakeTrivial(S.Context,
8075 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008076 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008077 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008078
Douglas Gregor06a9f362010-05-01 20:49:11 +00008079 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008080 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008081 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008082 /*TemplateKWLoc=*/SourceLocation(),
8083 /*FirstQualifierInScope=*/0,
8084 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008085 /*TemplateArgs=*/0,
8086 /*SuppressQualifierCheck=*/true);
8087 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008088 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008089
Douglas Gregor06a9f362010-05-01 20:49:11 +00008090 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008091
Richard Smith044c8aa2012-11-13 00:54:12 +00008092 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008093 OpEqualRef.takeAs<Expr>(),
8094 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008095 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008096 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008097
Richard Smith8c889532012-11-14 00:50:40 +00008098 // If we built a call to a trivial 'operator=' while copying an array,
8099 // bail out. We'll replace the whole shebang with a memcpy.
8100 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8101 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8102 return StmtResult((Stmt*)0);
8103
Richard Smith044c8aa2012-11-13 00:54:12 +00008104 // Convert to an expression-statement, and clean up any produced
8105 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008106 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008107 }
John McCallb0207482010-03-16 06:11:48 +00008108
Richard Smith044c8aa2012-11-13 00:54:12 +00008109 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008110 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008111 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008112 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008113 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008114 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008115 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008116 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008117 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008118
8119 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008120 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008121
Douglas Gregor06a9f362010-05-01 20:49:11 +00008122 // Construct a loop over the array bounds, e.g.,
8123 //
8124 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8125 //
8126 // that will copy each of the array elements.
8127 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008128
Douglas Gregor06a9f362010-05-01 20:49:11 +00008129 // Create the iteration variable.
8130 IdentifierInfo *IterationVarName = 0;
8131 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008132 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008133 llvm::raw_svector_ostream OS(Str);
8134 OS << "__i" << Depth;
8135 IterationVarName = &S.Context.Idents.get(OS.str());
8136 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008137 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008138 IterationVarName, SizeType,
8139 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00008140 SC_None, SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008141
Douglas Gregor06a9f362010-05-01 20:49:11 +00008142 // Initialize the iteration variable to zero.
8143 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008144 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008145
8146 // Create a reference to the iteration variable; we'll use this several
8147 // times throughout.
8148 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008149 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008150 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008151 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8152 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8153
Douglas Gregor06a9f362010-05-01 20:49:11 +00008154 // Create the DeclStmt that holds the iteration variable.
8155 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008156
Douglas Gregor06a9f362010-05-01 20:49:11 +00008157 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008158 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008159 IterationVarRefRVal,
8160 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008161 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008162 IterationVarRefRVal,
8163 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008164 if (!Copying) // Cast to rvalue
8165 From = CastForMoving(S, From);
8166
8167 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008168 StmtResult Copy =
8169 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8170 To, From, CopyingBaseSubobject,
8171 Copying, Depth + 1);
8172 // Bail out if copying fails or if we determined that we should use memcpy.
8173 if (Copy.isInvalid() || !Copy.get())
8174 return Copy;
8175
8176 // Create the comparison against the array bound.
8177 llvm::APInt Upper
8178 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8179 Expr *Comparison
8180 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8181 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8182 BO_NE, S.Context.BoolTy,
8183 VK_RValue, OK_Ordinary, Loc, false);
8184
8185 // Create the pre-increment of the iteration variable.
8186 Expr *Increment
8187 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8188 VK_LValue, OK_Ordinary, Loc);
8189
Douglas Gregor06a9f362010-05-01 20:49:11 +00008190 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008191 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008192 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008193 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008194 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008195}
8196
Richard Smith8c889532012-11-14 00:50:40 +00008197static StmtResult
8198buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8199 Expr *To, Expr *From,
8200 bool CopyingBaseSubobject, bool Copying) {
8201 // Maybe we should use a memcpy?
8202 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8203 T.isTriviallyCopyableType(S.Context))
8204 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8205
8206 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8207 CopyingBaseSubobject,
8208 Copying, 0));
8209
8210 // If we ended up picking a trivial assignment operator for an array of a
8211 // non-trivially-copyable class type, just emit a memcpy.
8212 if (!Result.isInvalid() && !Result.get())
8213 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8214
8215 return Result;
8216}
8217
Richard Smithb9d0b762012-07-27 04:22:15 +00008218Sema::ImplicitExceptionSpecification
8219Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8220 CXXRecordDecl *ClassDecl = MD->getParent();
8221
8222 ImplicitExceptionSpecification ExceptSpec(*this);
8223 if (ClassDecl->isInvalidDecl())
8224 return ExceptSpec;
8225
8226 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8227 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8228 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8229
Douglas Gregorb87786f2010-07-01 17:48:08 +00008230 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008231 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008232 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008233
8234 // It is unspecified whether or not an implicit copy assignment operator
8235 // attempts to deduplicate calls to assignment operators of virtual bases are
8236 // made. As such, this exception specification is effectively unspecified.
8237 // Based on a similar decision made for constness in C++0x, we're erring on
8238 // the side of assuming such calls to be made regardless of whether they
8239 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008240 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8241 BaseEnd = ClassDecl->bases_end();
8242 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008243 if (Base->isVirtual())
8244 continue;
8245
Douglas Gregora376d102010-07-02 21:50:04 +00008246 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008247 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008248 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8249 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008250 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008251 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008252
8253 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8254 BaseEnd = ClassDecl->vbases_end();
8255 Base != BaseEnd; ++Base) {
8256 CXXRecordDecl *BaseClassDecl
8257 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8258 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8259 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008260 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008261 }
8262
Douglas Gregorb87786f2010-07-01 17:48:08 +00008263 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8264 FieldEnd = ClassDecl->field_end();
8265 Field != FieldEnd;
8266 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008267 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008268 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8269 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008270 LookupCopyingAssignment(FieldClassDecl,
8271 ArgQuals | FieldType.getCVRQualifiers(),
8272 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008273 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008274 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008275 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008276
Richard Smithb9d0b762012-07-27 04:22:15 +00008277 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008278}
8279
8280CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8281 // Note: The following rules are largely analoguous to the copy
8282 // constructor rules. Note that virtual bases are not taken into account
8283 // for determining the argument type of the operator. Note also that
8284 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008285 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008286
Richard Smithafb49182012-11-29 01:34:07 +00008287 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8288 if (DSM.isAlreadyBeingDeclared())
8289 return 0;
8290
Sean Hunt30de05c2011-05-14 05:23:20 +00008291 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8292 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008293 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008294 ArgType = ArgType.withConst();
8295 ArgType = Context.getLValueReferenceType(ArgType);
8296
Douglas Gregord3c35902010-07-01 16:36:15 +00008297 // An implicitly-declared copy assignment operator is an inline public
8298 // member of its class.
8299 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008300 SourceLocation ClassLoc = ClassDecl->getLocation();
8301 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008302 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008303 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00008304 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00008305 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008306 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008307 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008308 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008309 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008310 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008311
8312 // Build an exception specification pointing back at this member.
8313 FunctionProtoType::ExtProtoInfo EPI;
8314 EPI.ExceptionSpecType = EST_Unevaluated;
8315 EPI.ExceptionSpecDecl = CopyAssignment;
8316 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8317
Douglas Gregord3c35902010-07-01 16:36:15 +00008318 // Add the parameter to the operator.
8319 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008320 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008321 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008322 SC_None,
8323 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008324 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008325
Richard Smithbc2a35d2012-12-08 08:32:28 +00008326 AddOverriddenMethods(ClassDecl, CopyAssignment);
8327
8328 CopyAssignment->setTrivial(
8329 ClassDecl->needsOverloadResolutionForCopyAssignment()
8330 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8331 : ClassDecl->hasTrivialCopyAssignment());
8332
Nico Weberafcc96a2012-01-23 03:19:29 +00008333 // C++0x [class.copy]p19:
8334 // .... If the class definition does not explicitly declare a copy
8335 // assignment operator, there is no user-declared move constructor, and
8336 // there is no user-declared move assignment operator, a copy assignment
8337 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008338 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00008339 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008340
Richard Smithbc2a35d2012-12-08 08:32:28 +00008341 // Note that we have added this copy-assignment operator.
8342 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8343
8344 if (Scope *S = getScopeForContext(ClassDecl))
8345 PushOnScopeChains(CopyAssignment, S, false);
8346 ClassDecl->addDecl(CopyAssignment);
8347
Douglas Gregord3c35902010-07-01 16:36:15 +00008348 return CopyAssignment;
8349}
8350
Douglas Gregor06a9f362010-05-01 20:49:11 +00008351void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8352 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008353 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008354 CopyAssignOperator->isOverloadedOperator() &&
8355 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008356 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8357 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008358 "DefineImplicitCopyAssignment called for wrong function");
8359
8360 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8361
8362 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8363 CopyAssignOperator->setInvalidDecl();
8364 return;
8365 }
8366
8367 CopyAssignOperator->setUsed();
8368
Eli Friedman9a14db32012-10-18 20:14:08 +00008369 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008370 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008371
8372 // C++0x [class.copy]p30:
8373 // The implicitly-defined or explicitly-defaulted copy assignment operator
8374 // for a non-union class X performs memberwise copy assignment of its
8375 // subobjects. The direct base classes of X are assigned first, in the
8376 // order of their declaration in the base-specifier-list, and then the
8377 // immediate non-static data members of X are assigned, in the order in
8378 // which they were declared in the class definition.
8379
8380 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008381 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008382
8383 // The parameter for the "other" object, which we are copying from.
8384 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8385 Qualifiers OtherQuals = Other->getType().getQualifiers();
8386 QualType OtherRefType = Other->getType();
8387 if (const LValueReferenceType *OtherRef
8388 = OtherRefType->getAs<LValueReferenceType>()) {
8389 OtherRefType = OtherRef->getPointeeType();
8390 OtherQuals = OtherRefType.getQualifiers();
8391 }
8392
8393 // Our location for everything implicitly-generated.
8394 SourceLocation Loc = CopyAssignOperator->getLocation();
8395
8396 // Construct a reference to the "other" object. We'll be using this
8397 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008398 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008399 assert(OtherRef && "Reference to parameter cannot fail!");
8400
8401 // Construct the "this" pointer. We'll be using this throughout the generated
8402 // ASTs.
8403 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8404 assert(This && "Reference to this cannot fail!");
8405
8406 // Assign base classes.
8407 bool Invalid = false;
8408 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8409 E = ClassDecl->bases_end(); Base != E; ++Base) {
8410 // Form the assignment:
8411 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8412 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008413 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008414 Invalid = true;
8415 continue;
8416 }
8417
John McCallf871d0c2010-08-07 06:22:56 +00008418 CXXCastPath BasePath;
8419 BasePath.push_back(Base);
8420
Douglas Gregor06a9f362010-05-01 20:49:11 +00008421 // Construct the "from" expression, which is an implicit cast to the
8422 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008423 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008424 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8425 CK_UncheckedDerivedToBase,
8426 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008427
8428 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008429 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008430
8431 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008432 To = ImpCastExprToType(To.take(),
8433 Context.getCVRQualifiedType(BaseType,
8434 CopyAssignOperator->getTypeQualifiers()),
8435 CK_UncheckedDerivedToBase,
8436 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008437
8438 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008439 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008440 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008441 /*CopyingBaseSubobject=*/true,
8442 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008443 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008444 Diag(CurrentLocation, diag::note_member_synthesized_at)
8445 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8446 CopyAssignOperator->setInvalidDecl();
8447 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008448 }
8449
8450 // Success! Record the copy.
8451 Statements.push_back(Copy.takeAs<Expr>());
8452 }
8453
Douglas Gregor06a9f362010-05-01 20:49:11 +00008454 // Assign non-static members.
8455 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8456 FieldEnd = ClassDecl->field_end();
8457 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008458 if (Field->isUnnamedBitfield())
8459 continue;
8460
Douglas Gregor06a9f362010-05-01 20:49:11 +00008461 // Check for members of reference type; we can't copy those.
8462 if (Field->getType()->isReferenceType()) {
8463 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8464 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8465 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008466 Diag(CurrentLocation, diag::note_member_synthesized_at)
8467 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008468 Invalid = true;
8469 continue;
8470 }
8471
8472 // Check for members of const-qualified, non-class type.
8473 QualType BaseType = Context.getBaseElementType(Field->getType());
8474 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8475 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8476 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8477 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008478 Diag(CurrentLocation, diag::note_member_synthesized_at)
8479 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008480 Invalid = true;
8481 continue;
8482 }
John McCallb77115d2011-06-17 00:18:42 +00008483
8484 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008485 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8486 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008487
8488 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008489 if (FieldType->isIncompleteArrayType()) {
8490 assert(ClassDecl->hasFlexibleArrayMember() &&
8491 "Incomplete array type is not valid");
8492 continue;
8493 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008494
8495 // Build references to the field in the object we're copying from and to.
8496 CXXScopeSpec SS; // Intentionally empty
8497 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8498 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008499 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008500 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008501 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008502 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008503 SS, SourceLocation(), 0,
8504 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008505 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008506 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008507 SS, SourceLocation(), 0,
8508 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008509 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8510 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008511
Douglas Gregor06a9f362010-05-01 20:49:11 +00008512 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008513 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008514 To.get(), From.get(),
8515 /*CopyingBaseSubobject=*/false,
8516 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008517 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008518 Diag(CurrentLocation, diag::note_member_synthesized_at)
8519 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8520 CopyAssignOperator->setInvalidDecl();
8521 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008522 }
8523
8524 // Success! Record the copy.
8525 Statements.push_back(Copy.takeAs<Stmt>());
8526 }
8527
8528 if (!Invalid) {
8529 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008530 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008531
John McCall60d7b3a2010-08-24 06:29:42 +00008532 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008533 if (Return.isInvalid())
8534 Invalid = true;
8535 else {
8536 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008537
8538 if (Trap.hasErrorOccurred()) {
8539 Diag(CurrentLocation, diag::note_member_synthesized_at)
8540 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8541 Invalid = true;
8542 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008543 }
8544 }
8545
8546 if (Invalid) {
8547 CopyAssignOperator->setInvalidDecl();
8548 return;
8549 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008550
8551 StmtResult Body;
8552 {
8553 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008554 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008555 /*isStmtExpr=*/false);
8556 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8557 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008558 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008559
8560 if (ASTMutationListener *L = getASTMutationListener()) {
8561 L->CompletedImplicitDefinition(CopyAssignOperator);
8562 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008563}
8564
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008565Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008566Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8567 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008568
Richard Smithb9d0b762012-07-27 04:22:15 +00008569 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008570 if (ClassDecl->isInvalidDecl())
8571 return ExceptSpec;
8572
8573 // C++0x [except.spec]p14:
8574 // An implicitly declared special member function (Clause 12) shall have an
8575 // exception-specification. [...]
8576
8577 // It is unspecified whether or not an implicit move assignment operator
8578 // attempts to deduplicate calls to assignment operators of virtual bases are
8579 // made. As such, this exception specification is effectively unspecified.
8580 // Based on a similar decision made for constness in C++0x, we're erring on
8581 // the side of assuming such calls to be made regardless of whether they
8582 // actually happen.
8583 // Note that a move constructor is not implicitly declared when there are
8584 // virtual bases, but it can still be user-declared and explicitly defaulted.
8585 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8586 BaseEnd = ClassDecl->bases_end();
8587 Base != BaseEnd; ++Base) {
8588 if (Base->isVirtual())
8589 continue;
8590
8591 CXXRecordDecl *BaseClassDecl
8592 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8593 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008594 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008595 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008596 }
8597
8598 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8599 BaseEnd = ClassDecl->vbases_end();
8600 Base != BaseEnd; ++Base) {
8601 CXXRecordDecl *BaseClassDecl
8602 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8603 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008604 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008605 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008606 }
8607
8608 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8609 FieldEnd = ClassDecl->field_end();
8610 Field != FieldEnd;
8611 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008612 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008613 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008614 if (CXXMethodDecl *MoveAssign =
8615 LookupMovingAssignment(FieldClassDecl,
8616 FieldType.getCVRQualifiers(),
8617 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008618 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008619 }
8620 }
8621
8622 return ExceptSpec;
8623}
8624
Richard Smith1c931be2012-04-02 18:40:40 +00008625/// Determine whether the class type has any direct or indirect virtual base
8626/// classes which have a non-trivial move assignment operator.
8627static bool
8628hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8629 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8630 BaseEnd = ClassDecl->vbases_end();
8631 Base != BaseEnd; ++Base) {
8632 CXXRecordDecl *BaseClass =
8633 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8634
8635 // Try to declare the move assignment. If it would be deleted, then the
8636 // class does not have a non-trivial move assignment.
8637 if (BaseClass->needsImplicitMoveAssignment())
8638 S.DeclareImplicitMoveAssignment(BaseClass);
8639
Richard Smith426391c2012-11-16 00:53:38 +00008640 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008641 return true;
8642 }
8643
8644 return false;
8645}
8646
8647/// Determine whether the given type either has a move constructor or is
8648/// trivially copyable.
8649static bool
8650hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8651 Type = S.Context.getBaseElementType(Type);
8652
8653 // FIXME: Technically, non-trivially-copyable non-class types, such as
8654 // reference types, are supposed to return false here, but that appears
8655 // to be a standard defect.
8656 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008657 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008658 return true;
8659
8660 if (Type.isTriviallyCopyableType(S.Context))
8661 return true;
8662
8663 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008664 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8665 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008666 if (ClassDecl->needsImplicitMoveConstructor())
8667 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008668 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008669 }
8670
Richard Smithe5411b72012-12-01 02:35:44 +00008671 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8672 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008673 if (ClassDecl->needsImplicitMoveAssignment())
8674 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008675 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008676}
8677
8678/// Determine whether all non-static data members and direct or virtual bases
8679/// of class \p ClassDecl have either a move operation, or are trivially
8680/// copyable.
8681static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8682 bool IsConstructor) {
8683 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8684 BaseEnd = ClassDecl->bases_end();
8685 Base != BaseEnd; ++Base) {
8686 if (Base->isVirtual())
8687 continue;
8688
8689 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8690 return false;
8691 }
8692
8693 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8694 BaseEnd = ClassDecl->vbases_end();
8695 Base != BaseEnd; ++Base) {
8696 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8697 return false;
8698 }
8699
8700 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8701 FieldEnd = ClassDecl->field_end();
8702 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008703 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008704 return false;
8705 }
8706
8707 return true;
8708}
8709
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008710CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008711 // C++11 [class.copy]p20:
8712 // If the definition of a class X does not explicitly declare a move
8713 // assignment operator, one will be implicitly declared as defaulted
8714 // if and only if:
8715 //
8716 // - [first 4 bullets]
8717 assert(ClassDecl->needsImplicitMoveAssignment());
8718
Richard Smithafb49182012-11-29 01:34:07 +00008719 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8720 if (DSM.isAlreadyBeingDeclared())
8721 return 0;
8722
Richard Smith1c931be2012-04-02 18:40:40 +00008723 // [Checked after we build the declaration]
8724 // - the move assignment operator would not be implicitly defined as
8725 // deleted,
8726
8727 // [DR1402]:
8728 // - X has no direct or indirect virtual base class with a non-trivial
8729 // move assignment operator, and
8730 // - each of X's non-static data members and direct or virtual base classes
8731 // has a type that either has a move assignment operator or is trivially
8732 // copyable.
8733 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8734 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8735 ClassDecl->setFailedImplicitMoveAssignment();
8736 return 0;
8737 }
8738
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008739 // Note: The following rules are largely analoguous to the move
8740 // constructor rules.
8741
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008742 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8743 QualType RetType = Context.getLValueReferenceType(ArgType);
8744 ArgType = Context.getRValueReferenceType(ArgType);
8745
8746 // An implicitly-declared move assignment operator is an inline public
8747 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008748 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8749 SourceLocation ClassLoc = ClassDecl->getLocation();
8750 DeclarationNameInfo NameInfo(Name, ClassLoc);
8751 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008752 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008753 /*TInfo=*/0, /*isStatic=*/false,
8754 /*StorageClassAsWritten=*/SC_None,
8755 /*isInline=*/true,
8756 /*isConstexpr=*/false,
8757 SourceLocation());
8758 MoveAssignment->setAccess(AS_public);
8759 MoveAssignment->setDefaulted();
8760 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008761
Richard Smithb9d0b762012-07-27 04:22:15 +00008762 // Build an exception specification pointing back at this member.
8763 FunctionProtoType::ExtProtoInfo EPI;
8764 EPI.ExceptionSpecType = EST_Unevaluated;
8765 EPI.ExceptionSpecDecl = MoveAssignment;
8766 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8767
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008768 // Add the parameter to the operator.
8769 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8770 ClassLoc, ClassLoc, /*Id=*/0,
8771 ArgType, /*TInfo=*/0,
8772 SC_None,
8773 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008774 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008775
Richard Smithbc2a35d2012-12-08 08:32:28 +00008776 AddOverriddenMethods(ClassDecl, MoveAssignment);
8777
8778 MoveAssignment->setTrivial(
8779 ClassDecl->needsOverloadResolutionForMoveAssignment()
8780 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8781 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008782
8783 // C++0x [class.copy]p9:
8784 // If the definition of a class X does not explicitly declare a move
8785 // assignment operator, one will be implicitly declared as defaulted if and
8786 // only if:
8787 // [...]
8788 // - the move assignment operator would not be implicitly defined as
8789 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008790 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008791 // Cache this result so that we don't try to generate this over and over
8792 // on every lookup, leaking memory and wasting time.
8793 ClassDecl->setFailedImplicitMoveAssignment();
8794 return 0;
8795 }
8796
Richard Smithbc2a35d2012-12-08 08:32:28 +00008797 // Note that we have added this copy-assignment operator.
8798 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8799
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008800 if (Scope *S = getScopeForContext(ClassDecl))
8801 PushOnScopeChains(MoveAssignment, S, false);
8802 ClassDecl->addDecl(MoveAssignment);
8803
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008804 return MoveAssignment;
8805}
8806
8807void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8808 CXXMethodDecl *MoveAssignOperator) {
8809 assert((MoveAssignOperator->isDefaulted() &&
8810 MoveAssignOperator->isOverloadedOperator() &&
8811 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008812 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8813 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008814 "DefineImplicitMoveAssignment called for wrong function");
8815
8816 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8817
8818 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8819 MoveAssignOperator->setInvalidDecl();
8820 return;
8821 }
8822
8823 MoveAssignOperator->setUsed();
8824
Eli Friedman9a14db32012-10-18 20:14:08 +00008825 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008826 DiagnosticErrorTrap Trap(Diags);
8827
8828 // C++0x [class.copy]p28:
8829 // The implicitly-defined or move assignment operator for a non-union class
8830 // X performs memberwise move assignment of its subobjects. The direct base
8831 // classes of X are assigned first, in the order of their declaration in the
8832 // base-specifier-list, and then the immediate non-static data members of X
8833 // are assigned, in the order in which they were declared in the class
8834 // definition.
8835
8836 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008837 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008838
8839 // The parameter for the "other" object, which we are move from.
8840 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8841 QualType OtherRefType = Other->getType()->
8842 getAs<RValueReferenceType>()->getPointeeType();
8843 assert(OtherRefType.getQualifiers() == 0 &&
8844 "Bad argument type of defaulted move assignment");
8845
8846 // Our location for everything implicitly-generated.
8847 SourceLocation Loc = MoveAssignOperator->getLocation();
8848
8849 // Construct a reference to the "other" object. We'll be using this
8850 // throughout the generated ASTs.
8851 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8852 assert(OtherRef && "Reference to parameter cannot fail!");
8853 // Cast to rvalue.
8854 OtherRef = CastForMoving(*this, OtherRef);
8855
8856 // Construct the "this" pointer. We'll be using this throughout the generated
8857 // ASTs.
8858 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8859 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008860
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008861 // Assign base classes.
8862 bool Invalid = false;
8863 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8864 E = ClassDecl->bases_end(); Base != E; ++Base) {
8865 // Form the assignment:
8866 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8867 QualType BaseType = Base->getType().getUnqualifiedType();
8868 if (!BaseType->isRecordType()) {
8869 Invalid = true;
8870 continue;
8871 }
8872
8873 CXXCastPath BasePath;
8874 BasePath.push_back(Base);
8875
8876 // Construct the "from" expression, which is an implicit cast to the
8877 // appropriately-qualified base type.
8878 Expr *From = OtherRef;
8879 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008880 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008881
8882 // Dereference "this".
8883 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8884
8885 // Implicitly cast "this" to the appropriately-qualified base type.
8886 To = ImpCastExprToType(To.take(),
8887 Context.getCVRQualifiedType(BaseType,
8888 MoveAssignOperator->getTypeQualifiers()),
8889 CK_UncheckedDerivedToBase,
8890 VK_LValue, &BasePath);
8891
8892 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00008893 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008894 To.get(), From,
8895 /*CopyingBaseSubobject=*/true,
8896 /*Copying=*/false);
8897 if (Move.isInvalid()) {
8898 Diag(CurrentLocation, diag::note_member_synthesized_at)
8899 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8900 MoveAssignOperator->setInvalidDecl();
8901 return;
8902 }
8903
8904 // Success! Record the move.
8905 Statements.push_back(Move.takeAs<Expr>());
8906 }
8907
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008908 // Assign non-static members.
8909 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8910 FieldEnd = ClassDecl->field_end();
8911 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008912 if (Field->isUnnamedBitfield())
8913 continue;
8914
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008915 // Check for members of reference type; we can't move those.
8916 if (Field->getType()->isReferenceType()) {
8917 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8918 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8919 Diag(Field->getLocation(), diag::note_declared_at);
8920 Diag(CurrentLocation, diag::note_member_synthesized_at)
8921 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8922 Invalid = true;
8923 continue;
8924 }
8925
8926 // Check for members of const-qualified, non-class type.
8927 QualType BaseType = Context.getBaseElementType(Field->getType());
8928 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8929 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8930 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8931 Diag(Field->getLocation(), diag::note_declared_at);
8932 Diag(CurrentLocation, diag::note_member_synthesized_at)
8933 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8934 Invalid = true;
8935 continue;
8936 }
8937
8938 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008939 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8940 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008941
8942 QualType FieldType = Field->getType().getNonReferenceType();
8943 if (FieldType->isIncompleteArrayType()) {
8944 assert(ClassDecl->hasFlexibleArrayMember() &&
8945 "Incomplete array type is not valid");
8946 continue;
8947 }
8948
8949 // Build references to the field in the object we're copying from and to.
8950 CXXScopeSpec SS; // Intentionally empty
8951 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8952 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008953 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008954 MemberLookup.resolveKind();
8955 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8956 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008957 SS, SourceLocation(), 0,
8958 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008959 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8960 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008961 SS, SourceLocation(), 0,
8962 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008963 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8964 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8965
8966 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8967 "Member reference with rvalue base must be rvalue except for reference "
8968 "members, which aren't allowed for move assignment.");
8969
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008970 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008971 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008972 To.get(), From.get(),
8973 /*CopyingBaseSubobject=*/false,
8974 /*Copying=*/false);
8975 if (Move.isInvalid()) {
8976 Diag(CurrentLocation, diag::note_member_synthesized_at)
8977 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8978 MoveAssignOperator->setInvalidDecl();
8979 return;
8980 }
Richard Smithe7ce7092012-11-12 23:33:00 +00008981
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008982 // Success! Record the copy.
8983 Statements.push_back(Move.takeAs<Stmt>());
8984 }
8985
8986 if (!Invalid) {
8987 // Add a "return *this;"
8988 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8989
8990 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8991 if (Return.isInvalid())
8992 Invalid = true;
8993 else {
8994 Statements.push_back(Return.takeAs<Stmt>());
8995
8996 if (Trap.hasErrorOccurred()) {
8997 Diag(CurrentLocation, diag::note_member_synthesized_at)
8998 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8999 Invalid = true;
9000 }
9001 }
9002 }
9003
9004 if (Invalid) {
9005 MoveAssignOperator->setInvalidDecl();
9006 return;
9007 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009008
9009 StmtResult Body;
9010 {
9011 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009012 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009013 /*isStmtExpr=*/false);
9014 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9015 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009016 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9017
9018 if (ASTMutationListener *L = getASTMutationListener()) {
9019 L->CompletedImplicitDefinition(MoveAssignOperator);
9020 }
9021}
9022
Richard Smithb9d0b762012-07-27 04:22:15 +00009023Sema::ImplicitExceptionSpecification
9024Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9025 CXXRecordDecl *ClassDecl = MD->getParent();
9026
9027 ImplicitExceptionSpecification ExceptSpec(*this);
9028 if (ClassDecl->isInvalidDecl())
9029 return ExceptSpec;
9030
9031 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9032 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9033 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9034
Douglas Gregor0d405db2010-07-01 20:59:04 +00009035 // C++ [except.spec]p14:
9036 // An implicitly declared special member function (Clause 12) shall have an
9037 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009038 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9039 BaseEnd = ClassDecl->bases_end();
9040 Base != BaseEnd;
9041 ++Base) {
9042 // Virtual bases are handled below.
9043 if (Base->isVirtual())
9044 continue;
9045
Douglas Gregor22584312010-07-02 23:41:54 +00009046 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009047 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009048 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009049 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009050 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009051 }
9052 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9053 BaseEnd = ClassDecl->vbases_end();
9054 Base != BaseEnd;
9055 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009056 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009057 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009058 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009059 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009060 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009061 }
9062 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9063 FieldEnd = ClassDecl->field_end();
9064 Field != FieldEnd;
9065 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009066 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009067 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9068 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009069 LookupCopyingConstructor(FieldClassDecl,
9070 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009071 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009072 }
9073 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009074
Richard Smithb9d0b762012-07-27 04:22:15 +00009075 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009076}
9077
9078CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9079 CXXRecordDecl *ClassDecl) {
9080 // C++ [class.copy]p4:
9081 // If the class definition does not explicitly declare a copy
9082 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009083 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009084
Richard Smithafb49182012-11-29 01:34:07 +00009085 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9086 if (DSM.isAlreadyBeingDeclared())
9087 return 0;
9088
Sean Hunt49634cf2011-05-13 06:10:58 +00009089 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9090 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009091 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009092 if (Const)
9093 ArgType = ArgType.withConst();
9094 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009095
Richard Smith7756afa2012-06-10 05:43:50 +00009096 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9097 CXXCopyConstructor,
9098 Const);
9099
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009100 DeclarationName Name
9101 = Context.DeclarationNames.getCXXConstructorName(
9102 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009103 SourceLocation ClassLoc = ClassDecl->getLocation();
9104 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009105
9106 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009107 // member of its class.
9108 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009109 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009110 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009111 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009112 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009113 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009114
Richard Smithb9d0b762012-07-27 04:22:15 +00009115 // Build an exception specification pointing back at this member.
9116 FunctionProtoType::ExtProtoInfo EPI;
9117 EPI.ExceptionSpecType = EST_Unevaluated;
9118 EPI.ExceptionSpecDecl = CopyConstructor;
9119 CopyConstructor->setType(
9120 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9121
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009122 // Add the parameter to the constructor.
9123 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009124 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009125 /*IdentifierInfo=*/0,
9126 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009127 SC_None,
9128 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009129 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009130
Richard Smithbc2a35d2012-12-08 08:32:28 +00009131 CopyConstructor->setTrivial(
9132 ClassDecl->needsOverloadResolutionForCopyConstructor()
9133 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9134 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009135
Nico Weberafcc96a2012-01-23 03:19:29 +00009136 // C++11 [class.copy]p8:
9137 // ... If the class definition does not explicitly declare a copy
9138 // constructor, there is no user-declared move constructor, and there is no
9139 // user-declared move assignment operator, a copy constructor is implicitly
9140 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009141 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00009142 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00009143
Richard Smithbc2a35d2012-12-08 08:32:28 +00009144 // Note that we have declared this constructor.
9145 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9146
9147 if (Scope *S = getScopeForContext(ClassDecl))
9148 PushOnScopeChains(CopyConstructor, S, false);
9149 ClassDecl->addDecl(CopyConstructor);
9150
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009151 return CopyConstructor;
9152}
9153
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009154void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009155 CXXConstructorDecl *CopyConstructor) {
9156 assert((CopyConstructor->isDefaulted() &&
9157 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009158 !CopyConstructor->doesThisDeclarationHaveABody() &&
9159 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009160 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009161
Anders Carlsson63010a72010-04-23 16:24:12 +00009162 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009163 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009164
Eli Friedman9a14db32012-10-18 20:14:08 +00009165 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009166 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009167
David Blaikie93c86172013-01-17 05:26:25 +00009168 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009169 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009170 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009171 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009172 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009173 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009174 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009175 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9176 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009177 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009178 /*isStmtExpr=*/false)
9179 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009180 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009181 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009182
9183 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009184 if (ASTMutationListener *L = getASTMutationListener()) {
9185 L->CompletedImplicitDefinition(CopyConstructor);
9186 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009187}
9188
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009189Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009190Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9191 CXXRecordDecl *ClassDecl = MD->getParent();
9192
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009193 // C++ [except.spec]p14:
9194 // An implicitly declared special member function (Clause 12) shall have an
9195 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009196 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009197 if (ClassDecl->isInvalidDecl())
9198 return ExceptSpec;
9199
9200 // Direct base-class constructors.
9201 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9202 BEnd = ClassDecl->bases_end();
9203 B != BEnd; ++B) {
9204 if (B->isVirtual()) // Handled below.
9205 continue;
9206
9207 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9208 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009209 CXXConstructorDecl *Constructor =
9210 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009211 // If this is a deleted function, add it anyway. This might be conformant
9212 // with the standard. This might not. I'm not sure. It might not matter.
9213 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009214 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009215 }
9216 }
9217
9218 // Virtual base-class constructors.
9219 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9220 BEnd = ClassDecl->vbases_end();
9221 B != BEnd; ++B) {
9222 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9223 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009224 CXXConstructorDecl *Constructor =
9225 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009226 // If this is a deleted function, add it anyway. This might be conformant
9227 // with the standard. This might not. I'm not sure. It might not matter.
9228 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009229 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009230 }
9231 }
9232
9233 // Field constructors.
9234 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9235 FEnd = ClassDecl->field_end();
9236 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009237 QualType FieldType = Context.getBaseElementType(F->getType());
9238 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9239 CXXConstructorDecl *Constructor =
9240 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009241 // If this is a deleted function, add it anyway. This might be conformant
9242 // with the standard. This might not. I'm not sure. It might not matter.
9243 // In particular, the problem is that this function never gets called. It
9244 // might just be ill-formed because this function attempts to refer to
9245 // a deleted function here.
9246 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009247 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009248 }
9249 }
9250
9251 return ExceptSpec;
9252}
9253
9254CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9255 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009256 // C++11 [class.copy]p9:
9257 // If the definition of a class X does not explicitly declare a move
9258 // constructor, one will be implicitly declared as defaulted if and only if:
9259 //
9260 // - [first 4 bullets]
9261 assert(ClassDecl->needsImplicitMoveConstructor());
9262
Richard Smithafb49182012-11-29 01:34:07 +00009263 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9264 if (DSM.isAlreadyBeingDeclared())
9265 return 0;
9266
Richard Smith1c931be2012-04-02 18:40:40 +00009267 // [Checked after we build the declaration]
9268 // - the move assignment operator would not be implicitly defined as
9269 // deleted,
9270
9271 // [DR1402]:
9272 // - each of X's non-static data members and direct or virtual base classes
9273 // has a type that either has a move constructor or is trivially copyable.
9274 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9275 ClassDecl->setFailedImplicitMoveConstructor();
9276 return 0;
9277 }
9278
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009279 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9280 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009281
Richard Smith7756afa2012-06-10 05:43:50 +00009282 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9283 CXXMoveConstructor,
9284 false);
9285
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009286 DeclarationName Name
9287 = Context.DeclarationNames.getCXXConstructorName(
9288 Context.getCanonicalType(ClassType));
9289 SourceLocation ClassLoc = ClassDecl->getLocation();
9290 DeclarationNameInfo NameInfo(Name, ClassLoc);
9291
9292 // C++0x [class.copy]p11:
9293 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009294 // member of its class.
9295 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009296 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009297 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009298 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009299 MoveConstructor->setAccess(AS_public);
9300 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009301
Richard Smithb9d0b762012-07-27 04:22:15 +00009302 // Build an exception specification pointing back at this member.
9303 FunctionProtoType::ExtProtoInfo EPI;
9304 EPI.ExceptionSpecType = EST_Unevaluated;
9305 EPI.ExceptionSpecDecl = MoveConstructor;
9306 MoveConstructor->setType(
9307 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9308
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009309 // Add the parameter to the constructor.
9310 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9311 ClassLoc, ClassLoc,
9312 /*IdentifierInfo=*/0,
9313 ArgType, /*TInfo=*/0,
9314 SC_None,
9315 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009316 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009317
Richard Smithbc2a35d2012-12-08 08:32:28 +00009318 MoveConstructor->setTrivial(
9319 ClassDecl->needsOverloadResolutionForMoveConstructor()
9320 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9321 : ClassDecl->hasTrivialMoveConstructor());
9322
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009323 // C++0x [class.copy]p9:
9324 // If the definition of a class X does not explicitly declare a move
9325 // constructor, one will be implicitly declared as defaulted if and only if:
9326 // [...]
9327 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009328 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009329 // Cache this result so that we don't try to generate this over and over
9330 // on every lookup, leaking memory and wasting time.
9331 ClassDecl->setFailedImplicitMoveConstructor();
9332 return 0;
9333 }
9334
9335 // Note that we have declared this constructor.
9336 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9337
9338 if (Scope *S = getScopeForContext(ClassDecl))
9339 PushOnScopeChains(MoveConstructor, S, false);
9340 ClassDecl->addDecl(MoveConstructor);
9341
9342 return MoveConstructor;
9343}
9344
9345void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9346 CXXConstructorDecl *MoveConstructor) {
9347 assert((MoveConstructor->isDefaulted() &&
9348 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009349 !MoveConstructor->doesThisDeclarationHaveABody() &&
9350 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009351 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9352
9353 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9354 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9355
Eli Friedman9a14db32012-10-18 20:14:08 +00009356 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009357 DiagnosticErrorTrap Trap(Diags);
9358
David Blaikie93c86172013-01-17 05:26:25 +00009359 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009360 Trap.hasErrorOccurred()) {
9361 Diag(CurrentLocation, diag::note_member_synthesized_at)
9362 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9363 MoveConstructor->setInvalidDecl();
9364 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009365 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009366 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9367 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009368 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009369 /*isStmtExpr=*/false)
9370 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009371 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009372 }
9373
9374 MoveConstructor->setUsed();
9375
9376 if (ASTMutationListener *L = getASTMutationListener()) {
9377 L->CompletedImplicitDefinition(MoveConstructor);
9378 }
9379}
9380
Douglas Gregore4e68d42012-02-15 19:33:52 +00009381bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9382 return FD->isDeleted() &&
9383 (FD->isDefaulted() || FD->isImplicit()) &&
9384 isa<CXXMethodDecl>(FD);
9385}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009386
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009387/// \brief Mark the call operator of the given lambda closure type as "used".
9388static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9389 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009390 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009391 Lambda->lookup(
9392 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009393 CallOperator->setReferenced();
9394 CallOperator->setUsed();
9395}
9396
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009397void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9398 SourceLocation CurrentLocation,
9399 CXXConversionDecl *Conv)
9400{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009401 CXXRecordDecl *Lambda = Conv->getParent();
9402
9403 // Make sure that the lambda call operator is marked used.
9404 markLambdaCallOperatorUsed(*this, Lambda);
9405
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009406 Conv->setUsed();
9407
Eli Friedman9a14db32012-10-18 20:14:08 +00009408 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009409 DiagnosticErrorTrap Trap(Diags);
9410
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009411 // Return the address of the __invoke function.
9412 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9413 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009414 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009415 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9416 VK_LValue, Conv->getLocation()).take();
9417 assert(FunctionRef && "Can't refer to __invoke function?");
9418 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009419 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009420 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009421 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009422
9423 // Fill in the __invoke function with a dummy implementation. IR generation
9424 // will fill in the actual details.
9425 Invoke->setUsed();
9426 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009427 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009428
9429 if (ASTMutationListener *L = getASTMutationListener()) {
9430 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009431 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009432 }
9433}
9434
9435void Sema::DefineImplicitLambdaToBlockPointerConversion(
9436 SourceLocation CurrentLocation,
9437 CXXConversionDecl *Conv)
9438{
9439 Conv->setUsed();
9440
Eli Friedman9a14db32012-10-18 20:14:08 +00009441 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009442 DiagnosticErrorTrap Trap(Diags);
9443
Douglas Gregorac1303e2012-02-22 05:02:47 +00009444 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009445 Expr *This = ActOnCXXThis(CurrentLocation).take();
9446 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009447
Eli Friedman23f02672012-03-01 04:01:32 +00009448 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9449 Conv->getLocation(),
9450 Conv, DerefThis);
9451
9452 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9453 // behavior. Note that only the general conversion function does this
9454 // (since it's unusable otherwise); in the case where we inline the
9455 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009456 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009457 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9458 CK_CopyAndAutoreleaseBlockObject,
9459 BuildBlock.get(), 0, VK_RValue);
9460
9461 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009462 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009463 Conv->setInvalidDecl();
9464 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009465 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009466
Douglas Gregorac1303e2012-02-22 05:02:47 +00009467 // Create the return statement that returns the block from the conversion
9468 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009469 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009470 if (Return.isInvalid()) {
9471 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9472 Conv->setInvalidDecl();
9473 return;
9474 }
9475
9476 // Set the body of the conversion function.
9477 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009478 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009479 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009480 Conv->getLocation()));
9481
Douglas Gregorac1303e2012-02-22 05:02:47 +00009482 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009483 if (ASTMutationListener *L = getASTMutationListener()) {
9484 L->CompletedImplicitDefinition(Conv);
9485 }
9486}
9487
Douglas Gregorf52757d2012-03-10 06:53:13 +00009488/// \brief Determine whether the given list arguments contains exactly one
9489/// "real" (non-default) argument.
9490static bool hasOneRealArgument(MultiExprArg Args) {
9491 switch (Args.size()) {
9492 case 0:
9493 return false;
9494
9495 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009496 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009497 return false;
9498
9499 // fall through
9500 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009501 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009502 }
9503
9504 return false;
9505}
9506
John McCall60d7b3a2010-08-24 06:29:42 +00009507ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009508Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009509 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009510 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009511 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009512 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009513 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009514 unsigned ConstructKind,
9515 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009516 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009517
Douglas Gregor2f599792010-04-02 18:24:57 +00009518 // C++0x [class.copy]p34:
9519 // When certain criteria are met, an implementation is allowed to
9520 // omit the copy/move construction of a class object, even if the
9521 // copy/move constructor and/or destructor for the object have
9522 // side effects. [...]
9523 // - when a temporary class object that has not been bound to a
9524 // reference (12.2) would be copied/moved to a class object
9525 // with the same cv-unqualified type, the copy/move operation
9526 // can be omitted by constructing the temporary object
9527 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009528 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009529 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009530 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009531 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009532 }
Mike Stump1eb44332009-09-09 15:08:12 +00009533
9534 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009535 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009536 IsListInitialization, RequiresZeroInit,
9537 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009538}
9539
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009540/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9541/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009542ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009543Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9544 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009545 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009546 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009547 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009548 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009549 unsigned ConstructKind,
9550 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009551 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009552 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009553 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +00009554 HadMultipleCandidates,
9555 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009556 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9557 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009558}
9559
John McCall68c6c9a2010-02-02 09:10:11 +00009560void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009561 if (VD->isInvalidDecl()) return;
9562
John McCall68c6c9a2010-02-02 09:10:11 +00009563 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009564 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009565 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009566 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009567
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009568 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009569 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009570 CheckDestructorAccess(VD->getLocation(), Destructor,
9571 PDiag(diag::err_access_dtor_var)
9572 << VD->getDeclName()
9573 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009574 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009575
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009576 if (!VD->hasGlobalStorage()) return;
9577
9578 // Emit warning for non-trivial dtor in global scope (a real global,
9579 // class-static, function-static).
9580 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9581
9582 // TODO: this should be re-enabled for static locals by !CXAAtExit
9583 if (!VD->isStaticLocal())
9584 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009585}
9586
Douglas Gregor39da0b82009-09-09 23:08:42 +00009587/// \brief Given a constructor and the set of arguments provided for the
9588/// constructor, convert the arguments and add any required default arguments
9589/// to form a proper call to this constructor.
9590///
9591/// \returns true if an error occurred, false otherwise.
9592bool
9593Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9594 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009595 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009596 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009597 bool AllowExplicit,
9598 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009599 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9600 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009601 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009602
9603 const FunctionProtoType *Proto
9604 = Constructor->getType()->getAs<FunctionProtoType>();
9605 assert(Proto && "Constructor without a prototype?");
9606 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009607
9608 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009609 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009610 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009611 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009612 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009613
9614 VariadicCallType CallType =
9615 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009616 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009617 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9618 Proto, 0, Args, NumArgs, AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009619 CallType, AllowExplicit,
9620 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009621 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009622
9623 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9624
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00009625 CheckConstructorCall(Constructor,
9626 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9627 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +00009628 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009629
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009630 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009631}
9632
Anders Carlsson20d45d22009-12-12 00:32:00 +00009633static inline bool
9634CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9635 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009636 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009637 if (isa<NamespaceDecl>(DC)) {
9638 return SemaRef.Diag(FnDecl->getLocation(),
9639 diag::err_operator_new_delete_declared_in_namespace)
9640 << FnDecl->getDeclName();
9641 }
9642
9643 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009644 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009645 return SemaRef.Diag(FnDecl->getLocation(),
9646 diag::err_operator_new_delete_declared_static)
9647 << FnDecl->getDeclName();
9648 }
9649
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009650 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009651}
9652
Anders Carlsson156c78e2009-12-13 17:53:43 +00009653static inline bool
9654CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9655 CanQualType ExpectedResultType,
9656 CanQualType ExpectedFirstParamType,
9657 unsigned DependentParamTypeDiag,
9658 unsigned InvalidParamTypeDiag) {
9659 QualType ResultType =
9660 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9661
9662 // Check that the result type is not dependent.
9663 if (ResultType->isDependentType())
9664 return SemaRef.Diag(FnDecl->getLocation(),
9665 diag::err_operator_new_delete_dependent_result_type)
9666 << FnDecl->getDeclName() << ExpectedResultType;
9667
9668 // Check that the result type is what we expect.
9669 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9670 return SemaRef.Diag(FnDecl->getLocation(),
9671 diag::err_operator_new_delete_invalid_result_type)
9672 << FnDecl->getDeclName() << ExpectedResultType;
9673
9674 // A function template must have at least 2 parameters.
9675 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9676 return SemaRef.Diag(FnDecl->getLocation(),
9677 diag::err_operator_new_delete_template_too_few_parameters)
9678 << FnDecl->getDeclName();
9679
9680 // The function decl must have at least 1 parameter.
9681 if (FnDecl->getNumParams() == 0)
9682 return SemaRef.Diag(FnDecl->getLocation(),
9683 diag::err_operator_new_delete_too_few_parameters)
9684 << FnDecl->getDeclName();
9685
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009686 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009687 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9688 if (FirstParamType->isDependentType())
9689 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9690 << FnDecl->getDeclName() << ExpectedFirstParamType;
9691
9692 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009693 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009694 ExpectedFirstParamType)
9695 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9696 << FnDecl->getDeclName() << ExpectedFirstParamType;
9697
9698 return false;
9699}
9700
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009701static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009702CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009703 // C++ [basic.stc.dynamic.allocation]p1:
9704 // A program is ill-formed if an allocation function is declared in a
9705 // namespace scope other than global scope or declared static in global
9706 // scope.
9707 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9708 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009709
9710 CanQualType SizeTy =
9711 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9712
9713 // C++ [basic.stc.dynamic.allocation]p1:
9714 // The return type shall be void*. The first parameter shall have type
9715 // std::size_t.
9716 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9717 SizeTy,
9718 diag::err_operator_new_dependent_param_type,
9719 diag::err_operator_new_param_type))
9720 return true;
9721
9722 // C++ [basic.stc.dynamic.allocation]p1:
9723 // The first parameter shall not have an associated default argument.
9724 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009725 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009726 diag::err_operator_new_default_arg)
9727 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9728
9729 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009730}
9731
9732static bool
Richard Smith444d3842012-10-20 08:26:51 +00009733CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009734 // C++ [basic.stc.dynamic.deallocation]p1:
9735 // A program is ill-formed if deallocation functions are declared in a
9736 // namespace scope other than global scope or declared static in global
9737 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009738 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9739 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009740
9741 // C++ [basic.stc.dynamic.deallocation]p2:
9742 // Each deallocation function shall return void and its first parameter
9743 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009744 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9745 SemaRef.Context.VoidPtrTy,
9746 diag::err_operator_delete_dependent_param_type,
9747 diag::err_operator_delete_param_type))
9748 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009749
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009750 return false;
9751}
9752
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009753/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9754/// of this overloaded operator is well-formed. If so, returns false;
9755/// otherwise, emits appropriate diagnostics and returns true.
9756bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009757 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009758 "Expected an overloaded operator declaration");
9759
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009760 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9761
Mike Stump1eb44332009-09-09 15:08:12 +00009762 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009763 // The allocation and deallocation functions, operator new,
9764 // operator new[], operator delete and operator delete[], are
9765 // described completely in 3.7.3. The attributes and restrictions
9766 // found in the rest of this subclause do not apply to them unless
9767 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009768 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009769 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009770
Anders Carlssona3ccda52009-12-12 00:26:23 +00009771 if (Op == OO_New || Op == OO_Array_New)
9772 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009773
9774 // C++ [over.oper]p6:
9775 // An operator function shall either be a non-static member
9776 // function or be a non-member function and have at least one
9777 // parameter whose type is a class, a reference to a class, an
9778 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009779 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9780 if (MethodDecl->isStatic())
9781 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009782 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009783 } else {
9784 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009785 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9786 ParamEnd = FnDecl->param_end();
9787 Param != ParamEnd; ++Param) {
9788 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009789 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9790 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009791 ClassOrEnumParam = true;
9792 break;
9793 }
9794 }
9795
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009796 if (!ClassOrEnumParam)
9797 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009798 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009799 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009800 }
9801
9802 // C++ [over.oper]p8:
9803 // An operator function cannot have default arguments (8.3.6),
9804 // except where explicitly stated below.
9805 //
Mike Stump1eb44332009-09-09 15:08:12 +00009806 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009807 // (C++ [over.call]p1).
9808 if (Op != OO_Call) {
9809 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9810 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009811 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009812 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009813 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009814 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009815 }
9816 }
9817
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009818 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9819 { false, false, false }
9820#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9821 , { Unary, Binary, MemberOnly }
9822#include "clang/Basic/OperatorKinds.def"
9823 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009824
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009825 bool CanBeUnaryOperator = OperatorUses[Op][0];
9826 bool CanBeBinaryOperator = OperatorUses[Op][1];
9827 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009828
9829 // C++ [over.oper]p8:
9830 // [...] Operator functions cannot have more or fewer parameters
9831 // than the number required for the corresponding operator, as
9832 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009833 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009834 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009835 if (Op != OO_Call &&
9836 ((NumParams == 1 && !CanBeUnaryOperator) ||
9837 (NumParams == 2 && !CanBeBinaryOperator) ||
9838 (NumParams < 1) || (NumParams > 2))) {
9839 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009840 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009841 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009842 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009843 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009844 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009845 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009846 assert(CanBeBinaryOperator &&
9847 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009848 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009849 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009850
Chris Lattner416e46f2008-11-21 07:57:12 +00009851 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009852 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009853 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009854
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009855 // Overloaded operators other than operator() cannot be variadic.
9856 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009857 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009858 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009859 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009860 }
9861
9862 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009863 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9864 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009865 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009866 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009867 }
9868
9869 // C++ [over.inc]p1:
9870 // The user-defined function called operator++ implements the
9871 // prefix and postfix ++ operator. If this function is a member
9872 // function with no parameters, or a non-member function with one
9873 // parameter of class or enumeration type, it defines the prefix
9874 // increment operator ++ for objects of that type. If the function
9875 // is a member function with one parameter (which shall be of type
9876 // int) or a non-member function with two parameters (the second
9877 // of which shall be of type int), it defines the postfix
9878 // increment operator ++ for objects of that type.
9879 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9880 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9881 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009882 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009883 ParamIsInt = BT->getKind() == BuiltinType::Int;
9884
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009885 if (!ParamIsInt)
9886 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009887 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009888 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009889 }
9890
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009891 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009892}
Chris Lattner5a003a42008-12-17 07:09:26 +00009893
Sean Hunta6c058d2010-01-13 09:01:02 +00009894/// CheckLiteralOperatorDeclaration - Check whether the declaration
9895/// of this literal operator function is well-formed. If so, returns
9896/// false; otherwise, emits appropriate diagnostics and returns true.
9897bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009898 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009899 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9900 << FnDecl->getDeclName();
9901 return true;
9902 }
9903
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009904 if (FnDecl->isExternC()) {
9905 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9906 return true;
9907 }
9908
Sean Hunta6c058d2010-01-13 09:01:02 +00009909 bool Valid = false;
9910
Richard Smith36f5cfe2012-03-09 08:00:36 +00009911 // This might be the definition of a literal operator template.
9912 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9913 // This might be a specialization of a literal operator template.
9914 if (!TpDecl)
9915 TpDecl = FnDecl->getPrimaryTemplate();
9916
Sean Hunt216c2782010-04-07 23:11:06 +00009917 // template <char...> type operator "" name() is the only valid template
9918 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009919 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009920 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009921 // Must have only one template parameter
9922 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9923 if (Params->size() == 1) {
9924 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009925 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009926
Sean Hunt216c2782010-04-07 23:11:06 +00009927 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009928 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9929 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9930 Valid = true;
9931 }
9932 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009933 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009934 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009935 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9936
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009937 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009938
Sean Hunt30019c02010-04-07 22:57:35 +00009939 // unsigned long long int, long double, and any character type are allowed
9940 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009941 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9942 Context.hasSameType(T, Context.LongDoubleTy) ||
9943 Context.hasSameType(T, Context.CharTy) ||
9944 Context.hasSameType(T, Context.WCharTy) ||
9945 Context.hasSameType(T, Context.Char16Ty) ||
9946 Context.hasSameType(T, Context.Char32Ty)) {
9947 if (++Param == FnDecl->param_end())
9948 Valid = true;
9949 goto FinishedParams;
9950 }
9951
Sean Hunt30019c02010-04-07 22:57:35 +00009952 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009953 const PointerType *PT = T->getAs<PointerType>();
9954 if (!PT)
9955 goto FinishedParams;
9956 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009957 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009958 goto FinishedParams;
9959 T = T.getUnqualifiedType();
9960
9961 // Move on to the second parameter;
9962 ++Param;
9963
9964 // If there is no second parameter, the first must be a const char *
9965 if (Param == FnDecl->param_end()) {
9966 if (Context.hasSameType(T, Context.CharTy))
9967 Valid = true;
9968 goto FinishedParams;
9969 }
9970
9971 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9972 // are allowed as the first parameter to a two-parameter function
9973 if (!(Context.hasSameType(T, Context.CharTy) ||
9974 Context.hasSameType(T, Context.WCharTy) ||
9975 Context.hasSameType(T, Context.Char16Ty) ||
9976 Context.hasSameType(T, Context.Char32Ty)))
9977 goto FinishedParams;
9978
9979 // The second and final parameter must be an std::size_t
9980 T = (*Param)->getType().getUnqualifiedType();
9981 if (Context.hasSameType(T, Context.getSizeType()) &&
9982 ++Param == FnDecl->param_end())
9983 Valid = true;
9984 }
9985
9986 // FIXME: This diagnostic is absolutely terrible.
9987FinishedParams:
9988 if (!Valid) {
9989 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9990 << FnDecl->getDeclName();
9991 return true;
9992 }
9993
Richard Smitha9e88b22012-03-09 08:16:22 +00009994 // A parameter-declaration-clause containing a default argument is not
9995 // equivalent to any of the permitted forms.
9996 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9997 ParamEnd = FnDecl->param_end();
9998 Param != ParamEnd; ++Param) {
9999 if ((*Param)->hasDefaultArg()) {
10000 Diag((*Param)->getDefaultArgRange().getBegin(),
10001 diag::err_literal_operator_default_argument)
10002 << (*Param)->getDefaultArgRange();
10003 break;
10004 }
10005 }
10006
Richard Smith2fb4ae32012-03-08 02:39:21 +000010007 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010008 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10009 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010010 // C++11 [usrlit.suffix]p1:
10011 // Literal suffix identifiers that do not start with an underscore
10012 // are reserved for future standardization.
10013 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010014 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010015
Sean Hunta6c058d2010-01-13 09:01:02 +000010016 return false;
10017}
10018
Douglas Gregor074149e2009-01-05 19:45:36 +000010019/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10020/// linkage specification, including the language and (if present)
10021/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10022/// the location of the language string literal, which is provided
10023/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10024/// the '{' brace. Otherwise, this linkage specification does not
10025/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010026Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10027 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010028 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010029 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010030 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010031 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010032 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010033 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010034 Language = LinkageSpecDecl::lang_cxx;
10035 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010036 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010037 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010038 }
Mike Stump1eb44332009-09-09 15:08:12 +000010039
Chris Lattnercc98eac2008-12-17 07:13:27 +000010040 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010041
Douglas Gregor074149e2009-01-05 19:45:36 +000010042 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010043 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010044 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010045 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010046 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010047}
10048
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010049/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010050/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10051/// valid, it's the position of the closing '}' brace in a linkage
10052/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010053Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010054 Decl *LinkageSpec,
10055 SourceLocation RBraceLoc) {
10056 if (LinkageSpec) {
10057 if (RBraceLoc.isValid()) {
10058 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10059 LSDecl->setRBraceLoc(RBraceLoc);
10060 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010061 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010062 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010063 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010064}
10065
Douglas Gregord308e622009-05-18 20:51:54 +000010066/// \brief Perform semantic analysis for the variable declaration that
10067/// occurs within a C++ catch clause, returning the newly-created
10068/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010069VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010070 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010071 SourceLocation StartLoc,
10072 SourceLocation Loc,
10073 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010074 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010075 QualType ExDeclType = TInfo->getType();
10076
Sebastian Redl4b07b292008-12-22 19:15:10 +000010077 // Arrays and functions decay.
10078 if (ExDeclType->isArrayType())
10079 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10080 else if (ExDeclType->isFunctionType())
10081 ExDeclType = Context.getPointerType(ExDeclType);
10082
10083 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10084 // The exception-declaration shall not denote a pointer or reference to an
10085 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010086 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010087 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010088 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010089 Invalid = true;
10090 }
Douglas Gregord308e622009-05-18 20:51:54 +000010091
Sebastian Redl4b07b292008-12-22 19:15:10 +000010092 QualType BaseType = ExDeclType;
10093 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010094 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010095 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010096 BaseType = Ptr->getPointeeType();
10097 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010098 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010099 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010100 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010101 BaseType = Ref->getPointeeType();
10102 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010103 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010104 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010105 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010106 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010107 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010108
Mike Stump1eb44332009-09-09 15:08:12 +000010109 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010110 RequireNonAbstractType(Loc, ExDeclType,
10111 diag::err_abstract_type_in_decl,
10112 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010113 Invalid = true;
10114
John McCall5a180392010-07-24 00:37:23 +000010115 // Only the non-fragile NeXT runtime currently supports C++ catches
10116 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010117 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010118 QualType T = ExDeclType;
10119 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10120 T = RT->getPointeeType();
10121
10122 if (T->isObjCObjectType()) {
10123 Diag(Loc, diag::err_objc_object_catch);
10124 Invalid = true;
10125 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010126 // FIXME: should this be a test for macosx-fragile specifically?
10127 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010128 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010129 }
10130 }
10131
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010132 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10133 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010134 ExDecl->setExceptionVariable(true);
10135
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010136 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010137 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010138 Invalid = true;
10139
Douglas Gregorc41b8782011-07-06 18:14:43 +000010140 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010141 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +000010142 // C++ [except.handle]p16:
10143 // The object declared in an exception-declaration or, if the
10144 // exception-declaration does not specify a name, a temporary (12.2) is
10145 // copy-initialized (8.5) from the exception object. [...]
10146 // The object is destroyed when the handler exits, after the destruction
10147 // of any automatic objects initialized within the handler.
10148 //
10149 // We just pretend to initialize the object with itself, then make sure
10150 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010151 QualType initType = ExDeclType;
10152
10153 InitializedEntity entity =
10154 InitializedEntity::InitializeVariable(ExDecl);
10155 InitializationKind initKind =
10156 InitializationKind::CreateCopy(Loc, SourceLocation());
10157
10158 Expr *opaqueValue =
10159 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10160 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10161 ExprResult result = sequence.Perform(*this, entity, initKind,
10162 MultiExprArg(&opaqueValue, 1));
10163 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010164 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010165 else {
10166 // If the constructor used was non-trivial, set this as the
10167 // "initializer".
10168 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10169 if (!construct->getConstructor()->isTrivial()) {
10170 Expr *init = MaybeCreateExprWithCleanups(construct);
10171 ExDecl->setInit(init);
10172 }
10173
10174 // And make sure it's destructable.
10175 FinalizeVarWithDestructor(ExDecl, recordType);
10176 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010177 }
10178 }
10179
Douglas Gregord308e622009-05-18 20:51:54 +000010180 if (Invalid)
10181 ExDecl->setInvalidDecl();
10182
10183 return ExDecl;
10184}
10185
10186/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10187/// handler.
John McCalld226f652010-08-21 09:40:31 +000010188Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010189 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010190 bool Invalid = D.isInvalidType();
10191
10192 // Check for unexpanded parameter packs.
10193 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10194 UPPC_ExceptionType)) {
10195 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10196 D.getIdentifierLoc());
10197 Invalid = true;
10198 }
10199
Sebastian Redl4b07b292008-12-22 19:15:10 +000010200 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010201 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010202 LookupOrdinaryName,
10203 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010204 // The scope should be freshly made just for us. There is just no way
10205 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010206 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010207 if (PrevDecl->isTemplateParameter()) {
10208 // Maybe we will complain about the shadowed template parameter.
10209 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010210 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010211 }
10212 }
10213
Chris Lattnereaaebc72009-04-25 08:06:05 +000010214 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010215 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10216 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010217 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010218 }
10219
Douglas Gregor83cb9422010-09-09 17:09:21 +000010220 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010221 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010222 D.getIdentifierLoc(),
10223 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010224 if (Invalid)
10225 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010226
Sebastian Redl4b07b292008-12-22 19:15:10 +000010227 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010228 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010229 PushOnScopeChains(ExDecl, S);
10230 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010231 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010232
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010233 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010234 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010235}
Anders Carlssonfb311762009-03-14 00:25:26 +000010236
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010237Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010238 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010239 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010240 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010241 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010242
Richard Smithe3f470a2012-07-11 22:37:56 +000010243 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10244 return 0;
10245
10246 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10247 AssertMessage, RParenLoc, false);
10248}
10249
10250Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10251 Expr *AssertExpr,
10252 StringLiteral *AssertMessage,
10253 SourceLocation RParenLoc,
10254 bool Failed) {
10255 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10256 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010257 // In a static_assert-declaration, the constant-expression shall be a
10258 // constant expression that can be contextually converted to bool.
10259 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10260 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010261 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010262
Richard Smithdaaefc52011-12-14 23:32:26 +000010263 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010264 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010265 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010266 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010267 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010268
Richard Smithe3f470a2012-07-11 22:37:56 +000010269 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010270 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010271 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010272 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010273 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010274 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010275 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010276 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010277 }
Mike Stump1eb44332009-09-09 15:08:12 +000010278
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010279 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010280 AssertExpr, AssertMessage, RParenLoc,
10281 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010282
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010283 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010284 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010285}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010286
Douglas Gregor1d869352010-04-07 16:53:43 +000010287/// \brief Perform semantic analysis of the given friend type declaration.
10288///
10289/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010290FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010291 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010292 TypeSourceInfo *TSInfo) {
10293 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10294
10295 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010296 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010297
Richard Smith6b130222011-10-18 21:39:00 +000010298 // C++03 [class.friend]p2:
10299 // An elaborated-type-specifier shall be used in a friend declaration
10300 // for a class.*
10301 //
10302 // * The class-key of the elaborated-type-specifier is required.
10303 if (!ActiveTemplateInstantiations.empty()) {
10304 // Do not complain about the form of friend template types during
10305 // template instantiation; we will already have complained when the
10306 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010307 } else {
10308 if (!T->isElaboratedTypeSpecifier()) {
10309 // If we evaluated the type to a record type, suggest putting
10310 // a tag in front.
10311 if (const RecordType *RT = T->getAs<RecordType>()) {
10312 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010313
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010314 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010315
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010316 Diag(TypeRange.getBegin(),
10317 getLangOpts().CPlusPlus11 ?
10318 diag::warn_cxx98_compat_unelaborated_friend_type :
10319 diag::ext_unelaborated_friend_type)
10320 << (unsigned) RD->getTagKind()
10321 << T
10322 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10323 InsertionText);
10324 } else {
10325 Diag(FriendLoc,
10326 getLangOpts().CPlusPlus11 ?
10327 diag::warn_cxx98_compat_nonclass_type_friend :
10328 diag::ext_nonclass_type_friend)
10329 << T
10330 << TypeRange;
10331 }
10332 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010333 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010334 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010335 diag::warn_cxx98_compat_enum_friend :
10336 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010337 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010338 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010339 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010340
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010341 // C++11 [class.friend]p3:
10342 // A friend declaration that does not declare a function shall have one
10343 // of the following forms:
10344 // friend elaborated-type-specifier ;
10345 // friend simple-type-specifier ;
10346 // friend typename-specifier ;
10347 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10348 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10349 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010350
Douglas Gregor06245bf2010-04-07 17:57:12 +000010351 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010352 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010353 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010354 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010355}
10356
John McCall9a34edb2010-10-19 01:40:49 +000010357/// Handle a friend tag declaration where the scope specifier was
10358/// templated.
10359Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10360 unsigned TagSpec, SourceLocation TagLoc,
10361 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010362 IdentifierInfo *Name,
10363 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010364 AttributeList *Attr,
10365 MultiTemplateParamsArg TempParamLists) {
10366 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10367
10368 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010369 bool Invalid = false;
10370
10371 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010372 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010373 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010374 TempParamLists.size(),
10375 /*friend*/ true,
10376 isExplicitSpecialization,
10377 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010378 if (TemplateParams->size() > 0) {
10379 // This is a declaration of a class template.
10380 if (Invalid)
10381 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010382
Eric Christopher4110e132011-07-21 05:34:24 +000010383 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10384 SS, Name, NameLoc, Attr,
10385 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010386 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010387 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010388 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010389 } else {
10390 // The "template<>" header is extraneous.
10391 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10392 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10393 isExplicitSpecialization = true;
10394 }
10395 }
10396
10397 if (Invalid) return 0;
10398
John McCall9a34edb2010-10-19 01:40:49 +000010399 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010400 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010401 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010402 isAllExplicitSpecializations = false;
10403 break;
10404 }
10405 }
10406
10407 // FIXME: don't ignore attributes.
10408
10409 // If it's explicit specializations all the way down, just forget
10410 // about the template header and build an appropriate non-templated
10411 // friend. TODO: for source fidelity, remember the headers.
10412 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010413 if (SS.isEmpty()) {
10414 bool Owned = false;
10415 bool IsDependent = false;
10416 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10417 Attr, AS_public,
10418 /*ModulePrivateLoc=*/SourceLocation(),
10419 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010420 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010421 /*ScopedEnumUsesClassTag=*/false,
10422 /*UnderlyingType=*/TypeResult());
10423 }
10424
Douglas Gregor2494dd02011-03-01 01:34:45 +000010425 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010426 ElaboratedTypeKeyword Keyword
10427 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010428 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010429 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010430 if (T.isNull())
10431 return 0;
10432
10433 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10434 if (isa<DependentNameType>(T)) {
10435 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010436 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010437 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010438 TL.setNameLoc(NameLoc);
10439 } else {
10440 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010441 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010442 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010443 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10444 }
10445
10446 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010447 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010448 Friend->setAccess(AS_public);
10449 CurContext->addDecl(Friend);
10450 return Friend;
10451 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010452
10453 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10454
10455
John McCall9a34edb2010-10-19 01:40:49 +000010456
10457 // Handle the case of a templated-scope friend class. e.g.
10458 // template <class T> class A<T>::B;
10459 // FIXME: we don't support these right now.
10460 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10461 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10462 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10463 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010464 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010465 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010466 TL.setNameLoc(NameLoc);
10467
10468 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010469 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010470 Friend->setAccess(AS_public);
10471 Friend->setUnsupportedFriend(true);
10472 CurContext->addDecl(Friend);
10473 return Friend;
10474}
10475
10476
John McCalldd4a3b02009-09-16 22:47:08 +000010477/// Handle a friend type declaration. This works in tandem with
10478/// ActOnTag.
10479///
10480/// Notes on friend class templates:
10481///
10482/// We generally treat friend class declarations as if they were
10483/// declaring a class. So, for example, the elaborated type specifier
10484/// in a friend declaration is required to obey the restrictions of a
10485/// class-head (i.e. no typedefs in the scope chain), template
10486/// parameters are required to match up with simple template-ids, &c.
10487/// However, unlike when declaring a template specialization, it's
10488/// okay to refer to a template specialization without an empty
10489/// template parameter declaration, e.g.
10490/// friend class A<T>::B<unsigned>;
10491/// We permit this as a special case; if there are any template
10492/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010493/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010494Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010495 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010496 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010497
10498 assert(DS.isFriendSpecified());
10499 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10500
John McCalldd4a3b02009-09-16 22:47:08 +000010501 // Try to convert the decl specifier to a type. This works for
10502 // friend templates because ActOnTag never produces a ClassTemplateDecl
10503 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010504 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010505 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10506 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010507 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010508 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010509
Douglas Gregor6ccab972010-12-16 01:14:37 +000010510 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10511 return 0;
10512
John McCalldd4a3b02009-09-16 22:47:08 +000010513 // This is definitely an error in C++98. It's probably meant to
10514 // be forbidden in C++0x, too, but the specification is just
10515 // poorly written.
10516 //
10517 // The problem is with declarations like the following:
10518 // template <T> friend A<T>::foo;
10519 // where deciding whether a class C is a friend or not now hinges
10520 // on whether there exists an instantiation of A that causes
10521 // 'foo' to equal C. There are restrictions on class-heads
10522 // (which we declare (by fiat) elaborated friend declarations to
10523 // be) that makes this tractable.
10524 //
10525 // FIXME: handle "template <> friend class A<T>;", which
10526 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010527 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010528 Diag(Loc, diag::err_tagless_friend_type_template)
10529 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010530 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010531 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010532
John McCall02cace72009-08-28 07:59:38 +000010533 // C++98 [class.friend]p1: A friend of a class is a function
10534 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010535 // This is fixed in DR77, which just barely didn't make the C++03
10536 // deadline. It's also a very silly restriction that seriously
10537 // affects inner classes and which nobody else seems to implement;
10538 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010539 //
10540 // But note that we could warn about it: it's always useless to
10541 // friend one of your own members (it's not, however, worthless to
10542 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010543
John McCalldd4a3b02009-09-16 22:47:08 +000010544 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010545 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010546 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010547 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010548 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010549 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010550 DS.getFriendSpecLoc());
10551 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010552 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010553
10554 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010555 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010556
John McCalldd4a3b02009-09-16 22:47:08 +000010557 D->setAccess(AS_public);
10558 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010559
John McCalld226f652010-08-21 09:40:31 +000010560 return D;
John McCall02cace72009-08-28 07:59:38 +000010561}
10562
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000010563NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10564 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010565 const DeclSpec &DS = D.getDeclSpec();
10566
10567 assert(DS.isFriendSpecified());
10568 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10569
10570 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010571 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010572
10573 // C++ [class.friend]p1
10574 // A friend of a class is a function or class....
10575 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010576 // It *doesn't* see through dependent types, which is correct
10577 // according to [temp.arg.type]p3:
10578 // If a declaration acquires a function type through a
10579 // type dependent on a template-parameter and this causes
10580 // a declaration that does not use the syntactic form of a
10581 // function declarator to have a function type, the program
10582 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010583 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010584 Diag(Loc, diag::err_unexpected_friend);
10585
10586 // It might be worthwhile to try to recover by creating an
10587 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010588 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010589 }
10590
10591 // C++ [namespace.memdef]p3
10592 // - If a friend declaration in a non-local class first declares a
10593 // class or function, the friend class or function is a member
10594 // of the innermost enclosing namespace.
10595 // - The name of the friend is not found by simple name lookup
10596 // until a matching declaration is provided in that namespace
10597 // scope (either before or after the class declaration granting
10598 // friendship).
10599 // - If a friend function is called, its name may be found by the
10600 // name lookup that considers functions from namespaces and
10601 // classes associated with the types of the function arguments.
10602 // - When looking for a prior declaration of a class or a function
10603 // declared as a friend, scopes outside the innermost enclosing
10604 // namespace scope are not considered.
10605
John McCall337ec3d2010-10-12 23:13:28 +000010606 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010607 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10608 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010609 assert(Name);
10610
Douglas Gregor6ccab972010-12-16 01:14:37 +000010611 // Check for unexpanded parameter packs.
10612 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10613 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10614 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10615 return 0;
10616
John McCall67d1a672009-08-06 02:15:43 +000010617 // The context we found the declaration in, or in which we should
10618 // create the declaration.
10619 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010620 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010621 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010622 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010623
John McCall337ec3d2010-10-12 23:13:28 +000010624 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010625
John McCall337ec3d2010-10-12 23:13:28 +000010626 // There are four cases here.
10627 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010628 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010629 // there as appropriate.
10630 // Recover from invalid scope qualifiers as if they just weren't there.
10631 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010632 // C++0x [namespace.memdef]p3:
10633 // If the name in a friend declaration is neither qualified nor
10634 // a template-id and the declaration is a function or an
10635 // elaborated-type-specifier, the lookup to determine whether
10636 // the entity has been previously declared shall not consider
10637 // any scopes outside the innermost enclosing namespace.
10638 // C++0x [class.friend]p11:
10639 // If a friend declaration appears in a local class and the name
10640 // specified is an unqualified name, a prior declaration is
10641 // looked up without considering scopes that are outside the
10642 // innermost enclosing non-class scope. For a friend function
10643 // declaration, if there is no prior declaration, the program is
10644 // ill-formed.
10645 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010646 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010647
John McCall29ae6e52010-10-13 05:45:15 +000010648 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010649 DC = CurContext;
10650 while (true) {
10651 // Skip class contexts. If someone can cite chapter and verse
10652 // for this behavior, that would be nice --- it's what GCC and
10653 // EDG do, and it seems like a reasonable intent, but the spec
10654 // really only says that checks for unqualified existing
10655 // declarations should stop at the nearest enclosing namespace,
10656 // not that they should only consider the nearest enclosing
10657 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010658 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010659 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010660
John McCall68263142009-11-18 22:49:29 +000010661 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010662
10663 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010664 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010665 break;
John McCall29ae6e52010-10-13 05:45:15 +000010666
John McCall8a407372010-10-14 22:22:28 +000010667 if (isTemplateId) {
10668 if (isa<TranslationUnitDecl>(DC)) break;
10669 } else {
10670 if (DC->isFileContext()) break;
10671 }
John McCall67d1a672009-08-06 02:15:43 +000010672 DC = DC->getParent();
10673 }
10674
10675 // C++ [class.friend]p1: A friend of a class is a function or
10676 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010677 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010678 // Most C++ 98 compilers do seem to give an error here, so
10679 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010680 if (!Previous.empty() && DC->Equals(CurContext))
10681 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010682 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010683 diag::warn_cxx98_compat_friend_is_member :
10684 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010685
John McCall380aaa42010-10-13 06:22:15 +000010686 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010687
Douglas Gregor883af832011-10-10 01:11:59 +000010688 // C++ [class.friend]p6:
10689 // A function can be defined in a friend declaration of a class if and
10690 // only if the class is a non-local class (9.8), the function name is
10691 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010692 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010693 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10694 }
10695
John McCall337ec3d2010-10-12 23:13:28 +000010696 // - There's a non-dependent scope specifier, in which case we
10697 // compute it and do a previous lookup there for a function
10698 // or function template.
10699 } else if (!SS.getScopeRep()->isDependent()) {
10700 DC = computeDeclContext(SS);
10701 if (!DC) return 0;
10702
10703 if (RequireCompleteDeclContext(SS, DC)) return 0;
10704
10705 LookupQualifiedName(Previous, DC);
10706
10707 // Ignore things found implicitly in the wrong scope.
10708 // TODO: better diagnostics for this case. Suggesting the right
10709 // qualified scope would be nice...
10710 LookupResult::Filter F = Previous.makeFilter();
10711 while (F.hasNext()) {
10712 NamedDecl *D = F.next();
10713 if (!DC->InEnclosingNamespaceSetOf(
10714 D->getDeclContext()->getRedeclContext()))
10715 F.erase();
10716 }
10717 F.done();
10718
10719 if (Previous.empty()) {
10720 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010721 Diag(Loc, diag::err_qualified_friend_not_found)
10722 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010723 return 0;
10724 }
10725
10726 // C++ [class.friend]p1: A friend of a class is a function or
10727 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010728 if (DC->Equals(CurContext))
10729 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010730 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010731 diag::warn_cxx98_compat_friend_is_member :
10732 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010733
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010734 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010735 // C++ [class.friend]p6:
10736 // A function can be defined in a friend declaration of a class if and
10737 // only if the class is a non-local class (9.8), the function name is
10738 // unqualified, and the function has namespace scope.
10739 SemaDiagnosticBuilder DB
10740 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10741
10742 DB << SS.getScopeRep();
10743 if (DC->isFileContext())
10744 DB << FixItHint::CreateRemoval(SS.getRange());
10745 SS.clear();
10746 }
John McCall337ec3d2010-10-12 23:13:28 +000010747
10748 // - There's a scope specifier that does not match any template
10749 // parameter lists, in which case we use some arbitrary context,
10750 // create a method or method template, and wait for instantiation.
10751 // - There's a scope specifier that does match some template
10752 // parameter lists, which we don't handle right now.
10753 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010754 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010755 // C++ [class.friend]p6:
10756 // A function can be defined in a friend declaration of a class if and
10757 // only if the class is a non-local class (9.8), the function name is
10758 // unqualified, and the function has namespace scope.
10759 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10760 << SS.getScopeRep();
10761 }
10762
John McCall337ec3d2010-10-12 23:13:28 +000010763 DC = CurContext;
10764 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010765 }
Douglas Gregor883af832011-10-10 01:11:59 +000010766
John McCall29ae6e52010-10-13 05:45:15 +000010767 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010768 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010769 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10770 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10771 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010772 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010773 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10774 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010775 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010776 }
John McCall67d1a672009-08-06 02:15:43 +000010777 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010778
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010779 // FIXME: This is an egregious hack to cope with cases where the scope stack
10780 // does not contain the declaration context, i.e., in an out-of-line
10781 // definition of a class.
10782 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10783 if (!DCScope) {
10784 FakeDCScope.setEntity(DC);
10785 DCScope = &FakeDCScope;
10786 }
10787
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010788 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010789 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010790 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010791 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010792
Douglas Gregor182ddf02009-09-28 00:08:27 +000010793 assert(ND->getDeclContext() == DC);
10794 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010795
John McCallab88d972009-08-31 22:39:49 +000010796 // Add the function declaration to the appropriate lookup tables,
10797 // adjusting the redeclarations list as necessary. We don't
10798 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010799 //
John McCallab88d972009-08-31 22:39:49 +000010800 // Also update the scope-based lookup if the target context's
10801 // lookup context is in lexical scope.
10802 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010803 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010804 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010805 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010806 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010807 }
John McCall02cace72009-08-28 07:59:38 +000010808
10809 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010810 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010811 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010812 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010813 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010814
John McCall1f2e1a92012-08-10 03:15:35 +000010815 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010816 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010817 } else {
10818 if (DC->isRecord()) CheckFriendAccess(ND);
10819
John McCall6102ca12010-10-16 06:59:13 +000010820 FunctionDecl *FD;
10821 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10822 FD = FTD->getTemplatedDecl();
10823 else
10824 FD = cast<FunctionDecl>(ND);
10825
10826 // Mark templated-scope function declarations as unsupported.
10827 if (FD->getNumTemplateParameterLists())
10828 FrD->setUnsupportedFriend(true);
10829 }
John McCall337ec3d2010-10-12 23:13:28 +000010830
John McCalld226f652010-08-21 09:40:31 +000010831 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010832}
10833
John McCalld226f652010-08-21 09:40:31 +000010834void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10835 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010836
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000010837 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000010838 if (!Fn) {
10839 Diag(DelLoc, diag::err_deleted_non_function);
10840 return;
10841 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010842 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010843 // Don't consider the implicit declaration we generate for explicit
10844 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010845 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10846 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010847 Diag(DelLoc, diag::err_deleted_decl_not_first);
10848 Diag(Prev->getLocation(), diag::note_previous_declaration);
10849 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010850 // If the declaration wasn't the first, we delete the function anyway for
10851 // recovery.
10852 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010853 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010854}
Sebastian Redl13e88542009-04-27 21:33:24 +000010855
Sean Hunte4246a62011-05-12 06:15:49 +000010856void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000010857 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000010858
10859 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010860 if (MD->getParent()->isDependentType()) {
10861 MD->setDefaulted();
10862 MD->setExplicitlyDefaulted();
10863 return;
10864 }
10865
Sean Hunte4246a62011-05-12 06:15:49 +000010866 CXXSpecialMember Member = getSpecialMember(MD);
10867 if (Member == CXXInvalid) {
10868 Diag(DefaultLoc, diag::err_default_special_members);
10869 return;
10870 }
10871
10872 MD->setDefaulted();
10873 MD->setExplicitlyDefaulted();
10874
Sean Huntcd10dec2011-05-23 23:14:04 +000010875 // If this definition appears within the record, do the checking when
10876 // the record is complete.
10877 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000010878 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000010879 // Find the uninstantiated declaration that actually had the '= default'
10880 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000010881 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000010882
10883 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010884 return;
10885
Richard Smithb9d0b762012-07-27 04:22:15 +000010886 CheckExplicitlyDefaultedSpecialMember(MD);
10887
Richard Smith1d28caf2012-12-11 01:14:52 +000010888 // The exception specification is needed because we are defining the
10889 // function.
10890 ResolveExceptionSpec(DefaultLoc,
10891 MD->getType()->castAs<FunctionProtoType>());
10892
Sean Hunte4246a62011-05-12 06:15:49 +000010893 switch (Member) {
10894 case CXXDefaultConstructor: {
10895 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010896 if (!CD->isInvalidDecl())
10897 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10898 break;
10899 }
10900
10901 case CXXCopyConstructor: {
10902 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010903 if (!CD->isInvalidDecl())
10904 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010905 break;
10906 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010907
Sean Hunt2b188082011-05-14 05:23:28 +000010908 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010909 if (!MD->isInvalidDecl())
10910 DefineImplicitCopyAssignment(DefaultLoc, MD);
10911 break;
10912 }
10913
Sean Huntcb45a0f2011-05-12 22:46:25 +000010914 case CXXDestructor: {
10915 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010916 if (!DD->isInvalidDecl())
10917 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010918 break;
10919 }
10920
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010921 case CXXMoveConstructor: {
10922 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010923 if (!CD->isInvalidDecl())
10924 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010925 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010926 }
Sean Hunt82713172011-05-25 23:16:36 +000010927
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010928 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010929 if (!MD->isInvalidDecl())
10930 DefineImplicitMoveAssignment(DefaultLoc, MD);
10931 break;
10932 }
10933
10934 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010935 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010936 }
10937 } else {
10938 Diag(DefaultLoc, diag::err_default_special_members);
10939 }
10940}
10941
Sebastian Redl13e88542009-04-27 21:33:24 +000010942static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010943 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010944 Stmt *SubStmt = *CI;
10945 if (!SubStmt)
10946 continue;
10947 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010948 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010949 diag::err_return_in_constructor_handler);
10950 if (!isa<Expr>(SubStmt))
10951 SearchForReturnInStmt(Self, SubStmt);
10952 }
10953}
10954
10955void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10956 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10957 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10958 SearchForReturnInStmt(*this, Handler);
10959 }
10960}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010961
David Blaikie299adab2013-01-18 23:03:15 +000010962bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000010963 const CXXMethodDecl *Old) {
10964 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
10965 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
10966
10967 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
10968
10969 // If the calling conventions match, everything is fine
10970 if (NewCC == OldCC)
10971 return false;
10972
10973 // If either of the calling conventions are set to "default", we need to pick
10974 // something more sensible based on the target. This supports code where the
10975 // one method explicitly sets thiscall, and another has no explicit calling
10976 // convention.
10977 CallingConv Default =
10978 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
10979 if (NewCC == CC_Default)
10980 NewCC = Default;
10981 if (OldCC == CC_Default)
10982 OldCC = Default;
10983
10984 // If the calling conventions still don't match, then report the error
10985 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000010986 Diag(New->getLocation(),
10987 diag::err_conflicting_overriding_cc_attributes)
10988 << New->getDeclName() << New->getType() << Old->getType();
10989 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10990 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000010991 }
10992
10993 return false;
10994}
10995
Mike Stump1eb44332009-09-09 15:08:12 +000010996bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010997 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010998 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10999 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011000
Chandler Carruth73857792010-02-15 11:53:20 +000011001 if (Context.hasSameType(NewTy, OldTy) ||
11002 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011003 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011004
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011005 // Check if the return types are covariant
11006 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011007
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011008 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011009 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11010 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011011 NewClassTy = NewPT->getPointeeType();
11012 OldClassTy = OldPT->getPointeeType();
11013 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011014 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11015 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11016 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11017 NewClassTy = NewRT->getPointeeType();
11018 OldClassTy = OldRT->getPointeeType();
11019 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011020 }
11021 }
Mike Stump1eb44332009-09-09 15:08:12 +000011022
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011023 // The return types aren't either both pointers or references to a class type.
11024 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011025 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011026 diag::err_different_return_type_for_overriding_virtual_function)
11027 << New->getDeclName() << NewTy << OldTy;
11028 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011029
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011030 return true;
11031 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011032
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011033 // C++ [class.virtual]p6:
11034 // If the return type of D::f differs from the return type of B::f, the
11035 // class type in the return type of D::f shall be complete at the point of
11036 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011037 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11038 if (!RT->isBeingDefined() &&
11039 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011040 diag::err_covariant_return_incomplete,
11041 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011042 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011043 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011044
Douglas Gregora4923eb2009-11-16 21:35:15 +000011045 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011046 // Check if the new class derives from the old class.
11047 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11048 Diag(New->getLocation(),
11049 diag::err_covariant_return_not_derived)
11050 << New->getDeclName() << NewTy << OldTy;
11051 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11052 return true;
11053 }
Mike Stump1eb44332009-09-09 15:08:12 +000011054
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011055 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011056 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011057 diag::err_covariant_return_inaccessible_base,
11058 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11059 // FIXME: Should this point to the return type?
11060 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011061 // FIXME: this note won't trigger for delayed access control
11062 // diagnostics, and it's impossible to get an undelayed error
11063 // here from access control during the original parse because
11064 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011065 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11066 return true;
11067 }
11068 }
Mike Stump1eb44332009-09-09 15:08:12 +000011069
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011070 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011071 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011072 Diag(New->getLocation(),
11073 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011074 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011075 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11076 return true;
11077 };
Mike Stump1eb44332009-09-09 15:08:12 +000011078
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011079
11080 // The new class type must have the same or less qualifiers as the old type.
11081 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11082 Diag(New->getLocation(),
11083 diag::err_covariant_return_type_class_type_more_qualified)
11084 << New->getDeclName() << NewTy << OldTy;
11085 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11086 return true;
11087 };
Mike Stump1eb44332009-09-09 15:08:12 +000011088
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011089 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011090}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011091
Douglas Gregor4ba31362009-12-01 17:24:26 +000011092/// \brief Mark the given method pure.
11093///
11094/// \param Method the method to be marked pure.
11095///
11096/// \param InitRange the source range that covers the "0" initializer.
11097bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011098 SourceLocation EndLoc = InitRange.getEnd();
11099 if (EndLoc.isValid())
11100 Method->setRangeEnd(EndLoc);
11101
Douglas Gregor4ba31362009-12-01 17:24:26 +000011102 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11103 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011104 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011105 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011106
11107 if (!Method->isInvalidDecl())
11108 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11109 << Method->getDeclName() << InitRange;
11110 return true;
11111}
11112
Douglas Gregor552e2992012-02-21 02:22:07 +000011113/// \brief Determine whether the given declaration is a static data member.
11114static bool isStaticDataMember(Decl *D) {
11115 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11116 if (!Var)
11117 return false;
11118
11119 return Var->isStaticDataMember();
11120}
John McCall731ad842009-12-19 09:28:58 +000011121/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11122/// an initializer for the out-of-line declaration 'Dcl'. The scope
11123/// is a fresh scope pushed for just this purpose.
11124///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011125/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11126/// static data member of class X, names should be looked up in the scope of
11127/// class X.
John McCalld226f652010-08-21 09:40:31 +000011128void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011129 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011130 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011131
John McCall731ad842009-12-19 09:28:58 +000011132 // We should only get called for declarations with scope specifiers, like:
11133 // int foo::bar;
11134 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011135 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011136
11137 // If we are parsing the initializer for a static data member, push a
11138 // new expression evaluation context that is associated with this static
11139 // data member.
11140 if (isStaticDataMember(D))
11141 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011142}
11143
11144/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011145/// initializer for the out-of-line declaration 'D'.
11146void Sema::ActOnCXXExitDeclInitializer(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
Douglas Gregor552e2992012-02-21 02:22:07 +000011150 if (isStaticDataMember(D))
11151 PopExpressionEvaluationContext();
11152
John McCall731ad842009-12-19 09:28:58 +000011153 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011154 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011155}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011156
11157/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11158/// C++ if/switch/while/for statement.
11159/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011160DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011161 // C++ 6.4p2:
11162 // The declarator shall not specify a function or an array.
11163 // The type-specifier-seq shall not contain typedef and shall not declare a
11164 // new class or enumeration.
11165 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11166 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011167
11168 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011169 if (!Dcl)
11170 return true;
11171
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011172 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11173 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011174 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011175 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011176 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011177
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011178 return Dcl;
11179}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011180
Douglas Gregordfe65432011-07-28 19:11:31 +000011181void Sema::LoadExternalVTableUses() {
11182 if (!ExternalSource)
11183 return;
11184
11185 SmallVector<ExternalVTableUse, 4> VTables;
11186 ExternalSource->ReadUsedVTables(VTables);
11187 SmallVector<VTableUse, 4> NewUses;
11188 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11189 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11190 = VTablesUsed.find(VTables[I].Record);
11191 // Even if a definition wasn't required before, it may be required now.
11192 if (Pos != VTablesUsed.end()) {
11193 if (!Pos->second && VTables[I].DefinitionRequired)
11194 Pos->second = true;
11195 continue;
11196 }
11197
11198 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11199 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11200 }
11201
11202 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11203}
11204
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011205void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11206 bool DefinitionRequired) {
11207 // Ignore any vtable uses in unevaluated operands or for classes that do
11208 // not have a vtable.
11209 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11210 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011211 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011212 return;
11213
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011214 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011215 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011216 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11217 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11218 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11219 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011220 // If we already had an entry, check to see if we are promoting this vtable
11221 // to required a definition. If so, we need to reappend to the VTableUses
11222 // list, since we may have already processed the first entry.
11223 if (DefinitionRequired && !Pos.first->second) {
11224 Pos.first->second = true;
11225 } else {
11226 // Otherwise, we can early exit.
11227 return;
11228 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011229 }
11230
11231 // Local classes need to have their virtual members marked
11232 // immediately. For all other classes, we mark their virtual members
11233 // at the end of the translation unit.
11234 if (Class->isLocalClass())
11235 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011236 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011237 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011238}
11239
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011240bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011241 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011242 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011243 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011244
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011245 // Note: The VTableUses vector could grow as a result of marking
11246 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011247 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011248 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011249 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011250 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011251 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011252 if (!Class)
11253 continue;
11254
11255 SourceLocation Loc = VTableUses[I].second;
11256
Richard Smithb9d0b762012-07-27 04:22:15 +000011257 bool DefineVTable = true;
11258
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011259 // If this class has a key function, but that key function is
11260 // defined in another translation unit, we don't need to emit the
11261 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011262 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011263 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011264 switch (KeyFunction->getTemplateSpecializationKind()) {
11265 case TSK_Undeclared:
11266 case TSK_ExplicitSpecialization:
11267 case TSK_ExplicitInstantiationDeclaration:
11268 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011269 DefineVTable = false;
11270 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011271
11272 case TSK_ExplicitInstantiationDefinition:
11273 case TSK_ImplicitInstantiation:
11274 // We will be instantiating the key function.
11275 break;
11276 }
11277 } else if (!KeyFunction) {
11278 // If we have a class with no key function that is the subject
11279 // of an explicit instantiation declaration, suppress the
11280 // vtable; it will live with the explicit instantiation
11281 // definition.
11282 bool IsExplicitInstantiationDeclaration
11283 = Class->getTemplateSpecializationKind()
11284 == TSK_ExplicitInstantiationDeclaration;
11285 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11286 REnd = Class->redecls_end();
11287 R != REnd; ++R) {
11288 TemplateSpecializationKind TSK
11289 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11290 if (TSK == TSK_ExplicitInstantiationDeclaration)
11291 IsExplicitInstantiationDeclaration = true;
11292 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11293 IsExplicitInstantiationDeclaration = false;
11294 break;
11295 }
11296 }
11297
11298 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011299 DefineVTable = false;
11300 }
11301
11302 // The exception specifications for all virtual members may be needed even
11303 // if we are not providing an authoritative form of the vtable in this TU.
11304 // We may choose to emit it available_externally anyway.
11305 if (!DefineVTable) {
11306 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11307 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011308 }
11309
11310 // Mark all of the virtual members of this class as referenced, so
11311 // that we can build a vtable. Then, tell the AST consumer that a
11312 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011313 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011314 MarkVirtualMembersReferenced(Loc, Class);
11315 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11316 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11317
11318 // Optionally warn if we're emitting a weak vtable.
11319 if (Class->getLinkage() == ExternalLinkage &&
11320 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011321 const FunctionDecl *KeyFunctionDef = 0;
11322 if (!KeyFunction ||
11323 (KeyFunction->hasBody(KeyFunctionDef) &&
11324 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011325 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11326 TSK_ExplicitInstantiationDefinition
11327 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11328 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011329 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011330 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011331 VTableUses.clear();
11332
Douglas Gregor78844032011-04-22 22:25:37 +000011333 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011334}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011335
Richard Smithb9d0b762012-07-27 04:22:15 +000011336void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11337 const CXXRecordDecl *RD) {
11338 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11339 E = RD->method_end(); I != E; ++I)
11340 if ((*I)->isVirtual() && !(*I)->isPure())
11341 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11342}
11343
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011344void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11345 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011346 // Mark all functions which will appear in RD's vtable as used.
11347 CXXFinalOverriderMap FinalOverriders;
11348 RD->getFinalOverriders(FinalOverriders);
11349 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11350 E = FinalOverriders.end();
11351 I != E; ++I) {
11352 for (OverridingMethods::const_iterator OI = I->second.begin(),
11353 OE = I->second.end();
11354 OI != OE; ++OI) {
11355 assert(OI->second.size() > 0 && "no final overrider");
11356 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011357
Richard Smithff817f72012-07-07 06:59:51 +000011358 // C++ [basic.def.odr]p2:
11359 // [...] A virtual member function is used if it is not pure. [...]
11360 if (!Overrider->isPure())
11361 MarkFunctionReferenced(Loc, Overrider);
11362 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011363 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011364
11365 // Only classes that have virtual bases need a VTT.
11366 if (RD->getNumVBases() == 0)
11367 return;
11368
11369 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11370 e = RD->bases_end(); i != e; ++i) {
11371 const CXXRecordDecl *Base =
11372 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011373 if (Base->getNumVBases() == 0)
11374 continue;
11375 MarkVirtualMembersReferenced(Loc, Base);
11376 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011377}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011378
11379/// SetIvarInitializers - This routine builds initialization ASTs for the
11380/// Objective-C implementation whose ivars need be initialized.
11381void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011382 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011383 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011384 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011385 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011386 CollectIvarsToConstructOrDestruct(OID, ivars);
11387 if (ivars.empty())
11388 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011389 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011390 for (unsigned i = 0; i < ivars.size(); i++) {
11391 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011392 if (Field->isInvalidDecl())
11393 continue;
11394
Sean Huntcbb67482011-01-08 20:30:50 +000011395 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011396 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11397 InitializationKind InitKind =
11398 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11399
11400 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011401 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011402 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011403 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011404 // Note, MemberInit could actually come back empty if no initialization
11405 // is required (e.g., because it would call a trivial default constructor)
11406 if (!MemberInit.get() || MemberInit.isInvalid())
11407 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011408
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011409 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011410 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11411 SourceLocation(),
11412 MemberInit.takeAs<Expr>(),
11413 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011414 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011415
11416 // Be sure that the destructor is accessible and is marked as referenced.
11417 if (const RecordType *RecordTy
11418 = Context.getBaseElementType(Field->getType())
11419 ->getAs<RecordType>()) {
11420 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011421 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011422 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011423 CheckDestructorAccess(Field->getLocation(), Destructor,
11424 PDiag(diag::err_access_dtor_ivar)
11425 << Context.getBaseElementType(Field->getType()));
11426 }
11427 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011428 }
11429 ObjCImplementation->setIvarInitializers(Context,
11430 AllToInit.data(), AllToInit.size());
11431 }
11432}
Sean Huntfe57eef2011-05-04 05:57:24 +000011433
Sean Huntebcbe1d2011-05-04 23:29:54 +000011434static
11435void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11436 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11437 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11438 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11439 Sema &S) {
11440 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11441 CE = Current.end();
11442 if (Ctor->isInvalidDecl())
11443 return;
11444
Richard Smitha8eaf002012-08-23 06:16:52 +000011445 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11446
11447 // Target may not be determinable yet, for instance if this is a dependent
11448 // call in an uninstantiated template.
11449 if (Target) {
11450 const FunctionDecl *FNTarget = 0;
11451 (void)Target->hasBody(FNTarget);
11452 Target = const_cast<CXXConstructorDecl*>(
11453 cast_or_null<CXXConstructorDecl>(FNTarget));
11454 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011455
11456 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11457 // Avoid dereferencing a null pointer here.
11458 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11459
11460 if (!Current.insert(Canonical))
11461 return;
11462
11463 // We know that beyond here, we aren't chaining into a cycle.
11464 if (!Target || !Target->isDelegatingConstructor() ||
11465 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11466 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11467 Valid.insert(*CI);
11468 Current.clear();
11469 // We've hit a cycle.
11470 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11471 Current.count(TCanonical)) {
11472 // If we haven't diagnosed this cycle yet, do so now.
11473 if (!Invalid.count(TCanonical)) {
11474 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011475 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011476 << Ctor;
11477
Richard Smitha8eaf002012-08-23 06:16:52 +000011478 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011479 if (TCanonical != Canonical)
11480 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11481
11482 CXXConstructorDecl *C = Target;
11483 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011484 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011485 (void)C->getTargetConstructor()->hasBody(FNTarget);
11486 assert(FNTarget && "Ctor cycle through bodiless function");
11487
Richard Smitha8eaf002012-08-23 06:16:52 +000011488 C = const_cast<CXXConstructorDecl*>(
11489 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011490 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11491 }
11492 }
11493
11494 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11495 Invalid.insert(*CI);
11496 Current.clear();
11497 } else {
11498 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11499 }
11500}
11501
11502
Sean Huntfe57eef2011-05-04 05:57:24 +000011503void Sema::CheckDelegatingCtorCycles() {
11504 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11505
Sean Huntebcbe1d2011-05-04 23:29:54 +000011506 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11507 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011508
Douglas Gregor0129b562011-07-27 21:57:17 +000011509 for (DelegatingCtorDeclsType::iterator
11510 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011511 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011512 I != E; ++I)
11513 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011514
11515 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11516 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011517}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011518
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011519namespace {
11520 /// \brief AST visitor that finds references to the 'this' expression.
11521 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11522 Sema &S;
11523
11524 public:
11525 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11526
11527 bool VisitCXXThisExpr(CXXThisExpr *E) {
11528 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11529 << E->isImplicit();
11530 return false;
11531 }
11532 };
11533}
11534
11535bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11536 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11537 if (!TSInfo)
11538 return false;
11539
11540 TypeLoc TL = TSInfo->getTypeLoc();
11541 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11542 if (!ProtoTL)
11543 return false;
11544
11545 // C++11 [expr.prim.general]p3:
11546 // [The expression this] shall not appear before the optional
11547 // cv-qualifier-seq and it shall not appear within the declaration of a
11548 // static member function (although its type and value category are defined
11549 // within a static member function as they are within a non-static member
11550 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011551 // until the complete declarator is known. - end note ]
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011552 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11553 FindCXXThisExpr Finder(*this);
11554
11555 // If the return type came after the cv-qualifier-seq, check it now.
11556 if (Proto->hasTrailingReturn() &&
11557 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11558 return true;
11559
11560 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011561 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11562 return true;
11563
11564 return checkThisInStaticMemberFunctionAttributes(Method);
11565}
11566
11567bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11568 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11569 if (!TSInfo)
11570 return false;
11571
11572 TypeLoc TL = TSInfo->getTypeLoc();
11573 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11574 if (!ProtoTL)
11575 return false;
11576
11577 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11578 FindCXXThisExpr Finder(*this);
11579
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011580 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011581 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011582 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011583 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011584 case EST_DynamicNone:
11585 case EST_MSAny:
11586 case EST_None:
11587 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011588
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011589 case EST_ComputedNoexcept:
11590 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11591 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011592
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011593 case EST_Dynamic:
11594 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011595 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011596 E != EEnd; ++E) {
11597 if (!Finder.TraverseType(*E))
11598 return true;
11599 }
11600 break;
11601 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011602
11603 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011604}
11605
11606bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11607 FindCXXThisExpr Finder(*this);
11608
11609 // Check attributes.
11610 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11611 A != AEnd; ++A) {
11612 // FIXME: This should be emitted by tblgen.
11613 Expr *Arg = 0;
11614 ArrayRef<Expr *> Args;
11615 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11616 Arg = G->getArg();
11617 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11618 Arg = G->getArg();
11619 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11620 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11621 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11622 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11623 else if (ExclusiveLockFunctionAttr *ELF
11624 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11625 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11626 else if (SharedLockFunctionAttr *SLF
11627 = dyn_cast<SharedLockFunctionAttr>(*A))
11628 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11629 else if (ExclusiveTrylockFunctionAttr *ETLF
11630 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11631 Arg = ETLF->getSuccessValue();
11632 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11633 } else if (SharedTrylockFunctionAttr *STLF
11634 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11635 Arg = STLF->getSuccessValue();
11636 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11637 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11638 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11639 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11640 Arg = LR->getArg();
11641 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11642 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11643 else if (ExclusiveLocksRequiredAttr *ELR
11644 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11645 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11646 else if (SharedLocksRequiredAttr *SLR
11647 = dyn_cast<SharedLocksRequiredAttr>(*A))
11648 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11649
11650 if (Arg && !Finder.TraverseStmt(Arg))
11651 return true;
11652
11653 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11654 if (!Finder.TraverseStmt(Args[I]))
11655 return true;
11656 }
11657 }
11658
11659 return false;
11660}
11661
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011662void
11663Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11664 ArrayRef<ParsedType> DynamicExceptions,
11665 ArrayRef<SourceRange> DynamicExceptionRanges,
11666 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011667 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011668 FunctionProtoType::ExtProtoInfo &EPI) {
11669 Exceptions.clear();
11670 EPI.ExceptionSpecType = EST;
11671 if (EST == EST_Dynamic) {
11672 Exceptions.reserve(DynamicExceptions.size());
11673 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11674 // FIXME: Preserve type source info.
11675 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11676
11677 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11678 collectUnexpandedParameterPacks(ET, Unexpanded);
11679 if (!Unexpanded.empty()) {
11680 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11681 UPPC_ExceptionType,
11682 Unexpanded);
11683 continue;
11684 }
11685
11686 // Check that the type is valid for an exception spec, and
11687 // drop it if not.
11688 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11689 Exceptions.push_back(ET);
11690 }
11691 EPI.NumExceptions = Exceptions.size();
11692 EPI.Exceptions = Exceptions.data();
11693 return;
11694 }
11695
11696 if (EST == EST_ComputedNoexcept) {
11697 // If an error occurred, there's no expression here.
11698 if (NoexceptExpr) {
11699 assert((NoexceptExpr->isTypeDependent() ||
11700 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11701 Context.BoolTy) &&
11702 "Parser should have made sure that the expression is boolean");
11703 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11704 EPI.ExceptionSpecType = EST_BasicNoexcept;
11705 return;
11706 }
11707
11708 if (!NoexceptExpr->isValueDependent())
11709 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011710 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011711 /*AllowFold*/ false).take();
11712 EPI.NoexceptExpr = NoexceptExpr;
11713 }
11714 return;
11715 }
11716}
11717
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011718/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11719Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11720 // Implicitly declared functions (e.g. copy constructors) are
11721 // __host__ __device__
11722 if (D->isImplicit())
11723 return CFT_HostDevice;
11724
11725 if (D->hasAttr<CUDAGlobalAttr>())
11726 return CFT_Global;
11727
11728 if (D->hasAttr<CUDADeviceAttr>()) {
11729 if (D->hasAttr<CUDAHostAttr>())
11730 return CFT_HostDevice;
11731 else
11732 return CFT_Device;
11733 }
11734
11735 return CFT_Host;
11736}
11737
11738bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11739 CUDAFunctionTarget CalleeTarget) {
11740 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11741 // Callable from the device only."
11742 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11743 return true;
11744
11745 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11746 // Callable from the host only."
11747 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11748 // Callable from the host only."
11749 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11750 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11751 return true;
11752
11753 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11754 return true;
11755
11756 return false;
11757}