blob: 61d8dfce5fc8300f7aea775ce107da1536226474 [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
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001669 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001670 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001671 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001672
1673 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001674 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001675 Diag(Loc, diag::err_bad_variable_name)
1676 << Name;
1677 return 0;
1678 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001679
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001680 IdentifierInfo *II = Name.getAsIdentifierInfo();
1681
Douglas Gregorf2503652011-09-21 14:40:46 +00001682 // Member field could not be with "template" keyword.
1683 // So TemplateParameterLists should be empty in this case.
1684 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001685 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001686 if (TemplateParams->size()) {
1687 // There is no such thing as a member field template.
1688 Diag(D.getIdentifierLoc(), diag::err_template_member)
1689 << II
1690 << SourceRange(TemplateParams->getTemplateLoc(),
1691 TemplateParams->getRAngleLoc());
1692 } else {
1693 // There is an extraneous 'template<>' for this member.
1694 Diag(TemplateParams->getTemplateLoc(),
1695 diag::err_template_member_noparams)
1696 << II
1697 << SourceRange(TemplateParams->getTemplateLoc(),
1698 TemplateParams->getRAngleLoc());
1699 }
1700 return 0;
1701 }
1702
Douglas Gregor922fff22010-10-13 22:19:53 +00001703 if (SS.isSet() && !SS.isInvalid()) {
1704 // The user provided a superfluous scope specifier inside a class
1705 // definition:
1706 //
1707 // class X {
1708 // int X::member;
1709 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001710 if (DeclContext *DC = computeDeclContext(SS, false))
1711 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001712 else
1713 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1714 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001715
Douglas Gregor922fff22010-10-13 22:19:53 +00001716 SS.clear();
1717 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001718
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001719 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001720 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001721 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001722 } else {
Richard Smithca523302012-06-10 03:12:00 +00001723 assert(InitStyle == ICIS_NoInit);
Richard Smith7a614d82011-06-11 17:19:42 +00001724
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001725 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001726 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001727 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001728 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001729
1730 // Non-instance-fields can't have a bitfield.
1731 if (BitWidth) {
1732 if (Member->isInvalidDecl()) {
1733 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001734 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001735 // C++ 9.6p3: A bit-field shall not be a static member.
1736 // "static member 'A' cannot be a bit-field"
1737 Diag(Loc, diag::err_static_not_bitfield)
1738 << Name << BitWidth->getSourceRange();
1739 } else if (isa<TypedefDecl>(Member)) {
1740 // "typedef member 'x' cannot be a bit-field"
1741 Diag(Loc, diag::err_typedef_not_bitfield)
1742 << Name << BitWidth->getSourceRange();
1743 } else {
1744 // A function typedef ("typedef int f(); f a;").
1745 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1746 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001747 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001748 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001749 }
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Chris Lattner8b963ef2009-03-05 23:01:03 +00001751 BitWidth = 0;
1752 Member->setInvalidDecl();
1753 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001754
1755 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Douglas Gregor37b372b2009-08-20 22:52:58 +00001757 // If we have declared a member function template, set the access of the
1758 // templated declaration as well.
1759 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1760 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001761 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001762
Richard Smitha4b39652012-08-06 03:25:17 +00001763 if (VS.isOverrideSpecified())
1764 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1765 if (VS.isFinalSpecified())
1766 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001767
Douglas Gregorf5251602011-03-08 17:10:18 +00001768 if (VS.getLastLocation().isValid()) {
1769 // Update the end location of a method that has a virt-specifiers.
1770 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1771 MD->setRangeEnd(VS.getLastLocation());
1772 }
Richard Smitha4b39652012-08-06 03:25:17 +00001773
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001774 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001775
Douglas Gregor10bd3682008-11-17 22:58:34 +00001776 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001777
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001778 if (isInstField) {
1779 FieldDecl *FD = cast<FieldDecl>(Member);
1780 FieldCollector->Add(FD);
1781
1782 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1783 FD->getLocation())
1784 != DiagnosticsEngine::Ignored) {
1785 // Remember all explicit private FieldDecls that have a name, no side
1786 // effects and are not part of a dependent type declaration.
1787 if (!FD->isImplicit() && FD->getDeclName() &&
1788 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001789 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001790 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001791 !InitializationHasSideEffects(*FD))
1792 UnusedPrivateFields.insert(FD);
1793 }
1794 }
1795
John McCalld226f652010-08-21 09:40:31 +00001796 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001797}
1798
Hans Wennborg471f9852012-09-18 15:58:06 +00001799namespace {
1800 class UninitializedFieldVisitor
1801 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1802 Sema &S;
1803 ValueDecl *VD;
1804 public:
1805 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1806 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001807 S(S) {
1808 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1809 this->VD = IFD->getAnonField();
1810 else
1811 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001812 }
1813
1814 void HandleExpr(Expr *E) {
1815 if (!E) return;
1816
1817 // Expressions like x(x) sometimes lack the surrounding expressions
1818 // but need to be checked anyways.
1819 HandleValue(E);
1820 Visit(E);
1821 }
1822
1823 void HandleValue(Expr *E) {
1824 E = E->IgnoreParens();
1825
1826 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1827 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001828 return;
1829
1830 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1831 // or union.
1832 MemberExpr *FieldME = ME;
1833
Hans Wennborg471f9852012-09-18 15:58:06 +00001834 Expr *Base = E;
1835 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001836 ME = cast<MemberExpr>(Base);
1837
1838 if (isa<VarDecl>(ME->getMemberDecl()))
1839 return;
1840
1841 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1842 if (!FD->isAnonymousStructOrUnion())
1843 FieldME = ME;
1844
Hans Wennborg471f9852012-09-18 15:58:06 +00001845 Base = ME->getBase();
1846 }
1847
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001848 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00001849 unsigned diag = VD->getType()->isReferenceType()
1850 ? diag::warn_reference_field_is_uninit
1851 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001852 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001853 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001854 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00001855 }
1856
1857 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1858 HandleValue(CO->getTrueExpr());
1859 HandleValue(CO->getFalseExpr());
1860 return;
1861 }
1862
1863 if (BinaryConditionalOperator *BCO =
1864 dyn_cast<BinaryConditionalOperator>(E)) {
1865 HandleValue(BCO->getCommon());
1866 HandleValue(BCO->getFalseExpr());
1867 return;
1868 }
1869
1870 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1871 switch (BO->getOpcode()) {
1872 default:
1873 return;
1874 case(BO_PtrMemD):
1875 case(BO_PtrMemI):
1876 HandleValue(BO->getLHS());
1877 return;
1878 case(BO_Comma):
1879 HandleValue(BO->getRHS());
1880 return;
1881 }
1882 }
1883 }
1884
1885 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1886 if (E->getCastKind() == CK_LValueToRValue)
1887 HandleValue(E->getSubExpr());
1888
1889 Inherited::VisitImplicitCastExpr(E);
1890 }
1891
1892 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1893 Expr *Callee = E->getCallee();
1894 if (isa<MemberExpr>(Callee))
1895 HandleValue(Callee);
1896
1897 Inherited::VisitCXXMemberCallExpr(E);
1898 }
1899 };
1900 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1901 ValueDecl *VD) {
1902 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1903 }
1904} // namespace
1905
Richard Smith7a614d82011-06-11 17:19:42 +00001906/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001907/// in-class initializer for a non-static C++ class member, and after
1908/// instantiating an in-class initializer in a class template. Such actions
1909/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001910void
Richard Smithca523302012-06-10 03:12:00 +00001911Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001912 Expr *InitExpr) {
1913 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001914 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1915 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001916
1917 if (!InitExpr) {
1918 FD->setInvalidDecl();
1919 FD->removeInClassInitializer();
1920 return;
1921 }
1922
Peter Collingbournefef21892011-10-23 18:59:44 +00001923 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1924 FD->setInvalidDecl();
1925 FD->removeInClassInitializer();
1926 return;
1927 }
1928
Hans Wennborg471f9852012-09-18 15:58:06 +00001929 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1930 != DiagnosticsEngine::Ignored) {
1931 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1932 }
1933
Richard Smith7a614d82011-06-11 17:19:42 +00001934 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00001935 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001936 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001937 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001938 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1939 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001940 Expr **Inits = &InitExpr;
1941 unsigned NumInits = 1;
1942 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00001943 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00001944 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00001945 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00001946 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1947 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001948 if (Init.isInvalid()) {
1949 FD->setInvalidDecl();
1950 return;
1951 }
Richard Smith7a614d82011-06-11 17:19:42 +00001952 }
1953
Richard Smith41956372013-01-14 22:39:08 +00001954 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00001955 // The initialization of each base and member constitutes a
1956 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00001957 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00001958 if (Init.isInvalid()) {
1959 FD->setInvalidDecl();
1960 return;
1961 }
1962
1963 InitExpr = Init.release();
1964
1965 FD->setInClassInitializer(InitExpr);
1966}
1967
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001968/// \brief Find the direct and/or virtual base specifiers that
1969/// correspond to the given base type, for use in base initialization
1970/// within a constructor.
1971static bool FindBaseInitializer(Sema &SemaRef,
1972 CXXRecordDecl *ClassDecl,
1973 QualType BaseType,
1974 const CXXBaseSpecifier *&DirectBaseSpec,
1975 const CXXBaseSpecifier *&VirtualBaseSpec) {
1976 // First, check for a direct base class.
1977 DirectBaseSpec = 0;
1978 for (CXXRecordDecl::base_class_const_iterator Base
1979 = ClassDecl->bases_begin();
1980 Base != ClassDecl->bases_end(); ++Base) {
1981 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1982 // We found a direct base of this type. That's what we're
1983 // initializing.
1984 DirectBaseSpec = &*Base;
1985 break;
1986 }
1987 }
1988
1989 // Check for a virtual base class.
1990 // FIXME: We might be able to short-circuit this if we know in advance that
1991 // there are no virtual bases.
1992 VirtualBaseSpec = 0;
1993 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1994 // We haven't found a base yet; search the class hierarchy for a
1995 // virtual base class.
1996 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1997 /*DetectVirtual=*/false);
1998 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1999 BaseType, Paths)) {
2000 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2001 Path != Paths.end(); ++Path) {
2002 if (Path->back().Base->isVirtual()) {
2003 VirtualBaseSpec = Path->back().Base;
2004 break;
2005 }
2006 }
2007 }
2008 }
2009
2010 return DirectBaseSpec || VirtualBaseSpec;
2011}
2012
Sebastian Redl6df65482011-09-24 17:48:25 +00002013/// \brief Handle a C++ member initializer using braced-init-list syntax.
2014MemInitResult
2015Sema::ActOnMemInitializer(Decl *ConstructorD,
2016 Scope *S,
2017 CXXScopeSpec &SS,
2018 IdentifierInfo *MemberOrBase,
2019 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002020 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002021 SourceLocation IdLoc,
2022 Expr *InitList,
2023 SourceLocation EllipsisLoc) {
2024 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002025 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002026 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002027}
2028
2029/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002030MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002031Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002032 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002033 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002034 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002035 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002036 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002037 SourceLocation IdLoc,
2038 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002039 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002040 SourceLocation RParenLoc,
2041 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002042 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2043 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002044 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002045 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002046 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002047}
2048
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002049namespace {
2050
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002051// Callback to only accept typo corrections that can be a valid C++ member
2052// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002053class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2054 public:
2055 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2056 : ClassDecl(ClassDecl) {}
2057
2058 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2059 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2060 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2061 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2062 else
2063 return isa<TypeDecl>(ND);
2064 }
2065 return false;
2066 }
2067
2068 private:
2069 CXXRecordDecl *ClassDecl;
2070};
2071
2072}
2073
Sebastian Redl6df65482011-09-24 17:48:25 +00002074/// \brief Handle a C++ member initializer.
2075MemInitResult
2076Sema::BuildMemInitializer(Decl *ConstructorD,
2077 Scope *S,
2078 CXXScopeSpec &SS,
2079 IdentifierInfo *MemberOrBase,
2080 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002081 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002082 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002083 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002084 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002085 if (!ConstructorD)
2086 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002088 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002089
2090 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002091 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002092 if (!Constructor) {
2093 // The user wrote a constructor initializer on a function that is
2094 // not a C++ constructor. Ignore the error for now, because we may
2095 // have more member initializers coming; we'll diagnose it just
2096 // once in ActOnMemInitializers.
2097 return true;
2098 }
2099
2100 CXXRecordDecl *ClassDecl = Constructor->getParent();
2101
2102 // C++ [class.base.init]p2:
2103 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002104 // constructor's class and, if not found in that scope, are looked
2105 // up in the scope containing the constructor's definition.
2106 // [Note: if the constructor's class contains a member with the
2107 // same name as a direct or virtual base class of the class, a
2108 // mem-initializer-id naming the member or base class and composed
2109 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002110 // mem-initializer-id for the hidden base class may be specified
2111 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002112 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002113 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002114 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002115 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002116 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002117 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002118 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2119 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002120 if (EllipsisLoc.isValid())
2121 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002122 << MemberOrBase
2123 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002124
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002125 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002126 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002127 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002128 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002129 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002130 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002131 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002132
2133 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002134 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002135 } else if (DS.getTypeSpecType() == TST_decltype) {
2136 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002137 } else {
2138 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2139 LookupParsedName(R, S, &SS);
2140
2141 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2142 if (!TyD) {
2143 if (R.isAmbiguous()) return true;
2144
John McCallfd225442010-04-09 19:01:14 +00002145 // We don't want access-control diagnostics here.
2146 R.suppressDiagnostics();
2147
Douglas Gregor7a886e12010-01-19 06:46:48 +00002148 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2149 bool NotUnknownSpecialization = false;
2150 DeclContext *DC = computeDeclContext(SS, false);
2151 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2152 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2153
2154 if (!NotUnknownSpecialization) {
2155 // When the scope specifier can refer to a member of an unknown
2156 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002157 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2158 SS.getWithLocInContext(Context),
2159 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002160 if (BaseType.isNull())
2161 return true;
2162
Douglas Gregor7a886e12010-01-19 06:46:48 +00002163 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002164 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002165 }
2166 }
2167
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002168 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002169 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002170 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002171 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002172 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002173 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002174 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2175 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002176 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002177 // We have found a non-static data member with a similar
2178 // name to what was typed; complain and initialize that
2179 // member.
2180 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2181 << MemberOrBase << true << CorrectedQuotedStr
2182 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2183 Diag(Member->getLocation(), diag::note_previous_decl)
2184 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002185
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002186 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002187 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002188 const CXXBaseSpecifier *DirectBaseSpec;
2189 const CXXBaseSpecifier *VirtualBaseSpec;
2190 if (FindBaseInitializer(*this, ClassDecl,
2191 Context.getTypeDeclType(Type),
2192 DirectBaseSpec, VirtualBaseSpec)) {
2193 // We have found a direct or virtual base class with a
2194 // similar name to what was typed; complain and initialize
2195 // that base class.
2196 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002197 << MemberOrBase << false << CorrectedQuotedStr
2198 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002199
2200 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2201 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002202 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002203 diag::note_base_class_specified_here)
2204 << BaseSpec->getType()
2205 << BaseSpec->getSourceRange();
2206
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002207 TyD = Type;
2208 }
2209 }
2210 }
2211
Douglas Gregor7a886e12010-01-19 06:46:48 +00002212 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002213 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002214 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002215 return true;
2216 }
John McCall2b194412009-12-21 10:41:20 +00002217 }
2218
Douglas Gregor7a886e12010-01-19 06:46:48 +00002219 if (BaseType.isNull()) {
2220 BaseType = Context.getTypeDeclType(TyD);
2221 if (SS.isSet()) {
2222 NestedNameSpecifier *Qualifier =
2223 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002224
Douglas Gregor7a886e12010-01-19 06:46:48 +00002225 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002226 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002227 }
John McCall2b194412009-12-21 10:41:20 +00002228 }
2229 }
Mike Stump1eb44332009-09-09 15:08:12 +00002230
John McCalla93c9342009-12-07 02:54:59 +00002231 if (!TInfo)
2232 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002233
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002234 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002235}
2236
Chandler Carruth81c64772011-09-03 01:14:15 +00002237/// Checks a member initializer expression for cases where reference (or
2238/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002239static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2240 Expr *Init,
2241 SourceLocation IdLoc) {
2242 QualType MemberTy = Member->getType();
2243
2244 // We only handle pointers and references currently.
2245 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2246 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2247 return;
2248
2249 const bool IsPointer = MemberTy->isPointerType();
2250 if (IsPointer) {
2251 if (const UnaryOperator *Op
2252 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2253 // The only case we're worried about with pointers requires taking the
2254 // address.
2255 if (Op->getOpcode() != UO_AddrOf)
2256 return;
2257
2258 Init = Op->getSubExpr();
2259 } else {
2260 // We only handle address-of expression initializers for pointers.
2261 return;
2262 }
2263 }
2264
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002265 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2266 // Taking the address of a temporary will be diagnosed as a hard error.
2267 if (IsPointer)
2268 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002269
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002270 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2271 << Member << Init->getSourceRange();
2272 } else if (const DeclRefExpr *DRE
2273 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2274 // We only warn when referring to a non-reference parameter declaration.
2275 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2276 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002277 return;
2278
2279 S.Diag(Init->getExprLoc(),
2280 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2281 : diag::warn_bind_ref_member_to_parameter)
2282 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002283 } else {
2284 // Other initializers are fine.
2285 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002286 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002287
2288 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2289 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002290}
2291
John McCallf312b1e2010-08-26 23:41:50 +00002292MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002293Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002294 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002295 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2296 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2297 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002298 "Member must be a FieldDecl or IndirectFieldDecl");
2299
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002300 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002301 return true;
2302
Douglas Gregor464b2f02010-11-05 22:21:31 +00002303 if (Member->isInvalidDecl())
2304 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002305
John McCallb4190042009-11-04 23:02:40 +00002306 // Diagnose value-uses of fields to initialize themselves, e.g.
2307 // foo(foo)
2308 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002309 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002310 Expr **Args;
2311 unsigned NumArgs;
2312 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2313 Args = ParenList->getExprs();
2314 NumArgs = ParenList->getNumExprs();
Richard Smithc83c2302012-12-19 01:39:02 +00002315 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002316 Args = InitList->getInits();
2317 NumArgs = InitList->getNumInits();
Richard Smithc83c2302012-12-19 01:39:02 +00002318 } else {
2319 // Template instantiation doesn't reconstruct ParenListExprs for us.
2320 Args = &Init;
2321 NumArgs = 1;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002322 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002323
Richard Trieude5e75c2012-06-14 23:11:34 +00002324 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2325 != DiagnosticsEngine::Ignored)
2326 for (unsigned i = 0; i < NumArgs; ++i)
2327 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002328 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002329 // initializing the i'th field, throw a warning if any of the >= i'th
2330 // fields are used, as they are not yet initialized.
2331 // Right now we are only handling the case where the i'th field uses
2332 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002333 // Also need to take into account that some fields may be initialized by
2334 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002335 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002336
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002337 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002338
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002339 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002340 // Can't check initialization for a member of dependent type or when
2341 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002342 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002343 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002344 bool InitList = false;
2345 if (isa<InitListExpr>(Init)) {
2346 InitList = true;
2347 Args = &Init;
2348 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002349
2350 if (isStdInitializerList(Member->getType(), 0)) {
2351 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2352 << /*at end of ctor*/1 << InitRange;
2353 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002354 }
2355
Chandler Carruth894aed92010-12-06 09:23:57 +00002356 // Initialize the member.
2357 InitializedEntity MemberEntity =
2358 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2359 : InitializedEntity::InitializeMember(IndirectMember, 0);
2360 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002361 InitList ? InitializationKind::CreateDirectList(IdLoc)
2362 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2363 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002364
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002365 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2366 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002367 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002368 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002369 if (MemberInit.isInvalid())
2370 return true;
2371
Richard Smith41956372013-01-14 22:39:08 +00002372 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002373 // The initialization of each base and member constitutes a
2374 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002375 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002376 if (MemberInit.isInvalid())
2377 return true;
2378
Richard Smithc83c2302012-12-19 01:39:02 +00002379 Init = MemberInit.get();
2380 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002381 }
2382
Chandler Carruth894aed92010-12-06 09:23:57 +00002383 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002384 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2385 InitRange.getBegin(), Init,
2386 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002387 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002388 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2389 InitRange.getBegin(), Init,
2390 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002391 }
Eli Friedman59c04372009-07-29 19:44:27 +00002392}
2393
John McCallf312b1e2010-08-26 23:41:50 +00002394MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002395Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002396 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002397 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002398 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002399 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002400 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002401 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002402
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002403 bool InitList = true;
2404 Expr **Args = &Init;
2405 unsigned NumArgs = 1;
2406 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2407 InitList = false;
2408 Args = ParenList->getExprs();
2409 NumArgs = ParenList->getNumExprs();
2410 }
2411
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002412 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002413 // Initialize the object.
2414 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2415 QualType(ClassDecl->getTypeForDecl(), 0));
2416 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002417 InitList ? InitializationKind::CreateDirectList(NameLoc)
2418 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2419 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002420 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2421 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002422 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002423 0);
Sean Hunt41717662011-02-26 19:13:13 +00002424 if (DelegationInit.isInvalid())
2425 return true;
2426
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002427 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2428 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002429
Richard Smith41956372013-01-14 22:39:08 +00002430 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002431 // The initialization of each base and member constitutes a
2432 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002433 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2434 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002435 if (DelegationInit.isInvalid())
2436 return true;
2437
Eli Friedmand21016f2012-05-19 23:35:23 +00002438 // If we are in a dependent context, template instantiation will
2439 // perform this type-checking again. Just save the arguments that we
2440 // received in a ParenListExpr.
2441 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2442 // of the information that we have about the base
2443 // initializer. However, deconstructing the ASTs is a dicey process,
2444 // and this approach is far more likely to get the corner cases right.
2445 if (CurContext->isDependentContext())
2446 DelegationInit = Owned(Init);
2447
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002448 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002449 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002450 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002451}
2452
2453MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002454Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002455 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002456 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002457 SourceLocation BaseLoc
2458 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002459
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002460 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2461 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2462 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2463
2464 // C++ [class.base.init]p2:
2465 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002466 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002467 // of that class, the mem-initializer is ill-formed. A
2468 // mem-initializer-list can initialize a base class using any
2469 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002470 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002471
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002472 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002473 if (EllipsisLoc.isValid()) {
2474 // This is a pack expansion.
2475 if (!BaseType->containsUnexpandedParameterPack()) {
2476 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002477 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002478
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002479 EllipsisLoc = SourceLocation();
2480 }
2481 } else {
2482 // Check for any unexpanded parameter packs.
2483 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2484 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002485
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002486 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002487 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002488 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002489
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002490 // Check for direct and virtual base classes.
2491 const CXXBaseSpecifier *DirectBaseSpec = 0;
2492 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2493 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002494 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2495 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002496 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002497
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002498 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2499 VirtualBaseSpec);
2500
2501 // C++ [base.class.init]p2:
2502 // Unless the mem-initializer-id names a nonstatic data member of the
2503 // constructor's class or a direct or virtual base of that class, the
2504 // mem-initializer is ill-formed.
2505 if (!DirectBaseSpec && !VirtualBaseSpec) {
2506 // If the class has any dependent bases, then it's possible that
2507 // one of those types will resolve to the same type as
2508 // BaseType. Therefore, just treat this as a dependent base
2509 // class initialization. FIXME: Should we try to check the
2510 // initialization anyway? It seems odd.
2511 if (ClassDecl->hasAnyDependentBases())
2512 Dependent = true;
2513 else
2514 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2515 << BaseType << Context.getTypeDeclType(ClassDecl)
2516 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2517 }
2518 }
2519
2520 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002521 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002522
Sebastian Redl6df65482011-09-24 17:48:25 +00002523 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2524 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002525 InitRange.getBegin(), Init,
2526 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002527 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002528
2529 // C++ [base.class.init]p2:
2530 // If a mem-initializer-id is ambiguous because it designates both
2531 // a direct non-virtual base class and an inherited virtual base
2532 // class, the mem-initializer is ill-formed.
2533 if (DirectBaseSpec && VirtualBaseSpec)
2534 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002535 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002536
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002537 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002538 if (!BaseSpec)
2539 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2540
2541 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002542 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002543 Expr **Args = &Init;
2544 unsigned NumArgs = 1;
2545 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002546 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002547 Args = ParenList->getExprs();
2548 NumArgs = ParenList->getNumExprs();
2549 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002550
2551 InitializedEntity BaseEntity =
2552 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2553 InitializationKind Kind =
2554 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2555 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2556 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002557 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2558 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002559 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002560 if (BaseInit.isInvalid())
2561 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002562
Richard Smith41956372013-01-14 22:39:08 +00002563 // C++11 [class.base.init]p7:
2564 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002565 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002566 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002567 if (BaseInit.isInvalid())
2568 return true;
2569
2570 // If we are in a dependent context, template instantiation will
2571 // perform this type-checking again. Just save the arguments that we
2572 // received in a ParenListExpr.
2573 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2574 // of the information that we have about the base
2575 // initializer. However, deconstructing the ASTs is a dicey process,
2576 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002577 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002578 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002579
Sean Huntcbb67482011-01-08 20:30:50 +00002580 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002581 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002582 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002583 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002584 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002585}
2586
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002587// Create a static_cast\<T&&>(expr).
2588static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2589 QualType ExprType = E->getType();
2590 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2591 SourceLocation ExprLoc = E->getLocStart();
2592 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2593 TargetType, ExprLoc);
2594
2595 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2596 SourceRange(ExprLoc, ExprLoc),
2597 E->getSourceRange()).take();
2598}
2599
Anders Carlssone5ef7402010-04-23 03:10:23 +00002600/// ImplicitInitializerKind - How an implicit base or member initializer should
2601/// initialize its base or member.
2602enum ImplicitInitializerKind {
2603 IIK_Default,
2604 IIK_Copy,
2605 IIK_Move
2606};
2607
Anders Carlssondefefd22010-04-23 02:00:02 +00002608static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002609BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002610 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002611 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002612 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002613 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002614 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002615 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2616 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002617
John McCall60d7b3a2010-08-24 06:29:42 +00002618 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002619
2620 switch (ImplicitInitKind) {
2621 case IIK_Default: {
2622 InitializationKind InitKind
2623 = InitializationKind::CreateDefault(Constructor->getLocation());
2624 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002625 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002626 break;
2627 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002628
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002629 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002630 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002631 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002632 ParmVarDecl *Param = Constructor->getParamDecl(0);
2633 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002634
Anders Carlssone5ef7402010-04-23 03:10:23 +00002635 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002636 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002637 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002638 Constructor->getLocation(), ParamType,
2639 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002640
Eli Friedman5f2987c2012-02-02 03:46:19 +00002641 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2642
Anders Carlssonc7957502010-04-24 22:02:54 +00002643 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002644 QualType ArgTy =
2645 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2646 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002647
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002648 if (Moving) {
2649 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2650 }
2651
John McCallf871d0c2010-08-07 06:22:56 +00002652 CXXCastPath BasePath;
2653 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002654 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2655 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002656 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002657 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002658
Anders Carlssone5ef7402010-04-23 03:10:23 +00002659 InitializationKind InitKind
2660 = InitializationKind::CreateDirect(Constructor->getLocation(),
2661 SourceLocation(), SourceLocation());
2662 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2663 &CopyCtorArg, 1);
2664 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002665 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002666 break;
2667 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002668 }
John McCall9ae2f072010-08-23 23:25:46 +00002669
Douglas Gregor53c374f2010-12-07 00:41:46 +00002670 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002671 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002672 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002673
Anders Carlssondefefd22010-04-23 02:00:02 +00002674 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002675 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002676 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2677 SourceLocation()),
2678 BaseSpec->isVirtual(),
2679 SourceLocation(),
2680 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002681 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002682 SourceLocation());
2683
Anders Carlssondefefd22010-04-23 02:00:02 +00002684 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002685}
2686
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002687static bool RefersToRValueRef(Expr *MemRef) {
2688 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2689 return Referenced->getType()->isRValueReferenceType();
2690}
2691
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002692static bool
2693BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002694 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002695 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002696 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002697 if (Field->isInvalidDecl())
2698 return true;
2699
Chandler Carruthf186b542010-06-29 23:50:44 +00002700 SourceLocation Loc = Constructor->getLocation();
2701
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002702 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2703 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002704 ParmVarDecl *Param = Constructor->getParamDecl(0);
2705 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002706
2707 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002708 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2709 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002710
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002711 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002712 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002713 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002714 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002715
Eli Friedman5f2987c2012-02-02 03:46:19 +00002716 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2717
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002718 if (Moving) {
2719 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2720 }
2721
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002722 // Build a reference to this field within the parameter.
2723 CXXScopeSpec SS;
2724 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2725 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002726 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2727 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002728 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002729 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002730 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002731 ParamType, Loc,
2732 /*IsArrow=*/false,
2733 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002734 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002735 /*FirstQualifierInScope=*/0,
2736 MemberLookup,
2737 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002738 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002739 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002740
2741 // C++11 [class.copy]p15:
2742 // - if a member m has rvalue reference type T&&, it is direct-initialized
2743 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002744 if (RefersToRValueRef(CtorArg.get())) {
2745 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002746 }
2747
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002748 // When the field we are copying is an array, create index variables for
2749 // each dimension of the array. We use these index variables to subscript
2750 // the source array, and other clients (e.g., CodeGen) will perform the
2751 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002752 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002753 QualType BaseType = Field->getType();
2754 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002755 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002756 while (const ConstantArrayType *Array
2757 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002758 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002759 // Create the iteration variable for this array index.
2760 IdentifierInfo *IterationVarName = 0;
2761 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002762 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002763 llvm::raw_svector_ostream OS(Str);
2764 OS << "__i" << IndexVariables.size();
2765 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2766 }
2767 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002768 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002769 IterationVarName, SizeType,
2770 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002771 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002772 IndexVariables.push_back(IterationVar);
2773
2774 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002775 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002776 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002777 assert(!IterationVarRef.isInvalid() &&
2778 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002779 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2780 assert(!IterationVarRef.isInvalid() &&
2781 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002782
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002783 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002784 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002785 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002786 Loc);
2787 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002788 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002789
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002790 BaseType = Array->getElementType();
2791 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002792
2793 // The array subscript expression is an lvalue, which is wrong for moving.
2794 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002795 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002796
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002797 // Construct the entity that we will be initializing. For an array, this
2798 // will be first element in the array, which may require several levels
2799 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002800 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002801 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002802 if (Indirect)
2803 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2804 else
2805 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002806 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2807 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2808 0,
2809 Entities.back()));
2810
2811 // Direct-initialize to use the copy constructor.
2812 InitializationKind InitKind =
2813 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2814
Sebastian Redl74e611a2011-09-04 18:14:28 +00002815 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002816 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002817 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002818
John McCall60d7b3a2010-08-24 06:29:42 +00002819 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002820 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002821 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002822 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002823 if (MemberInit.isInvalid())
2824 return true;
2825
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002826 if (Indirect) {
2827 assert(IndexVariables.size() == 0 &&
2828 "Indirect field improperly initialized");
2829 CXXMemberInit
2830 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2831 Loc, Loc,
2832 MemberInit.takeAs<Expr>(),
2833 Loc);
2834 } else
2835 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2836 Loc, MemberInit.takeAs<Expr>(),
2837 Loc,
2838 IndexVariables.data(),
2839 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002840 return false;
2841 }
2842
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002843 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2844
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002845 QualType FieldBaseElementType =
2846 SemaRef.Context.getBaseElementType(Field->getType());
2847
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002848 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002849 InitializedEntity InitEntity
2850 = Indirect? InitializedEntity::InitializeMember(Indirect)
2851 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002852 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002853 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002854
2855 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002856 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002857 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002858
Douglas Gregor53c374f2010-12-07 00:41:46 +00002859 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002860 if (MemberInit.isInvalid())
2861 return true;
2862
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002863 if (Indirect)
2864 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2865 Indirect, Loc,
2866 Loc,
2867 MemberInit.get(),
2868 Loc);
2869 else
2870 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2871 Field, Loc, Loc,
2872 MemberInit.get(),
2873 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002874 return false;
2875 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002876
Sean Hunt1f2f3842011-05-17 00:19:05 +00002877 if (!Field->getParent()->isUnion()) {
2878 if (FieldBaseElementType->isReferenceType()) {
2879 SemaRef.Diag(Constructor->getLocation(),
2880 diag::err_uninitialized_member_in_ctor)
2881 << (int)Constructor->isImplicit()
2882 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2883 << 0 << Field->getDeclName();
2884 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2885 return true;
2886 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002887
Sean Hunt1f2f3842011-05-17 00:19:05 +00002888 if (FieldBaseElementType.isConstQualified()) {
2889 SemaRef.Diag(Constructor->getLocation(),
2890 diag::err_uninitialized_member_in_ctor)
2891 << (int)Constructor->isImplicit()
2892 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2893 << 1 << Field->getDeclName();
2894 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2895 return true;
2896 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002897 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002898
David Blaikie4e4d0842012-03-11 07:00:24 +00002899 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002900 FieldBaseElementType->isObjCRetainableType() &&
2901 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2902 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002903 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002904 // Default-initialize Objective-C pointers to NULL.
2905 CXXMemberInit
2906 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2907 Loc, Loc,
2908 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2909 Loc);
2910 return false;
2911 }
2912
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002913 // Nothing to initialize.
2914 CXXMemberInit = 0;
2915 return false;
2916}
John McCallf1860e52010-05-20 23:23:51 +00002917
2918namespace {
2919struct BaseAndFieldInfo {
2920 Sema &S;
2921 CXXConstructorDecl *Ctor;
2922 bool AnyErrorsInInits;
2923 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002924 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002925 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002926
2927 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2928 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002929 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2930 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002931 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002932 else if (Generated && Ctor->isMoveConstructor())
2933 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002934 else
2935 IIK = IIK_Default;
2936 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002937
2938 bool isImplicitCopyOrMove() const {
2939 switch (IIK) {
2940 case IIK_Copy:
2941 case IIK_Move:
2942 return true;
2943
2944 case IIK_Default:
2945 return false;
2946 }
David Blaikie30263482012-01-20 21:50:17 +00002947
2948 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002949 }
Richard Smith0b8220a2012-08-07 21:30:42 +00002950
2951 bool addFieldInitializer(CXXCtorInitializer *Init) {
2952 AllToInit.push_back(Init);
2953
2954 // Check whether this initializer makes the field "used".
2955 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2956 S.UnusedPrivateFields.remove(Init->getAnyMember());
2957
2958 return false;
2959 }
John McCallf1860e52010-05-20 23:23:51 +00002960};
2961}
2962
Richard Smitha4950662011-09-19 13:34:43 +00002963/// \brief Determine whether the given indirect field declaration is somewhere
2964/// within an anonymous union.
2965static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2966 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2967 CEnd = F->chain_end();
2968 C != CEnd; ++C)
2969 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2970 if (Record->isUnion())
2971 return true;
2972
2973 return false;
2974}
2975
Douglas Gregorddb21472011-11-02 23:04:16 +00002976/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2977/// array type.
2978static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2979 if (T->isIncompleteArrayType())
2980 return true;
2981
2982 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2983 if (!ArrayT->getSize())
2984 return true;
2985
2986 T = ArrayT->getElementType();
2987 }
2988
2989 return false;
2990}
2991
Richard Smith7a614d82011-06-11 17:19:42 +00002992static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002993 FieldDecl *Field,
2994 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002995
Chandler Carruthe861c602010-06-30 02:59:29 +00002996 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00002997 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
2998 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00002999
Richard Smith0b8220a2012-08-07 21:30:42 +00003000 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003001 // has a brace-or-equal-initializer, the entity is initialized as specified
3002 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003003 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003004 CXXCtorInitializer *Init;
3005 if (Indirect)
3006 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3007 SourceLocation(),
3008 SourceLocation(), 0,
3009 SourceLocation());
3010 else
3011 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3012 SourceLocation(),
3013 SourceLocation(), 0,
3014 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003015 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003016 }
3017
Richard Smithc115f632011-09-18 11:14:50 +00003018 // Don't build an implicit initializer for union members if none was
3019 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003020 if (Field->getParent()->isUnion() ||
3021 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003022 return false;
3023
Douglas Gregorddb21472011-11-02 23:04:16 +00003024 // Don't initialize incomplete or zero-length arrays.
3025 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3026 return false;
3027
John McCallf1860e52010-05-20 23:23:51 +00003028 // Don't try to build an implicit initializer if there were semantic
3029 // errors in any of the initializers (and therefore we might be
3030 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003031 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003032 return false;
3033
Sean Huntcbb67482011-01-08 20:30:50 +00003034 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003035 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3036 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003037 return true;
John McCallf1860e52010-05-20 23:23:51 +00003038
Richard Smith0b8220a2012-08-07 21:30:42 +00003039 if (!Init)
3040 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003041
Richard Smith0b8220a2012-08-07 21:30:42 +00003042 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003043}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003044
3045bool
3046Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3047 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003048 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003049 Constructor->setNumCtorInitializers(1);
3050 CXXCtorInitializer **initializer =
3051 new (Context) CXXCtorInitializer*[1];
3052 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3053 Constructor->setCtorInitializers(initializer);
3054
Sean Huntb76af9c2011-05-03 23:05:34 +00003055 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003056 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003057 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3058 }
3059
Sean Huntc1598702011-05-05 00:05:47 +00003060 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003061
Sean Hunt059ce0d2011-05-01 07:04:31 +00003062 return false;
3063}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003064
David Blaikie93c86172013-01-17 05:26:25 +00003065bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3066 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003067 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003068 // Just store the initializers as written, they will be checked during
3069 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003070 if (!Initializers.empty()) {
3071 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003072 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003073 new (Context) CXXCtorInitializer*[Initializers.size()];
3074 memcpy(baseOrMemberInitializers, Initializers.data(),
3075 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003076 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003077 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003078
3079 // Let template instantiation know whether we had errors.
3080 if (AnyErrors)
3081 Constructor->setInvalidDecl();
3082
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003083 return false;
3084 }
3085
John McCallf1860e52010-05-20 23:23:51 +00003086 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003087
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003088 // We need to build the initializer AST according to order of construction
3089 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003090 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003091 if (!ClassDecl)
3092 return true;
3093
Eli Friedman80c30da2009-11-09 19:20:36 +00003094 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003095
David Blaikie93c86172013-01-17 05:26:25 +00003096 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003097 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003098
3099 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003100 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003101 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003102 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003103 }
3104
Anders Carlsson711f34a2010-04-21 19:52:01 +00003105 // Keep track of the direct virtual bases.
3106 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3107 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3108 E = ClassDecl->bases_end(); I != E; ++I) {
3109 if (I->isVirtual())
3110 DirectVBases.insert(I);
3111 }
3112
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003113 // Push virtual bases before others.
3114 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3115 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3116
Sean Huntcbb67482011-01-08 20:30:50 +00003117 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003118 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3119 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003120 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003121 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003122 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003123 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003124 VBase, IsInheritedVirtualBase,
3125 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003126 HadError = true;
3127 continue;
3128 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003129
John McCallf1860e52010-05-20 23:23:51 +00003130 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003131 }
3132 }
Mike Stump1eb44332009-09-09 15:08:12 +00003133
John McCallf1860e52010-05-20 23:23:51 +00003134 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003135 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3136 E = ClassDecl->bases_end(); Base != E; ++Base) {
3137 // Virtuals are in the virtual base list and already constructed.
3138 if (Base->isVirtual())
3139 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003140
Sean Huntcbb67482011-01-08 20:30:50 +00003141 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003142 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3143 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003144 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003145 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003146 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003147 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003148 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003149 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003150 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003151 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003152
John McCallf1860e52010-05-20 23:23:51 +00003153 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003154 }
3155 }
Mike Stump1eb44332009-09-09 15:08:12 +00003156
John McCallf1860e52010-05-20 23:23:51 +00003157 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003158 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3159 MemEnd = ClassDecl->decls_end();
3160 Mem != MemEnd; ++Mem) {
3161 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003162 // C++ [class.bit]p2:
3163 // A declaration for a bit-field that omits the identifier declares an
3164 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3165 // initialized.
3166 if (F->isUnnamedBitfield())
3167 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003168
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003169 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003170 // handle anonymous struct/union fields based on their individual
3171 // indirect fields.
3172 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3173 continue;
3174
3175 if (CollectFieldInitializer(*this, Info, F))
3176 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003177 continue;
3178 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003179
3180 // Beyond this point, we only consider default initialization.
3181 if (Info.IIK != IIK_Default)
3182 continue;
3183
3184 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3185 if (F->getType()->isIncompleteArrayType()) {
3186 assert(ClassDecl->hasFlexibleArrayMember() &&
3187 "Incomplete array type is not valid");
3188 continue;
3189 }
3190
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003191 // Initialize each field of an anonymous struct individually.
3192 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3193 HadError = true;
3194
3195 continue;
3196 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003197 }
Mike Stump1eb44332009-09-09 15:08:12 +00003198
David Blaikie93c86172013-01-17 05:26:25 +00003199 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003200 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003201 Constructor->setNumCtorInitializers(NumInitializers);
3202 CXXCtorInitializer **baseOrMemberInitializers =
3203 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003204 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003205 NumInitializers * sizeof(CXXCtorInitializer*));
3206 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003207
John McCallef027fe2010-03-16 21:39:52 +00003208 // Constructors implicitly reference the base and member
3209 // destructors.
3210 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3211 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003212 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003213
3214 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003215}
3216
David Blaikieee000bb2013-01-17 08:49:22 +00003217static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003218 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003219 const RecordDecl *RD = RT->getDecl();
3220 if (RD->isAnonymousStructOrUnion()) {
3221 for (RecordDecl::field_iterator Field = RD->field_begin(),
3222 E = RD->field_end(); Field != E; ++Field)
3223 PopulateKeysForFields(*Field, IdealInits);
3224 return;
3225 }
Eli Friedman6347f422009-07-21 19:28:10 +00003226 }
David Blaikieee000bb2013-01-17 08:49:22 +00003227 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003228}
3229
Anders Carlssonea356fb2010-04-02 05:42:15 +00003230static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003231 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003232}
3233
Anders Carlssonea356fb2010-04-02 05:42:15 +00003234static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003235 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003236 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003237 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003238
David Blaikieee000bb2013-01-17 08:49:22 +00003239 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003240}
3241
David Blaikie93c86172013-01-17 05:26:25 +00003242static void DiagnoseBaseOrMemInitializerOrder(
3243 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3244 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003245 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003246 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003247
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003248 // Don't check initializers order unless the warning is enabled at the
3249 // location of at least one initializer.
3250 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003251 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003252 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003253 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3254 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003255 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003256 ShouldCheckOrder = true;
3257 break;
3258 }
3259 }
3260 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003261 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003262
John McCalld6ca8da2010-04-10 07:37:23 +00003263 // Build the list of bases and members in the order that they'll
3264 // actually be initialized. The explicit initializers should be in
3265 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003266 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003267
Anders Carlsson071d6102010-04-02 03:38:04 +00003268 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3269
John McCalld6ca8da2010-04-10 07:37:23 +00003270 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003271 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003272 ClassDecl->vbases_begin(),
3273 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003274 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003275
John McCalld6ca8da2010-04-10 07:37:23 +00003276 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003277 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003278 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003279 if (Base->isVirtual())
3280 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003281 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003282 }
Mike Stump1eb44332009-09-09 15:08:12 +00003283
John McCalld6ca8da2010-04-10 07:37:23 +00003284 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003285 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003286 E = ClassDecl->field_end(); Field != E; ++Field) {
3287 if (Field->isUnnamedBitfield())
3288 continue;
3289
David Blaikieee000bb2013-01-17 08:49:22 +00003290 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003291 }
3292
John McCalld6ca8da2010-04-10 07:37:23 +00003293 unsigned NumIdealInits = IdealInitKeys.size();
3294 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003295
Sean Huntcbb67482011-01-08 20:30:50 +00003296 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003297 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003298 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003299 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003300
3301 // Scan forward to try to find this initializer in the idealized
3302 // initializers list.
3303 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3304 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003305 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003306
3307 // If we didn't find this initializer, it must be because we
3308 // scanned past it on a previous iteration. That can only
3309 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003310 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003311 Sema::SemaDiagnosticBuilder D =
3312 SemaRef.Diag(PrevInit->getSourceLocation(),
3313 diag::warn_initializer_out_of_order);
3314
Francois Pichet00eb3f92010-12-04 09:14:42 +00003315 if (PrevInit->isAnyMemberInitializer())
3316 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003317 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003318 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003319
Francois Pichet00eb3f92010-12-04 09:14:42 +00003320 if (Init->isAnyMemberInitializer())
3321 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003322 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003323 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003324
3325 // Move back to the initializer's location in the ideal list.
3326 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3327 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003328 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003329
3330 assert(IdealIndex != NumIdealInits &&
3331 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003332 }
John McCalld6ca8da2010-04-10 07:37:23 +00003333
3334 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003335 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003336}
3337
John McCall3c3ccdb2010-04-10 09:28:51 +00003338namespace {
3339bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003340 CXXCtorInitializer *Init,
3341 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003342 if (!PrevInit) {
3343 PrevInit = Init;
3344 return false;
3345 }
3346
3347 if (FieldDecl *Field = Init->getMember())
3348 S.Diag(Init->getSourceLocation(),
3349 diag::err_multiple_mem_initialization)
3350 << Field->getDeclName()
3351 << Init->getSourceRange();
3352 else {
John McCallf4c73712011-01-19 06:33:43 +00003353 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003354 assert(BaseClass && "neither field nor base");
3355 S.Diag(Init->getSourceLocation(),
3356 diag::err_multiple_base_initialization)
3357 << QualType(BaseClass, 0)
3358 << Init->getSourceRange();
3359 }
3360 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3361 << 0 << PrevInit->getSourceRange();
3362
3363 return true;
3364}
3365
Sean Huntcbb67482011-01-08 20:30:50 +00003366typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003367typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3368
3369bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003370 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003371 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003372 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003373 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003374 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003375
3376 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003377 if (Parent->isUnion()) {
3378 UnionEntry &En = Unions[Parent];
3379 if (En.first && En.first != Child) {
3380 S.Diag(Init->getSourceLocation(),
3381 diag::err_multiple_mem_union_initialization)
3382 << Field->getDeclName()
3383 << Init->getSourceRange();
3384 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3385 << 0 << En.second->getSourceRange();
3386 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003387 }
3388 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003389 En.first = Child;
3390 En.second = Init;
3391 }
David Blaikie6fe29652011-11-17 06:01:57 +00003392 if (!Parent->isAnonymousStructOrUnion())
3393 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003394 }
3395
3396 Child = Parent;
3397 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003398 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003399
3400 return false;
3401}
3402}
3403
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003404/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003405void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003406 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003407 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003408 bool AnyErrors) {
3409 if (!ConstructorDecl)
3410 return;
3411
3412 AdjustDeclIfTemplate(ConstructorDecl);
3413
3414 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003415 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003416
3417 if (!Constructor) {
3418 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3419 return;
3420 }
3421
John McCall3c3ccdb2010-04-10 09:28:51 +00003422 // Mapping for the duplicate initializers check.
3423 // For member initializers, this is keyed with a FieldDecl*.
3424 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003425 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003426
3427 // Mapping for the inconsistent anonymous-union initializers check.
3428 RedundantUnionMap MemberUnions;
3429
Anders Carlssonea356fb2010-04-02 05:42:15 +00003430 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003431 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003432 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003433
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003434 // Set the source order index.
3435 Init->setSourceOrder(i);
3436
Francois Pichet00eb3f92010-12-04 09:14:42 +00003437 if (Init->isAnyMemberInitializer()) {
3438 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003439 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3440 CheckRedundantUnionInit(*this, Init, MemberUnions))
3441 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003442 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003443 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3444 if (CheckRedundantInit(*this, Init, Members[Key]))
3445 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003446 } else {
3447 assert(Init->isDelegatingInitializer());
3448 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003449 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003450 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003451 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003452 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003453 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003454 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003455 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003456 // Return immediately as the initializer is set.
3457 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003458 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003459 }
3460
Anders Carlssonea356fb2010-04-02 05:42:15 +00003461 if (HadError)
3462 return;
3463
David Blaikie93c86172013-01-17 05:26:25 +00003464 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003465
David Blaikie93c86172013-01-17 05:26:25 +00003466 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003467}
3468
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003469void
John McCallef027fe2010-03-16 21:39:52 +00003470Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3471 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003472 // Ignore dependent contexts. Also ignore unions, since their members never
3473 // have destructors implicitly called.
3474 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003475 return;
John McCall58e6f342010-03-16 05:22:47 +00003476
3477 // FIXME: all the access-control diagnostics are positioned on the
3478 // field/base declaration. That's probably good; that said, the
3479 // user might reasonably want to know why the destructor is being
3480 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003481
Anders Carlsson9f853df2009-11-17 04:44:12 +00003482 // Non-static data members.
3483 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3484 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003485 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003486 if (Field->isInvalidDecl())
3487 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003488
3489 // Don't destroy incomplete or zero-length arrays.
3490 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3491 continue;
3492
Anders Carlsson9f853df2009-11-17 04:44:12 +00003493 QualType FieldType = Context.getBaseElementType(Field->getType());
3494
3495 const RecordType* RT = FieldType->getAs<RecordType>();
3496 if (!RT)
3497 continue;
3498
3499 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003500 if (FieldClassDecl->isInvalidDecl())
3501 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003502 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003503 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003504 // The destructor for an implicit anonymous union member is never invoked.
3505 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3506 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003507
Douglas Gregordb89f282010-07-01 22:47:18 +00003508 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003509 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003510 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003511 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003512 << Field->getDeclName()
3513 << FieldType);
3514
Eli Friedman5f2987c2012-02-02 03:46:19 +00003515 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003516 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003517 }
3518
John McCall58e6f342010-03-16 05:22:47 +00003519 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3520
Anders Carlsson9f853df2009-11-17 04:44:12 +00003521 // Bases.
3522 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3523 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003524 // Bases are always records in a well-formed non-dependent class.
3525 const RecordType *RT = Base->getType()->getAs<RecordType>();
3526
3527 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003528 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003529 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003530
John McCall58e6f342010-03-16 05:22:47 +00003531 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003532 // If our base class is invalid, we probably can't get its dtor anyway.
3533 if (BaseClassDecl->isInvalidDecl())
3534 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003535 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003536 continue;
John McCall58e6f342010-03-16 05:22:47 +00003537
Douglas Gregordb89f282010-07-01 22:47:18 +00003538 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003539 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003540
3541 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003542 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003543 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003544 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003545 << Base->getSourceRange(),
3546 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003547
Eli Friedman5f2987c2012-02-02 03:46:19 +00003548 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003549 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003550 }
3551
3552 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003553 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3554 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003555
3556 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003557 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003558
3559 // Ignore direct virtual bases.
3560 if (DirectVirtualBases.count(RT))
3561 continue;
3562
John McCall58e6f342010-03-16 05:22:47 +00003563 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003564 // If our base class is invalid, we probably can't get its dtor anyway.
3565 if (BaseClassDecl->isInvalidDecl())
3566 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003567 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003568 continue;
John McCall58e6f342010-03-16 05:22:47 +00003569
Douglas Gregordb89f282010-07-01 22:47:18 +00003570 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003571 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003572 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003573 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003574 << VBase->getType(),
3575 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +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);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003579 }
3580}
3581
John McCalld226f652010-08-21 09:40:31 +00003582void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003583 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003584 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003585
Mike Stump1eb44332009-09-09 15:08:12 +00003586 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003587 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003588 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003589}
3590
Mike Stump1eb44332009-09-09 15:08:12 +00003591bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003592 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003593 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3594 unsigned DiagID;
3595 AbstractDiagSelID SelID;
3596
3597 public:
3598 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3599 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3600
3601 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003602 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003603 if (SelID == -1)
3604 S.Diag(Loc, DiagID) << T;
3605 else
3606 S.Diag(Loc, DiagID) << SelID << T;
3607 }
3608 } Diagnoser(DiagID, SelID);
3609
3610 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003611}
3612
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003613bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003614 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003615 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003616 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003617
Anders Carlsson11f21a02009-03-23 19:10:31 +00003618 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003619 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003620
Ted Kremenek6217b802009-07-29 21:53:49 +00003621 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003622 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003623 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003624 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003625
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003626 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003627 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003628 }
Mike Stump1eb44332009-09-09 15:08:12 +00003629
Ted Kremenek6217b802009-07-29 21:53:49 +00003630 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003631 if (!RT)
3632 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003633
John McCall86ff3082010-02-04 22:26:26 +00003634 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003635
John McCall94c3b562010-08-18 09:41:07 +00003636 // We can't answer whether something is abstract until it has a
3637 // definition. If it's currently being defined, we'll walk back
3638 // over all the declarations when we have a full definition.
3639 const CXXRecordDecl *Def = RD->getDefinition();
3640 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003641 return false;
3642
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003643 if (!RD->isAbstract())
3644 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003645
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003646 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003647 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003648
John McCall94c3b562010-08-18 09:41:07 +00003649 return true;
3650}
3651
3652void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3653 // Check if we've already emitted the list of pure virtual functions
3654 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003655 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003656 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003657
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003658 CXXFinalOverriderMap FinalOverriders;
3659 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003660
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003661 // Keep a set of seen pure methods so we won't diagnose the same method
3662 // more than once.
3663 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3664
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003665 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3666 MEnd = FinalOverriders.end();
3667 M != MEnd;
3668 ++M) {
3669 for (OverridingMethods::iterator SO = M->second.begin(),
3670 SOEnd = M->second.end();
3671 SO != SOEnd; ++SO) {
3672 // C++ [class.abstract]p4:
3673 // A class is abstract if it contains or inherits at least one
3674 // pure virtual function for which the final overrider is pure
3675 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003676
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003677 //
3678 if (SO->second.size() != 1)
3679 continue;
3680
3681 if (!SO->second.front().Method->isPure())
3682 continue;
3683
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003684 if (!SeenPureMethods.insert(SO->second.front().Method))
3685 continue;
3686
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003687 Diag(SO->second.front().Method->getLocation(),
3688 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003689 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003690 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003691 }
3692
3693 if (!PureVirtualClassDiagSet)
3694 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3695 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003696}
3697
Anders Carlsson8211eff2009-03-24 01:19:16 +00003698namespace {
John McCall94c3b562010-08-18 09:41:07 +00003699struct AbstractUsageInfo {
3700 Sema &S;
3701 CXXRecordDecl *Record;
3702 CanQualType AbstractType;
3703 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003704
John McCall94c3b562010-08-18 09:41:07 +00003705 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3706 : S(S), Record(Record),
3707 AbstractType(S.Context.getCanonicalType(
3708 S.Context.getTypeDeclType(Record))),
3709 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003710
John McCall94c3b562010-08-18 09:41:07 +00003711 void DiagnoseAbstractType() {
3712 if (Invalid) return;
3713 S.DiagnoseAbstractType(Record);
3714 Invalid = true;
3715 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003716
John McCall94c3b562010-08-18 09:41:07 +00003717 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3718};
3719
3720struct CheckAbstractUsage {
3721 AbstractUsageInfo &Info;
3722 const NamedDecl *Ctx;
3723
3724 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3725 : Info(Info), Ctx(Ctx) {}
3726
3727 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3728 switch (TL.getTypeLocClass()) {
3729#define ABSTRACT_TYPELOC(CLASS, PARENT)
3730#define TYPELOC(CLASS, PARENT) \
3731 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3732#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003733 }
John McCall94c3b562010-08-18 09:41:07 +00003734 }
Mike Stump1eb44332009-09-09 15:08:12 +00003735
John McCall94c3b562010-08-18 09:41:07 +00003736 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3737 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3738 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003739 if (!TL.getArg(I))
3740 continue;
3741
John McCall94c3b562010-08-18 09:41:07 +00003742 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3743 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003744 }
John McCall94c3b562010-08-18 09:41:07 +00003745 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003746
John McCall94c3b562010-08-18 09:41:07 +00003747 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3748 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3749 }
Mike Stump1eb44332009-09-09 15:08:12 +00003750
John McCall94c3b562010-08-18 09:41:07 +00003751 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3752 // Visit the type parameters from a permissive context.
3753 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3754 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3755 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3756 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3757 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3758 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003759 }
John McCall94c3b562010-08-18 09:41:07 +00003760 }
Mike Stump1eb44332009-09-09 15:08:12 +00003761
John McCall94c3b562010-08-18 09:41:07 +00003762 // Visit pointee types from a permissive context.
3763#define CheckPolymorphic(Type) \
3764 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3765 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3766 }
3767 CheckPolymorphic(PointerTypeLoc)
3768 CheckPolymorphic(ReferenceTypeLoc)
3769 CheckPolymorphic(MemberPointerTypeLoc)
3770 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003771 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003772
John McCall94c3b562010-08-18 09:41:07 +00003773 /// Handle all the types we haven't given a more specific
3774 /// implementation for above.
3775 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3776 // Every other kind of type that we haven't called out already
3777 // that has an inner type is either (1) sugar or (2) contains that
3778 // inner type in some way as a subobject.
3779 if (TypeLoc Next = TL.getNextTypeLoc())
3780 return Visit(Next, Sel);
3781
3782 // If there's no inner type and we're in a permissive context,
3783 // don't diagnose.
3784 if (Sel == Sema::AbstractNone) return;
3785
3786 // Check whether the type matches the abstract type.
3787 QualType T = TL.getType();
3788 if (T->isArrayType()) {
3789 Sel = Sema::AbstractArrayType;
3790 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003791 }
John McCall94c3b562010-08-18 09:41:07 +00003792 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3793 if (CT != Info.AbstractType) return;
3794
3795 // It matched; do some magic.
3796 if (Sel == Sema::AbstractArrayType) {
3797 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3798 << T << TL.getSourceRange();
3799 } else {
3800 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3801 << Sel << T << TL.getSourceRange();
3802 }
3803 Info.DiagnoseAbstractType();
3804 }
3805};
3806
3807void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3808 Sema::AbstractDiagSelID Sel) {
3809 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3810}
3811
3812}
3813
3814/// Check for invalid uses of an abstract type in a method declaration.
3815static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3816 CXXMethodDecl *MD) {
3817 // No need to do the check on definitions, which require that
3818 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003819 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003820 return;
3821
3822 // For safety's sake, just ignore it if we don't have type source
3823 // information. This should never happen for non-implicit methods,
3824 // but...
3825 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3826 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3827}
3828
3829/// Check for invalid uses of an abstract type within a class definition.
3830static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3831 CXXRecordDecl *RD) {
3832 for (CXXRecordDecl::decl_iterator
3833 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3834 Decl *D = *I;
3835 if (D->isImplicit()) continue;
3836
3837 // Methods and method templates.
3838 if (isa<CXXMethodDecl>(D)) {
3839 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3840 } else if (isa<FunctionTemplateDecl>(D)) {
3841 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3842 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3843
3844 // Fields and static variables.
3845 } else if (isa<FieldDecl>(D)) {
3846 FieldDecl *FD = cast<FieldDecl>(D);
3847 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3848 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3849 } else if (isa<VarDecl>(D)) {
3850 VarDecl *VD = cast<VarDecl>(D);
3851 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3852 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3853
3854 // Nested classes and class templates.
3855 } else if (isa<CXXRecordDecl>(D)) {
3856 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3857 } else if (isa<ClassTemplateDecl>(D)) {
3858 CheckAbstractClassUsage(Info,
3859 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3860 }
3861 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003862}
3863
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003864/// \brief Perform semantic checks on a class definition that has been
3865/// completing, introducing implicitly-declared members, checking for
3866/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003867void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003868 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003869 return;
3870
John McCall94c3b562010-08-18 09:41:07 +00003871 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3872 AbstractUsageInfo Info(*this, Record);
3873 CheckAbstractClassUsage(Info, Record);
3874 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003875
3876 // If this is not an aggregate type and has no user-declared constructor,
3877 // complain about any non-static data members of reference or const scalar
3878 // type, since they will never get initializers.
3879 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003880 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3881 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003882 bool Complained = false;
3883 for (RecordDecl::field_iterator F = Record->field_begin(),
3884 FEnd = Record->field_end();
3885 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003886 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003887 continue;
3888
Douglas Gregor325e5932010-04-15 00:00:53 +00003889 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003890 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003891 if (!Complained) {
3892 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3893 << Record->getTagKind() << Record;
3894 Complained = true;
3895 }
3896
3897 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3898 << F->getType()->isReferenceType()
3899 << F->getDeclName();
3900 }
3901 }
3902 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003903
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003904 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003905 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003906
3907 if (Record->getIdentifier()) {
3908 // C++ [class.mem]p13:
3909 // If T is the name of a class, then each of the following shall have a
3910 // name different from T:
3911 // - every member of every anonymous union that is a member of class T.
3912 //
3913 // C++ [class.mem]p14:
3914 // In addition, if class T has a user-declared constructor (12.1), every
3915 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00003916 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3917 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3918 ++I) {
3919 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00003920 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3921 isa<IndirectFieldDecl>(D)) {
3922 Diag(D->getLocation(), diag::err_member_name_of_class)
3923 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003924 break;
3925 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003926 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003927 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003928
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003929 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003930 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003931 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003932 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003933 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3934 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3935 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003936
David Blaikieb6b5b972012-09-21 03:21:07 +00003937 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
3938 Diag(Record->getLocation(), diag::warn_abstract_final_class);
3939 DiagnoseAbstractType(Record);
3940 }
3941
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003942 if (!Record->isDependentType()) {
3943 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3944 MEnd = Record->method_end();
3945 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00003946 // See if a method overloads virtual methods in a base
3947 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00003948 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003949 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00003950
3951 // Check whether the explicitly-defaulted special members are valid.
3952 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
3953 CheckExplicitlyDefaultedSpecialMember(*M);
3954
3955 // For an explicitly defaulted or deleted special member, we defer
3956 // determining triviality until the class is complete. That time is now!
3957 if (!M->isImplicit() && !M->isUserProvided()) {
3958 CXXSpecialMember CSM = getSpecialMember(*M);
3959 if (CSM != CXXInvalid) {
3960 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
3961
3962 // Inform the class that we've finished declaring this member.
3963 Record->finishedDefaultedOrDeletedMember(*M);
3964 }
3965 }
3966 }
3967 }
3968
3969 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
3970 // function that is not a constructor declares that member function to be
3971 // const. [...] The class of which that function is a member shall be
3972 // a literal type.
3973 //
3974 // If the class has virtual bases, any constexpr members will already have
3975 // been diagnosed by the checks performed on the member declaration, so
3976 // suppress this (less useful) diagnostic.
3977 //
3978 // We delay this until we know whether an explicitly-defaulted (or deleted)
3979 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00003980 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00003981 !Record->isLiteral() && !Record->getNumVBases()) {
3982 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3983 MEnd = Record->method_end();
3984 M != MEnd; ++M) {
3985 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
3986 switch (Record->getTemplateSpecializationKind()) {
3987 case TSK_ImplicitInstantiation:
3988 case TSK_ExplicitInstantiationDeclaration:
3989 case TSK_ExplicitInstantiationDefinition:
3990 // If a template instantiates to a non-literal type, but its members
3991 // instantiate to constexpr functions, the template is technically
3992 // ill-formed, but we allow it for sanity.
3993 continue;
3994
3995 case TSK_Undeclared:
3996 case TSK_ExplicitSpecialization:
3997 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
3998 diag::err_constexpr_method_non_literal);
3999 break;
4000 }
4001
4002 // Only produce one error per class.
4003 break;
4004 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004005 }
4006 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004007
4008 // Declare inherited constructors. We do this eagerly here because:
4009 // - The standard requires an eager diagnostic for conflicting inherited
4010 // constructors from different classes.
4011 // - The lazy declaration of the other implicit constructors is so as to not
4012 // waste space and performance on classes that are not meant to be
4013 // instantiated (e.g. meta-functions). This doesn't apply to classes that
4014 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004015 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004016}
4017
Richard Smith7756afa2012-06-10 05:43:50 +00004018/// Is the special member function which would be selected to perform the
4019/// specified operation on the specified class type a constexpr constructor?
4020static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4021 Sema::CXXSpecialMember CSM,
4022 bool ConstArg) {
4023 Sema::SpecialMemberOverloadResult *SMOR =
4024 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4025 false, false, false, false);
4026 if (!SMOR || !SMOR->getMethod())
4027 // A constructor we wouldn't select can't be "involved in initializing"
4028 // anything.
4029 return true;
4030 return SMOR->getMethod()->isConstexpr();
4031}
4032
4033/// Determine whether the specified special member function would be constexpr
4034/// if it were implicitly defined.
4035static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4036 Sema::CXXSpecialMember CSM,
4037 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004038 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004039 return false;
4040
4041 // C++11 [dcl.constexpr]p4:
4042 // In the definition of a constexpr constructor [...]
4043 switch (CSM) {
4044 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004045 // Since default constructor lookup is essentially trivial (and cannot
4046 // involve, for instance, template instantiation), we compute whether a
4047 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4048 //
4049 // This is important for performance; we need to know whether the default
4050 // constructor is constexpr to determine whether the type is a literal type.
4051 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4052
Richard Smith7756afa2012-06-10 05:43:50 +00004053 case Sema::CXXCopyConstructor:
4054 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004055 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004056 break;
4057
4058 case Sema::CXXCopyAssignment:
4059 case Sema::CXXMoveAssignment:
4060 case Sema::CXXDestructor:
4061 case Sema::CXXInvalid:
4062 return false;
4063 }
4064
4065 // -- if the class is a non-empty union, or for each non-empty anonymous
4066 // union member of a non-union class, exactly one non-static data member
4067 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004068 //
4069 // If we squint, this is guaranteed, since exactly one non-static data member
4070 // will be initialized (if the constructor isn't deleted), we just don't know
4071 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004072 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004073 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004074
4075 // -- the class shall not have any virtual base classes;
4076 if (ClassDecl->getNumVBases())
4077 return false;
4078
4079 // -- every constructor involved in initializing [...] base class
4080 // sub-objects shall be a constexpr constructor;
4081 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4082 BEnd = ClassDecl->bases_end();
4083 B != BEnd; ++B) {
4084 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4085 if (!BaseType) continue;
4086
4087 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4088 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4089 return false;
4090 }
4091
4092 // -- every constructor involved in initializing non-static data members
4093 // [...] shall be a constexpr constructor;
4094 // -- every non-static data member and base class sub-object shall be
4095 // initialized
4096 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4097 FEnd = ClassDecl->field_end();
4098 F != FEnd; ++F) {
4099 if (F->isInvalidDecl())
4100 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004101 if (const RecordType *RecordTy =
4102 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004103 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4104 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4105 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004106 }
4107 }
4108
4109 // All OK, it's constexpr!
4110 return true;
4111}
4112
Richard Smithb9d0b762012-07-27 04:22:15 +00004113static Sema::ImplicitExceptionSpecification
4114computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4115 switch (S.getSpecialMember(MD)) {
4116 case Sema::CXXDefaultConstructor:
4117 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4118 case Sema::CXXCopyConstructor:
4119 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4120 case Sema::CXXCopyAssignment:
4121 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4122 case Sema::CXXMoveConstructor:
4123 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4124 case Sema::CXXMoveAssignment:
4125 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4126 case Sema::CXXDestructor:
4127 return S.ComputeDefaultedDtorExceptionSpec(MD);
4128 case Sema::CXXInvalid:
4129 break;
4130 }
4131 llvm_unreachable("only special members have implicit exception specs");
4132}
4133
Richard Smithdd25e802012-07-30 23:48:14 +00004134static void
4135updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4136 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4137 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4138 ExceptSpec.getEPI(EPI);
4139 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4140 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4141 FPT->getNumArgs(), EPI));
4142 FD->setType(QualType(NewFPT, 0));
4143}
4144
Richard Smithb9d0b762012-07-27 04:22:15 +00004145void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4146 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4147 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4148 return;
4149
Richard Smithdd25e802012-07-30 23:48:14 +00004150 // Evaluate the exception specification.
4151 ImplicitExceptionSpecification ExceptSpec =
4152 computeImplicitExceptionSpec(*this, Loc, MD);
4153
4154 // Update the type of the special member to use it.
4155 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4156
4157 // A user-provided destructor can be defined outside the class. When that
4158 // happens, be sure to update the exception specification on both
4159 // declarations.
4160 const FunctionProtoType *CanonicalFPT =
4161 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4162 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4163 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4164 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004165}
4166
Richard Smith3003e1d2012-05-15 04:39:51 +00004167void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4168 CXXRecordDecl *RD = MD->getParent();
4169 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004170
Richard Smith3003e1d2012-05-15 04:39:51 +00004171 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4172 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004173
4174 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004175 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004176 bool First = MD == MD->getCanonicalDecl();
4177
4178 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004179
4180 // C++11 [dcl.fct.def.default]p1:
4181 // A function that is explicitly defaulted shall
4182 // -- be a special member function (checked elsewhere),
4183 // -- have the same type (except for ref-qualifiers, and except that a
4184 // copy operation can take a non-const reference) as an implicit
4185 // declaration, and
4186 // -- not have default arguments.
4187 unsigned ExpectedParams = 1;
4188 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4189 ExpectedParams = 0;
4190 if (MD->getNumParams() != ExpectedParams) {
4191 // This also checks for default arguments: a copy or move constructor with a
4192 // default argument is classified as a default constructor, and assignment
4193 // operations and destructors can't have default arguments.
4194 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4195 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004196 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004197 } else if (MD->isVariadic()) {
4198 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4199 << CSM << MD->getSourceRange();
4200 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004201 }
4202
Richard Smith3003e1d2012-05-15 04:39:51 +00004203 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004204
Richard Smith7756afa2012-06-10 05:43:50 +00004205 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004206 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004207 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004208 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004209 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004210
Richard Smith3003e1d2012-05-15 04:39:51 +00004211 QualType ReturnType = Context.VoidTy;
4212 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4213 // Check for return type matching.
4214 ReturnType = Type->getResultType();
4215 QualType ExpectedReturnType =
4216 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4217 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4218 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4219 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4220 HadError = true;
4221 }
4222
4223 // A defaulted special member cannot have cv-qualifiers.
4224 if (Type->getTypeQuals()) {
4225 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4226 << (CSM == CXXMoveAssignment);
4227 HadError = true;
4228 }
4229 }
4230
4231 // Check for parameter type matching.
4232 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004233 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004234 if (ExpectedParams && ArgType->isReferenceType()) {
4235 // Argument must be reference to possibly-const T.
4236 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004237 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004238
4239 if (ReferentType.isVolatileQualified()) {
4240 Diag(MD->getLocation(),
4241 diag::err_defaulted_special_member_volatile_param) << CSM;
4242 HadError = true;
4243 }
4244
Richard Smith7756afa2012-06-10 05:43:50 +00004245 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004246 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4247 Diag(MD->getLocation(),
4248 diag::err_defaulted_special_member_copy_const_param)
4249 << (CSM == CXXCopyAssignment);
4250 // FIXME: Explain why this special member can't be const.
4251 } else {
4252 Diag(MD->getLocation(),
4253 diag::err_defaulted_special_member_move_const_param)
4254 << (CSM == CXXMoveAssignment);
4255 }
4256 HadError = true;
4257 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004258 } else if (ExpectedParams) {
4259 // A copy assignment operator can take its argument by value, but a
4260 // defaulted one cannot.
4261 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004262 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004263 HadError = true;
4264 }
Sean Huntbe631222011-05-17 20:44:43 +00004265
Richard Smith61802452011-12-22 02:22:31 +00004266 // C++11 [dcl.fct.def.default]p2:
4267 // An explicitly-defaulted function may be declared constexpr only if it
4268 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004269 // Do not apply this rule to members of class templates, since core issue 1358
4270 // makes such functions always instantiate to constexpr functions. For
4271 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004272 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4273 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004274 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4275 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4276 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004277 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004278 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004279 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004280
Richard Smith61802452011-12-22 02:22:31 +00004281 // and may have an explicit exception-specification only if it is compatible
4282 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004283 if (Type->hasExceptionSpec()) {
4284 // Delay the check if this is the first declaration of the special member,
4285 // since we may not have parsed some necessary in-class initializers yet.
4286 if (First)
4287 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4288 else
4289 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4290 }
Richard Smith61802452011-12-22 02:22:31 +00004291
4292 // If a function is explicitly defaulted on its first declaration,
4293 if (First) {
4294 // -- it is implicitly considered to be constexpr if the implicit
4295 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004296 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004297
Richard Smith3003e1d2012-05-15 04:39:51 +00004298 // -- it is implicitly considered to have the same exception-specification
4299 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004300 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4301 EPI.ExceptionSpecType = EST_Unevaluated;
4302 EPI.ExceptionSpecDecl = MD;
4303 MD->setType(Context.getFunctionType(ReturnType, &ArgType,
4304 ExpectedParams, EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004305 }
4306
Richard Smith3003e1d2012-05-15 04:39:51 +00004307 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004308 if (First) {
4309 MD->setDeletedAsWritten();
4310 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004311 // C++11 [dcl.fct.def.default]p4:
4312 // [For a] user-provided explicitly-defaulted function [...] if such a
4313 // function is implicitly defined as deleted, the program is ill-formed.
4314 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4315 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004316 }
4317 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004318
Richard Smith3003e1d2012-05-15 04:39:51 +00004319 if (HadError)
4320 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004321}
4322
Richard Smith1d28caf2012-12-11 01:14:52 +00004323/// Check whether the exception specification provided for an
4324/// explicitly-defaulted special member matches the exception specification
4325/// that would have been generated for an implicit special member, per
4326/// C++11 [dcl.fct.def.default]p2.
4327void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4328 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4329 // Compute the implicit exception specification.
4330 FunctionProtoType::ExtProtoInfo EPI;
4331 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4332 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4333 Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4334
4335 // Ensure that it matches.
4336 CheckEquivalentExceptionSpec(
4337 PDiag(diag::err_incorrect_defaulted_exception_spec)
4338 << getSpecialMember(MD), PDiag(),
4339 ImplicitType, SourceLocation(),
4340 SpecifiedType, MD->getLocation());
4341}
4342
4343void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4344 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4345 I != N; ++I)
4346 CheckExplicitlyDefaultedMemberExceptionSpec(
4347 DelayedDefaultedMemberExceptionSpecs[I].first,
4348 DelayedDefaultedMemberExceptionSpecs[I].second);
4349
4350 DelayedDefaultedMemberExceptionSpecs.clear();
4351}
4352
Richard Smith7d5088a2012-02-18 02:02:13 +00004353namespace {
4354struct SpecialMemberDeletionInfo {
4355 Sema &S;
4356 CXXMethodDecl *MD;
4357 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004358 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004359
4360 // Properties of the special member, computed for convenience.
4361 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4362 SourceLocation Loc;
4363
4364 bool AllFieldsAreConst;
4365
4366 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004367 Sema::CXXSpecialMember CSM, bool Diagnose)
4368 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004369 IsConstructor(false), IsAssignment(false), IsMove(false),
4370 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4371 AllFieldsAreConst(true) {
4372 switch (CSM) {
4373 case Sema::CXXDefaultConstructor:
4374 case Sema::CXXCopyConstructor:
4375 IsConstructor = true;
4376 break;
4377 case Sema::CXXMoveConstructor:
4378 IsConstructor = true;
4379 IsMove = true;
4380 break;
4381 case Sema::CXXCopyAssignment:
4382 IsAssignment = true;
4383 break;
4384 case Sema::CXXMoveAssignment:
4385 IsAssignment = true;
4386 IsMove = true;
4387 break;
4388 case Sema::CXXDestructor:
4389 break;
4390 case Sema::CXXInvalid:
4391 llvm_unreachable("invalid special member kind");
4392 }
4393
4394 if (MD->getNumParams()) {
4395 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4396 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4397 }
4398 }
4399
4400 bool inUnion() const { return MD->getParent()->isUnion(); }
4401
4402 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004403 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4404 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004405 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004406 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4407 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4408 Quals = 0;
4409 return S.LookupSpecialMember(Class, CSM,
4410 ConstArg || (Quals & Qualifiers::Const),
4411 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004412 MD->getRefQualifier() == RQ_RValue,
4413 TQ & Qualifiers::Const,
4414 TQ & Qualifiers::Volatile);
4415 }
4416
Richard Smith6c4c36c2012-03-30 20:53:28 +00004417 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004418
Richard Smith6c4c36c2012-03-30 20:53:28 +00004419 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004420 bool shouldDeleteForField(FieldDecl *FD);
4421 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004422
Richard Smith517bb842012-07-18 03:51:16 +00004423 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4424 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004425 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4426 Sema::SpecialMemberOverloadResult *SMOR,
4427 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004428
4429 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004430};
4431}
4432
John McCall12d8d802012-04-09 20:53:23 +00004433/// Is the given special member inaccessible when used on the given
4434/// sub-object.
4435bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4436 CXXMethodDecl *target) {
4437 /// If we're operating on a base class, the object type is the
4438 /// type of this special member.
4439 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004440 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004441 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4442 objectTy = S.Context.getTypeDeclType(MD->getParent());
4443 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4444
4445 // If we're operating on a field, the object type is the type of the field.
4446 } else {
4447 objectTy = S.Context.getTypeDeclType(target->getParent());
4448 }
4449
4450 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4451}
4452
Richard Smith6c4c36c2012-03-30 20:53:28 +00004453/// Check whether we should delete a special member due to the implicit
4454/// definition containing a call to a special member of a subobject.
4455bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4456 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4457 bool IsDtorCallInCtor) {
4458 CXXMethodDecl *Decl = SMOR->getMethod();
4459 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4460
4461 int DiagKind = -1;
4462
4463 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4464 DiagKind = !Decl ? 0 : 1;
4465 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4466 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004467 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004468 DiagKind = 3;
4469 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4470 !Decl->isTrivial()) {
4471 // A member of a union must have a trivial corresponding special member.
4472 // As a weird special case, a destructor call from a union's constructor
4473 // must be accessible and non-deleted, but need not be trivial. Such a
4474 // destructor is never actually called, but is semantically checked as
4475 // if it were.
4476 DiagKind = 4;
4477 }
4478
4479 if (DiagKind == -1)
4480 return false;
4481
4482 if (Diagnose) {
4483 if (Field) {
4484 S.Diag(Field->getLocation(),
4485 diag::note_deleted_special_member_class_subobject)
4486 << CSM << MD->getParent() << /*IsField*/true
4487 << Field << DiagKind << IsDtorCallInCtor;
4488 } else {
4489 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4490 S.Diag(Base->getLocStart(),
4491 diag::note_deleted_special_member_class_subobject)
4492 << CSM << MD->getParent() << /*IsField*/false
4493 << Base->getType() << DiagKind << IsDtorCallInCtor;
4494 }
4495
4496 if (DiagKind == 1)
4497 S.NoteDeletedFunction(Decl);
4498 // FIXME: Explain inaccessibility if DiagKind == 3.
4499 }
4500
4501 return true;
4502}
4503
Richard Smith9a561d52012-02-26 09:11:52 +00004504/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004505/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004506bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004507 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004508 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004509
4510 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004511 // -- any direct or virtual base class, or non-static data member with no
4512 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004513 // either M has no default constructor or overload resolution as applied
4514 // to M's default constructor results in an ambiguity or in a function
4515 // that is deleted or inaccessible
4516 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4517 // -- a direct or virtual base class B that cannot be copied/moved because
4518 // overload resolution, as applied to B's corresponding special member,
4519 // results in an ambiguity or a function that is deleted or inaccessible
4520 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004521 // C++11 [class.dtor]p5:
4522 // -- any direct or virtual base class [...] has a type with a destructor
4523 // that is deleted or inaccessible
4524 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004525 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004526 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004527 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004528
Richard Smith6c4c36c2012-03-30 20:53:28 +00004529 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4530 // -- any direct or virtual base class or non-static data member has a
4531 // type with a destructor that is deleted or inaccessible
4532 if (IsConstructor) {
4533 Sema::SpecialMemberOverloadResult *SMOR =
4534 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4535 false, false, false, false, false);
4536 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4537 return true;
4538 }
4539
Richard Smith9a561d52012-02-26 09:11:52 +00004540 return false;
4541}
4542
4543/// Check whether we should delete a special member function due to the class
4544/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004545bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004546 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004547 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004548}
4549
4550/// Check whether we should delete a special member function due to the class
4551/// having a particular non-static data member.
4552bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4553 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4554 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4555
4556 if (CSM == Sema::CXXDefaultConstructor) {
4557 // For a default constructor, all references must be initialized in-class
4558 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004559 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4560 if (Diagnose)
4561 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4562 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004563 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004564 }
Richard Smith79363f52012-02-27 06:07:25 +00004565 // C++11 [class.ctor]p5: any non-variant non-static data member of
4566 // const-qualified type (or array thereof) with no
4567 // brace-or-equal-initializer does not have a user-provided default
4568 // constructor.
4569 if (!inUnion() && FieldType.isConstQualified() &&
4570 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004571 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4572 if (Diagnose)
4573 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004574 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004575 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004576 }
4577
4578 if (inUnion() && !FieldType.isConstQualified())
4579 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004580 } else if (CSM == Sema::CXXCopyConstructor) {
4581 // For a copy constructor, data members must not be of rvalue reference
4582 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004583 if (FieldType->isRValueReferenceType()) {
4584 if (Diagnose)
4585 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4586 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004587 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004588 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004589 } else if (IsAssignment) {
4590 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004591 if (FieldType->isReferenceType()) {
4592 if (Diagnose)
4593 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4594 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004595 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004596 }
4597 if (!FieldRecord && FieldType.isConstQualified()) {
4598 // C++11 [class.copy]p23:
4599 // -- a non-static data member of const non-class type (or array thereof)
4600 if (Diagnose)
4601 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004602 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004603 return true;
4604 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004605 }
4606
4607 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004608 // Some additional restrictions exist on the variant members.
4609 if (!inUnion() && FieldRecord->isUnion() &&
4610 FieldRecord->isAnonymousStructOrUnion()) {
4611 bool AllVariantFieldsAreConst = true;
4612
Richard Smithdf8dc862012-03-29 19:00:10 +00004613 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004614 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4615 UE = FieldRecord->field_end();
4616 UI != UE; ++UI) {
4617 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004618
4619 if (!UnionFieldType.isConstQualified())
4620 AllVariantFieldsAreConst = false;
4621
Richard Smith9a561d52012-02-26 09:11:52 +00004622 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4623 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004624 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4625 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004626 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004627 }
4628
4629 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004630 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004631 FieldRecord->field_begin() != FieldRecord->field_end()) {
4632 if (Diagnose)
4633 S.Diag(FieldRecord->getLocation(),
4634 diag::note_deleted_default_ctor_all_const)
4635 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004636 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004637 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004638
Richard Smithdf8dc862012-03-29 19:00:10 +00004639 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004640 // This is technically non-conformant, but sanity demands it.
4641 return false;
4642 }
4643
Richard Smith517bb842012-07-18 03:51:16 +00004644 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4645 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004646 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004647 }
4648
4649 return false;
4650}
4651
4652/// C++11 [class.ctor] p5:
4653/// A defaulted default constructor for a class X is defined as deleted if
4654/// X is a union and all of its variant members are of const-qualified type.
4655bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004656 // This is a silly definition, because it gives an empty union a deleted
4657 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004658 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4659 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4660 if (Diagnose)
4661 S.Diag(MD->getParent()->getLocation(),
4662 diag::note_deleted_default_ctor_all_const)
4663 << MD->getParent() << /*not anonymous union*/0;
4664 return true;
4665 }
4666 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004667}
4668
4669/// Determine whether a defaulted special member function should be defined as
4670/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4671/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004672bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4673 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004674 if (MD->isInvalidDecl())
4675 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004676 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004677 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004678 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004679 return false;
4680
Richard Smith7d5088a2012-02-18 02:02:13 +00004681 // C++11 [expr.lambda.prim]p19:
4682 // The closure type associated with a lambda-expression has a
4683 // deleted (8.4.3) default constructor and a deleted copy
4684 // assignment operator.
4685 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004686 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4687 if (Diagnose)
4688 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004689 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004690 }
4691
Richard Smith5bdaac52012-04-02 20:59:25 +00004692 // For an anonymous struct or union, the copy and assignment special members
4693 // will never be used, so skip the check. For an anonymous union declared at
4694 // namespace scope, the constructor and destructor are used.
4695 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4696 RD->isAnonymousStructOrUnion())
4697 return false;
4698
Richard Smith6c4c36c2012-03-30 20:53:28 +00004699 // C++11 [class.copy]p7, p18:
4700 // If the class definition declares a move constructor or move assignment
4701 // operator, an implicitly declared copy constructor or copy assignment
4702 // operator is defined as deleted.
4703 if (MD->isImplicit() &&
4704 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4705 CXXMethodDecl *UserDeclaredMove = 0;
4706
4707 // In Microsoft mode, a user-declared move only causes the deletion of the
4708 // corresponding copy operation, not both copy operations.
4709 if (RD->hasUserDeclaredMoveConstructor() &&
4710 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4711 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004712
4713 // Find any user-declared move constructor.
4714 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4715 E = RD->ctor_end(); I != E; ++I) {
4716 if (I->isMoveConstructor()) {
4717 UserDeclaredMove = *I;
4718 break;
4719 }
4720 }
Richard Smith1c931be2012-04-02 18:40:40 +00004721 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004722 } else if (RD->hasUserDeclaredMoveAssignment() &&
4723 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4724 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004725
4726 // Find any user-declared move assignment operator.
4727 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4728 E = RD->method_end(); I != E; ++I) {
4729 if (I->isMoveAssignmentOperator()) {
4730 UserDeclaredMove = *I;
4731 break;
4732 }
4733 }
Richard Smith1c931be2012-04-02 18:40:40 +00004734 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004735 }
4736
4737 if (UserDeclaredMove) {
4738 Diag(UserDeclaredMove->getLocation(),
4739 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004740 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004741 << UserDeclaredMove->isMoveAssignmentOperator();
4742 return true;
4743 }
4744 }
Sean Hunte16da072011-10-10 06:18:57 +00004745
Richard Smith5bdaac52012-04-02 20:59:25 +00004746 // Do access control from the special member function
4747 ContextRAII MethodContext(*this, MD);
4748
Richard Smith9a561d52012-02-26 09:11:52 +00004749 // C++11 [class.dtor]p5:
4750 // -- for a virtual destructor, lookup of the non-array deallocation function
4751 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004752 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004753 FunctionDecl *OperatorDelete = 0;
4754 DeclarationName Name =
4755 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4756 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004757 OperatorDelete, false)) {
4758 if (Diagnose)
4759 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004760 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004761 }
Richard Smith9a561d52012-02-26 09:11:52 +00004762 }
4763
Richard Smith6c4c36c2012-03-30 20:53:28 +00004764 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004765
Sean Huntcdee3fe2011-05-11 22:34:38 +00004766 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004767 BE = RD->bases_end(); BI != BE; ++BI)
4768 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004769 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004770 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004771
4772 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004773 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004774 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004775 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004776
4777 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004778 FE = RD->field_end(); FI != FE; ++FI)
4779 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004780 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004781 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004782
Richard Smith7d5088a2012-02-18 02:02:13 +00004783 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004784 return true;
4785
4786 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004787}
4788
Richard Smithac713512012-12-08 02:53:02 +00004789/// Perform lookup for a special member of the specified kind, and determine
4790/// whether it is trivial. If the triviality can be determined without the
4791/// lookup, skip it. This is intended for use when determining whether a
4792/// special member of a containing object is trivial, and thus does not ever
4793/// perform overload resolution for default constructors.
4794///
4795/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4796/// member that was most likely to be intended to be trivial, if any.
4797static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4798 Sema::CXXSpecialMember CSM, unsigned Quals,
4799 CXXMethodDecl **Selected) {
4800 if (Selected)
4801 *Selected = 0;
4802
4803 switch (CSM) {
4804 case Sema::CXXInvalid:
4805 llvm_unreachable("not a special member");
4806
4807 case Sema::CXXDefaultConstructor:
4808 // C++11 [class.ctor]p5:
4809 // A default constructor is trivial if:
4810 // - all the [direct subobjects] have trivial default constructors
4811 //
4812 // Note, no overload resolution is performed in this case.
4813 if (RD->hasTrivialDefaultConstructor())
4814 return true;
4815
4816 if (Selected) {
4817 // If there's a default constructor which could have been trivial, dig it
4818 // out. Otherwise, if there's any user-provided default constructor, point
4819 // to that as an example of why there's not a trivial one.
4820 CXXConstructorDecl *DefCtor = 0;
4821 if (RD->needsImplicitDefaultConstructor())
4822 S.DeclareImplicitDefaultConstructor(RD);
4823 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4824 CE = RD->ctor_end(); CI != CE; ++CI) {
4825 if (!CI->isDefaultConstructor())
4826 continue;
4827 DefCtor = *CI;
4828 if (!DefCtor->isUserProvided())
4829 break;
4830 }
4831
4832 *Selected = DefCtor;
4833 }
4834
4835 return false;
4836
4837 case Sema::CXXDestructor:
4838 // C++11 [class.dtor]p5:
4839 // A destructor is trivial if:
4840 // - all the direct [subobjects] have trivial destructors
4841 if (RD->hasTrivialDestructor())
4842 return true;
4843
4844 if (Selected) {
4845 if (RD->needsImplicitDestructor())
4846 S.DeclareImplicitDestructor(RD);
4847 *Selected = RD->getDestructor();
4848 }
4849
4850 return false;
4851
4852 case Sema::CXXCopyConstructor:
4853 // C++11 [class.copy]p12:
4854 // A copy constructor is trivial if:
4855 // - the constructor selected to copy each direct [subobject] is trivial
4856 if (RD->hasTrivialCopyConstructor()) {
4857 if (Quals == Qualifiers::Const)
4858 // We must either select the trivial copy constructor or reach an
4859 // ambiguity; no need to actually perform overload resolution.
4860 return true;
4861 } else if (!Selected) {
4862 return false;
4863 }
4864 // In C++98, we are not supposed to perform overload resolution here, but we
4865 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4866 // cases like B as having a non-trivial copy constructor:
4867 // struct A { template<typename T> A(T&); };
4868 // struct B { mutable A a; };
4869 goto NeedOverloadResolution;
4870
4871 case Sema::CXXCopyAssignment:
4872 // C++11 [class.copy]p25:
4873 // A copy assignment operator is trivial if:
4874 // - the assignment operator selected to copy each direct [subobject] is
4875 // trivial
4876 if (RD->hasTrivialCopyAssignment()) {
4877 if (Quals == Qualifiers::Const)
4878 return true;
4879 } else if (!Selected) {
4880 return false;
4881 }
4882 // In C++98, we are not supposed to perform overload resolution here, but we
4883 // treat that as a language defect.
4884 goto NeedOverloadResolution;
4885
4886 case Sema::CXXMoveConstructor:
4887 case Sema::CXXMoveAssignment:
4888 NeedOverloadResolution:
4889 Sema::SpecialMemberOverloadResult *SMOR =
4890 S.LookupSpecialMember(RD, CSM,
4891 Quals & Qualifiers::Const,
4892 Quals & Qualifiers::Volatile,
4893 /*RValueThis*/false, /*ConstThis*/false,
4894 /*VolatileThis*/false);
4895
4896 // The standard doesn't describe how to behave if the lookup is ambiguous.
4897 // We treat it as not making the member non-trivial, just like the standard
4898 // mandates for the default constructor. This should rarely matter, because
4899 // the member will also be deleted.
4900 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4901 return true;
4902
4903 if (!SMOR->getMethod()) {
4904 assert(SMOR->getKind() ==
4905 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
4906 return false;
4907 }
4908
4909 // We deliberately don't check if we found a deleted special member. We're
4910 // not supposed to!
4911 if (Selected)
4912 *Selected = SMOR->getMethod();
4913 return SMOR->getMethod()->isTrivial();
4914 }
4915
4916 llvm_unreachable("unknown special method kind");
4917}
4918
4919CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
4920 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
4921 CI != CE; ++CI)
4922 if (!CI->isImplicit())
4923 return *CI;
4924
4925 // Look for constructor templates.
4926 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
4927 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
4928 if (CXXConstructorDecl *CD =
4929 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
4930 return CD;
4931 }
4932
4933 return 0;
4934}
4935
4936/// The kind of subobject we are checking for triviality. The values of this
4937/// enumeration are used in diagnostics.
4938enum TrivialSubobjectKind {
4939 /// The subobject is a base class.
4940 TSK_BaseClass,
4941 /// The subobject is a non-static data member.
4942 TSK_Field,
4943 /// The object is actually the complete object.
4944 TSK_CompleteObject
4945};
4946
4947/// Check whether the special member selected for a given type would be trivial.
4948static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
4949 QualType SubType,
4950 Sema::CXXSpecialMember CSM,
4951 TrivialSubobjectKind Kind,
4952 bool Diagnose) {
4953 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
4954 if (!SubRD)
4955 return true;
4956
4957 CXXMethodDecl *Selected;
4958 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
4959 Diagnose ? &Selected : 0))
4960 return true;
4961
4962 if (Diagnose) {
4963 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
4964 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
4965 << Kind << SubType.getUnqualifiedType();
4966 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
4967 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
4968 } else if (!Selected)
4969 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
4970 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
4971 else if (Selected->isUserProvided()) {
4972 if (Kind == TSK_CompleteObject)
4973 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
4974 << Kind << SubType.getUnqualifiedType() << CSM;
4975 else {
4976 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
4977 << Kind << SubType.getUnqualifiedType() << CSM;
4978 S.Diag(Selected->getLocation(), diag::note_declared_at);
4979 }
4980 } else {
4981 if (Kind != TSK_CompleteObject)
4982 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
4983 << Kind << SubType.getUnqualifiedType() << CSM;
4984
4985 // Explain why the defaulted or deleted special member isn't trivial.
4986 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
4987 }
4988 }
4989
4990 return false;
4991}
4992
4993/// Check whether the members of a class type allow a special member to be
4994/// trivial.
4995static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
4996 Sema::CXXSpecialMember CSM,
4997 bool ConstArg, bool Diagnose) {
4998 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4999 FE = RD->field_end(); FI != FE; ++FI) {
5000 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5001 continue;
5002
5003 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5004
5005 // Pretend anonymous struct or union members are members of this class.
5006 if (FI->isAnonymousStructOrUnion()) {
5007 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5008 CSM, ConstArg, Diagnose))
5009 return false;
5010 continue;
5011 }
5012
5013 // C++11 [class.ctor]p5:
5014 // A default constructor is trivial if [...]
5015 // -- no non-static data member of its class has a
5016 // brace-or-equal-initializer
5017 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5018 if (Diagnose)
5019 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5020 return false;
5021 }
5022
5023 // Objective C ARC 4.3.5:
5024 // [...] nontrivally ownership-qualified types are [...] not trivially
5025 // default constructible, copy constructible, move constructible, copy
5026 // assignable, move assignable, or destructible [...]
5027 if (S.getLangOpts().ObjCAutoRefCount &&
5028 FieldType.hasNonTrivialObjCLifetime()) {
5029 if (Diagnose)
5030 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5031 << RD << FieldType.getObjCLifetime();
5032 return false;
5033 }
5034
5035 if (ConstArg && !FI->isMutable())
5036 FieldType.addConst();
5037 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5038 TSK_Field, Diagnose))
5039 return false;
5040 }
5041
5042 return true;
5043}
5044
5045/// Diagnose why the specified class does not have a trivial special member of
5046/// the given kind.
5047void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5048 QualType Ty = Context.getRecordType(RD);
5049 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5050 Ty.addConst();
5051
5052 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5053 TSK_CompleteObject, /*Diagnose*/true);
5054}
5055
5056/// Determine whether a defaulted or deleted special member function is trivial,
5057/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5058/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5059bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5060 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005061 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5062
5063 CXXRecordDecl *RD = MD->getParent();
5064
5065 bool ConstArg = false;
5066 ParmVarDecl *Param0 = MD->getNumParams() ? MD->getParamDecl(0) : 0;
5067
5068 // C++11 [class.copy]p12, p25:
5069 // A [special member] is trivial if its declared parameter type is the same
5070 // as if it had been implicitly declared [...]
5071 switch (CSM) {
5072 case CXXDefaultConstructor:
5073 case CXXDestructor:
5074 // Trivial default constructors and destructors cannot have parameters.
5075 break;
5076
5077 case CXXCopyConstructor:
5078 case CXXCopyAssignment: {
5079 // Trivial copy operations always have const, non-volatile parameter types.
5080 ConstArg = true;
5081 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5082 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5083 if (Diagnose)
5084 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5085 << Param0->getSourceRange() << Param0->getType()
5086 << Context.getLValueReferenceType(
5087 Context.getRecordType(RD).withConst());
5088 return false;
5089 }
5090 break;
5091 }
5092
5093 case CXXMoveConstructor:
5094 case CXXMoveAssignment: {
5095 // Trivial move operations always have non-cv-qualified parameters.
5096 const RValueReferenceType *RT =
5097 Param0->getType()->getAs<RValueReferenceType>();
5098 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5099 if (Diagnose)
5100 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5101 << Param0->getSourceRange() << Param0->getType()
5102 << Context.getRValueReferenceType(Context.getRecordType(RD));
5103 return false;
5104 }
5105 break;
5106 }
5107
5108 case CXXInvalid:
5109 llvm_unreachable("not a special member");
5110 }
5111
5112 // FIXME: We require that the parameter-declaration-clause is equivalent to
5113 // that of an implicit declaration, not just that the declared parameter type
5114 // matches, in order to prevent absuridities like a function simultaneously
5115 // being a trivial copy constructor and a non-trivial default constructor.
5116 // This issue has not yet been assigned a core issue number.
5117 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5118 if (Diagnose)
5119 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5120 diag::note_nontrivial_default_arg)
5121 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5122 return false;
5123 }
5124 if (MD->isVariadic()) {
5125 if (Diagnose)
5126 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5127 return false;
5128 }
5129
5130 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5131 // A copy/move [constructor or assignment operator] is trivial if
5132 // -- the [member] selected to copy/move each direct base class subobject
5133 // is trivial
5134 //
5135 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5136 // A [default constructor or destructor] is trivial if
5137 // -- all the direct base classes have trivial [default constructors or
5138 // destructors]
5139 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5140 BE = RD->bases_end(); BI != BE; ++BI)
5141 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5142 ConstArg ? BI->getType().withConst()
5143 : BI->getType(),
5144 CSM, TSK_BaseClass, Diagnose))
5145 return false;
5146
5147 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5148 // A copy/move [constructor or assignment operator] for a class X is
5149 // trivial if
5150 // -- for each non-static data member of X that is of class type (or array
5151 // thereof), the constructor selected to copy/move that member is
5152 // trivial
5153 //
5154 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5155 // A [default constructor or destructor] is trivial if
5156 // -- for all of the non-static data members of its class that are of class
5157 // type (or array thereof), each such class has a trivial [default
5158 // constructor or destructor]
5159 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5160 return false;
5161
5162 // C++11 [class.dtor]p5:
5163 // A destructor is trivial if [...]
5164 // -- the destructor is not virtual
5165 if (CSM == CXXDestructor && MD->isVirtual()) {
5166 if (Diagnose)
5167 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5168 return false;
5169 }
5170
5171 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5172 // A [special member] for class X is trivial if [...]
5173 // -- class X has no virtual functions and no virtual base classes
5174 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5175 if (!Diagnose)
5176 return false;
5177
5178 if (RD->getNumVBases()) {
5179 // Check for virtual bases. We already know that the corresponding
5180 // member in all bases is trivial, so vbases must all be direct.
5181 CXXBaseSpecifier &BS = *RD->vbases_begin();
5182 assert(BS.isVirtual());
5183 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5184 return false;
5185 }
5186
5187 // Must have a virtual method.
5188 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5189 ME = RD->method_end(); MI != ME; ++MI) {
5190 if (MI->isVirtual()) {
5191 SourceLocation MLoc = MI->getLocStart();
5192 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5193 return false;
5194 }
5195 }
5196
5197 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5198 }
5199
5200 // Looks like it's trivial!
5201 return true;
5202}
5203
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005204/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005205namespace {
5206 struct FindHiddenVirtualMethodData {
5207 Sema *S;
5208 CXXMethodDecl *Method;
5209 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005210 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005211 };
5212}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005213
David Blaikie5f750682012-10-19 00:53:08 +00005214/// \brief Check whether any most overriden method from MD in Methods
5215static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5216 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5217 if (MD->size_overridden_methods() == 0)
5218 return Methods.count(MD->getCanonicalDecl());
5219 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5220 E = MD->end_overridden_methods();
5221 I != E; ++I)
5222 if (CheckMostOverridenMethods(*I, Methods))
5223 return true;
5224 return false;
5225}
5226
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005227/// \brief Member lookup function that determines whether a given C++
5228/// method overloads virtual methods in a base class without overriding any,
5229/// to be used with CXXRecordDecl::lookupInBases().
5230static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5231 CXXBasePath &Path,
5232 void *UserData) {
5233 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5234
5235 FindHiddenVirtualMethodData &Data
5236 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5237
5238 DeclarationName Name = Data.Method->getDeclName();
5239 assert(Name.getNameKind() == DeclarationName::Identifier);
5240
5241 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005242 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005243 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005244 !Path.Decls.empty();
5245 Path.Decls = Path.Decls.slice(1)) {
5246 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005247 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005248 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005249 foundSameNameMethod = true;
5250 // Interested only in hidden virtual methods.
5251 if (!MD->isVirtual())
5252 continue;
5253 // If the method we are checking overrides a method from its base
5254 // don't warn about the other overloaded methods.
5255 if (!Data.S->IsOverload(Data.Method, MD, false))
5256 return true;
5257 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005258 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005259 overloadedMethods.push_back(MD);
5260 }
5261 }
5262
5263 if (foundSameNameMethod)
5264 Data.OverloadedMethods.append(overloadedMethods.begin(),
5265 overloadedMethods.end());
5266 return foundSameNameMethod;
5267}
5268
David Blaikie5f750682012-10-19 00:53:08 +00005269/// \brief Add the most overriden methods from MD to Methods
5270static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5271 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5272 if (MD->size_overridden_methods() == 0)
5273 Methods.insert(MD->getCanonicalDecl());
5274 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5275 E = MD->end_overridden_methods();
5276 I != E; ++I)
5277 AddMostOverridenMethods(*I, Methods);
5278}
5279
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005280/// \brief See if a method overloads virtual methods in a base class without
5281/// overriding any.
5282void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5283 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005284 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005285 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005286 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005287 return;
5288
5289 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5290 /*bool RecordPaths=*/false,
5291 /*bool DetectVirtual=*/false);
5292 FindHiddenVirtualMethodData Data;
5293 Data.Method = MD;
5294 Data.S = this;
5295
5296 // Keep the base methods that were overriden or introduced in the subclass
5297 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005298 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5299 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5300 NamedDecl *ND = *I;
5301 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005302 ND = shad->getTargetDecl();
5303 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5304 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005305 }
5306
5307 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5308 !Data.OverloadedMethods.empty()) {
5309 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5310 << MD << (Data.OverloadedMethods.size() > 1);
5311
5312 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5313 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5314 Diag(overloadedMD->getLocation(),
5315 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5316 }
5317 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005318}
5319
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005320void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005321 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005322 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005323 SourceLocation RBrac,
5324 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005325 if (!TagDecl)
5326 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005327
Douglas Gregor42af25f2009-05-11 19:58:34 +00005328 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005329
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005330 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5331 if (l->getKind() != AttributeList::AT_Visibility)
5332 continue;
5333 l->setInvalid();
5334 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5335 l->getName();
5336 }
5337
David Blaikie77b6de02011-09-22 02:58:26 +00005338 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005339 // strict aliasing violation!
5340 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005341 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005342
Douglas Gregor23c94db2010-07-02 17:43:08 +00005343 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005344 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005345}
5346
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005347/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5348/// special functions, such as the default constructor, copy
5349/// constructor, or destructor, to the given C++ class (C++
5350/// [special]p1). This routine can only be executed just before the
5351/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005352void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005353 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005354 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005355
Richard Smithbc2a35d2012-12-08 08:32:28 +00005356 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005357 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005358
Richard Smithbc2a35d2012-12-08 08:32:28 +00005359 // If the properties or semantics of the copy constructor couldn't be
5360 // determined while the class was being declared, force a declaration
5361 // of it now.
5362 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5363 DeclareImplicitCopyConstructor(ClassDecl);
5364 }
5365
Richard Smith80ad52f2013-01-02 11:42:31 +00005366 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005367 ++ASTContext::NumImplicitMoveConstructors;
5368
Richard Smithbc2a35d2012-12-08 08:32:28 +00005369 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5370 DeclareImplicitMoveConstructor(ClassDecl);
5371 }
5372
Douglas Gregora376d102010-07-02 21:50:04 +00005373 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5374 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005375
5376 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005377 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005378 // it shows up in the right place in the vtable and that we diagnose
5379 // problems with the implicit exception specification.
5380 if (ClassDecl->isDynamicClass() ||
5381 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005382 DeclareImplicitCopyAssignment(ClassDecl);
5383 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005384
Richard Smith80ad52f2013-01-02 11:42:31 +00005385 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005386 ++ASTContext::NumImplicitMoveAssignmentOperators;
5387
5388 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005389 if (ClassDecl->isDynamicClass() ||
5390 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005391 DeclareImplicitMoveAssignment(ClassDecl);
5392 }
5393
Douglas Gregor4923aa22010-07-02 20:37:36 +00005394 if (!ClassDecl->hasUserDeclaredDestructor()) {
5395 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005396
5397 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005398 // have to declare the destructor immediately. This ensures that, e.g., it
5399 // shows up in the right place in the vtable and that we diagnose problems
5400 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005401 if (ClassDecl->isDynamicClass() ||
5402 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005403 DeclareImplicitDestructor(ClassDecl);
5404 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005405}
5406
Francois Pichet8387e2a2011-04-22 22:18:13 +00005407void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5408 if (!D)
5409 return;
5410
5411 int NumParamList = D->getNumTemplateParameterLists();
5412 for (int i = 0; i < NumParamList; i++) {
5413 TemplateParameterList* Params = D->getTemplateParameterList(i);
5414 for (TemplateParameterList::iterator Param = Params->begin(),
5415 ParamEnd = Params->end();
5416 Param != ParamEnd; ++Param) {
5417 NamedDecl *Named = cast<NamedDecl>(*Param);
5418 if (Named->getDeclName()) {
5419 S->AddDecl(Named);
5420 IdResolver.AddDecl(Named);
5421 }
5422 }
5423 }
5424}
5425
John McCalld226f652010-08-21 09:40:31 +00005426void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005427 if (!D)
5428 return;
5429
5430 TemplateParameterList *Params = 0;
5431 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5432 Params = Template->getTemplateParameters();
5433 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5434 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5435 Params = PartialSpec->getTemplateParameters();
5436 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005437 return;
5438
Douglas Gregor6569d682009-05-27 23:11:45 +00005439 for (TemplateParameterList::iterator Param = Params->begin(),
5440 ParamEnd = Params->end();
5441 Param != ParamEnd; ++Param) {
5442 NamedDecl *Named = cast<NamedDecl>(*Param);
5443 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005444 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005445 IdResolver.AddDecl(Named);
5446 }
5447 }
5448}
5449
John McCalld226f652010-08-21 09:40:31 +00005450void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005451 if (!RecordD) return;
5452 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005453 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005454 PushDeclContext(S, Record);
5455}
5456
John McCalld226f652010-08-21 09:40:31 +00005457void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005458 if (!RecordD) return;
5459 PopDeclContext();
5460}
5461
Douglas Gregor72b505b2008-12-16 21:30:33 +00005462/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5463/// parsing a top-level (non-nested) C++ class, and we are now
5464/// parsing those parts of the given Method declaration that could
5465/// not be parsed earlier (C++ [class.mem]p2), such as default
5466/// arguments. This action should enter the scope of the given
5467/// Method declaration as if we had just parsed the qualified method
5468/// name. However, it should not bring the parameters into scope;
5469/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005470void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005471}
5472
5473/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5474/// C++ method declaration. We're (re-)introducing the given
5475/// function parameter into scope for use in parsing later parts of
5476/// the method declaration. For example, we could see an
5477/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005478void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005479 if (!ParamD)
5480 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005481
John McCalld226f652010-08-21 09:40:31 +00005482 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005483
5484 // If this parameter has an unparsed default argument, clear it out
5485 // to make way for the parsed default argument.
5486 if (Param->hasUnparsedDefaultArg())
5487 Param->setDefaultArg(0);
5488
John McCalld226f652010-08-21 09:40:31 +00005489 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005490 if (Param->getDeclName())
5491 IdResolver.AddDecl(Param);
5492}
5493
5494/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5495/// processing the delayed method declaration for Method. The method
5496/// declaration is now considered finished. There may be a separate
5497/// ActOnStartOfFunctionDef action later (not necessarily
5498/// immediately!) for this method, if it was also defined inside the
5499/// class body.
John McCalld226f652010-08-21 09:40:31 +00005500void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005501 if (!MethodD)
5502 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005503
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005504 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005505
John McCalld226f652010-08-21 09:40:31 +00005506 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005507
5508 // Now that we have our default arguments, check the constructor
5509 // again. It could produce additional diagnostics or affect whether
5510 // the class has implicitly-declared destructors, among other
5511 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005512 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5513 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005514
5515 // Check the default arguments, which we may have added.
5516 if (!Method->isInvalidDecl())
5517 CheckCXXDefaultArguments(Method);
5518}
5519
Douglas Gregor42a552f2008-11-05 20:51:48 +00005520/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005521/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005522/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005523/// emit diagnostics and set the invalid bit to true. In any case, the type
5524/// will be updated to reflect a well-formed type for the constructor and
5525/// returned.
5526QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005527 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005528 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005529
5530 // C++ [class.ctor]p3:
5531 // A constructor shall not be virtual (10.3) or static (9.4). A
5532 // constructor can be invoked for a const, volatile or const
5533 // volatile object. A constructor shall not be declared const,
5534 // volatile, or const volatile (9.3.2).
5535 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005536 if (!D.isInvalidType())
5537 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5538 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5539 << SourceRange(D.getIdentifierLoc());
5540 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005541 }
John McCalld931b082010-08-26 03:08:43 +00005542 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005543 if (!D.isInvalidType())
5544 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5545 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5546 << SourceRange(D.getIdentifierLoc());
5547 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005548 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005549 }
Mike Stump1eb44332009-09-09 15:08:12 +00005550
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005551 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005552 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005553 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005554 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5555 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005556 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005557 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5558 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005559 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005560 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5561 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005562 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005563 }
Mike Stump1eb44332009-09-09 15:08:12 +00005564
Douglas Gregorc938c162011-01-26 05:01:58 +00005565 // C++0x [class.ctor]p4:
5566 // A constructor shall not be declared with a ref-qualifier.
5567 if (FTI.hasRefQualifier()) {
5568 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5569 << FTI.RefQualifierIsLValueRef
5570 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5571 D.setInvalidType();
5572 }
5573
Douglas Gregor42a552f2008-11-05 20:51:48 +00005574 // Rebuild the function type "R" without any type qualifiers (in
5575 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005576 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005577 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005578 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5579 return R;
5580
5581 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5582 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005583 EPI.RefQualifier = RQ_None;
5584
Chris Lattner65401802009-04-25 08:28:21 +00005585 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005586 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005587}
5588
Douglas Gregor72b505b2008-12-16 21:30:33 +00005589/// CheckConstructor - Checks a fully-formed constructor for
5590/// well-formedness, issuing any diagnostics required. Returns true if
5591/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005592void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005593 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005594 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5595 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005596 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005597
5598 // C++ [class.copy]p3:
5599 // A declaration of a constructor for a class X is ill-formed if
5600 // its first parameter is of type (optionally cv-qualified) X and
5601 // either there are no other parameters or else all other
5602 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005603 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005604 ((Constructor->getNumParams() == 1) ||
5605 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005606 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5607 Constructor->getTemplateSpecializationKind()
5608 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005609 QualType ParamType = Constructor->getParamDecl(0)->getType();
5610 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5611 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005612 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005613 const char *ConstRef
5614 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5615 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005616 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005617 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005618
5619 // FIXME: Rather that making the constructor invalid, we should endeavor
5620 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005621 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005622 }
5623 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005624}
5625
John McCall15442822010-08-04 01:04:25 +00005626/// CheckDestructor - Checks a fully-formed destructor definition for
5627/// well-formedness, issuing any diagnostics required. Returns true
5628/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005629bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005630 CXXRecordDecl *RD = Destructor->getParent();
5631
5632 if (Destructor->isVirtual()) {
5633 SourceLocation Loc;
5634
5635 if (!Destructor->isImplicit())
5636 Loc = Destructor->getLocation();
5637 else
5638 Loc = RD->getLocation();
5639
5640 // If we have a virtual destructor, look up the deallocation function
5641 FunctionDecl *OperatorDelete = 0;
5642 DeclarationName Name =
5643 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005644 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005645 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005646
Eli Friedman5f2987c2012-02-02 03:46:19 +00005647 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005648
5649 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005650 }
Anders Carlsson37909802009-11-30 21:24:50 +00005651
5652 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005653}
5654
Mike Stump1eb44332009-09-09 15:08:12 +00005655static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005656FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5657 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5658 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005659 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005660}
5661
Douglas Gregor42a552f2008-11-05 20:51:48 +00005662/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5663/// the well-formednes of the destructor declarator @p D with type @p
5664/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005665/// emit diagnostics and set the declarator to invalid. Even if this happens,
5666/// will be updated to reflect a well-formed type for the destructor and
5667/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005668QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005669 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005670 // C++ [class.dtor]p1:
5671 // [...] A typedef-name that names a class is a class-name
5672 // (7.1.3); however, a typedef-name that names a class shall not
5673 // be used as the identifier in the declarator for a destructor
5674 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005675 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005676 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005677 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005678 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005679 else if (const TemplateSpecializationType *TST =
5680 DeclaratorType->getAs<TemplateSpecializationType>())
5681 if (TST->isTypeAlias())
5682 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5683 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005684
5685 // C++ [class.dtor]p2:
5686 // A destructor is used to destroy objects of its class type. A
5687 // destructor takes no parameters, and no return type can be
5688 // specified for it (not even void). The address of a destructor
5689 // shall not be taken. A destructor shall not be static. A
5690 // destructor can be invoked for a const, volatile or const
5691 // volatile object. A destructor shall not be declared const,
5692 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005693 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005694 if (!D.isInvalidType())
5695 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5696 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005697 << SourceRange(D.getIdentifierLoc())
5698 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5699
John McCalld931b082010-08-26 03:08:43 +00005700 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005701 }
Chris Lattner65401802009-04-25 08:28:21 +00005702 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005703 // Destructors don't have return types, but the parser will
5704 // happily parse something like:
5705 //
5706 // class X {
5707 // float ~X();
5708 // };
5709 //
5710 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005711 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5712 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5713 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005714 }
Mike Stump1eb44332009-09-09 15:08:12 +00005715
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005716 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005717 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005718 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005719 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5720 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005721 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005722 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5723 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005724 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005725 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5726 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005727 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005728 }
5729
Douglas Gregorc938c162011-01-26 05:01:58 +00005730 // C++0x [class.dtor]p2:
5731 // A destructor shall not be declared with a ref-qualifier.
5732 if (FTI.hasRefQualifier()) {
5733 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5734 << FTI.RefQualifierIsLValueRef
5735 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5736 D.setInvalidType();
5737 }
5738
Douglas Gregor42a552f2008-11-05 20:51:48 +00005739 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005740 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005741 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5742
5743 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005744 FTI.freeArgs();
5745 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005746 }
5747
Mike Stump1eb44332009-09-09 15:08:12 +00005748 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005749 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005750 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005751 D.setInvalidType();
5752 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005753
5754 // Rebuild the function type "R" without any type qualifiers or
5755 // parameters (in case any of the errors above fired) and with
5756 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005757 // types.
John McCalle23cf432010-12-14 08:05:40 +00005758 if (!D.isInvalidType())
5759 return R;
5760
Douglas Gregord92ec472010-07-01 05:10:53 +00005761 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005762 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5763 EPI.Variadic = false;
5764 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005765 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005766 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005767}
5768
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005769/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5770/// well-formednes of the conversion function declarator @p D with
5771/// type @p R. If there are any errors in the declarator, this routine
5772/// will emit diagnostics and return true. Otherwise, it will return
5773/// false. Either way, the type @p R will be updated to reflect a
5774/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005775void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005776 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005777 // C++ [class.conv.fct]p1:
5778 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005779 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005780 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005781 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005782 if (!D.isInvalidType())
5783 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5784 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5785 << SourceRange(D.getIdentifierLoc());
5786 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005787 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005788 }
John McCalla3f81372010-04-13 00:04:31 +00005789
5790 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5791
Chris Lattner6e475012009-04-25 08:35:12 +00005792 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005793 // Conversion functions don't have return types, but the parser will
5794 // happily parse something like:
5795 //
5796 // class X {
5797 // float operator bool();
5798 // };
5799 //
5800 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005801 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5802 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5803 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005804 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005805 }
5806
John McCalla3f81372010-04-13 00:04:31 +00005807 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5808
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005809 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005810 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005811 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5812
5813 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005814 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005815 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005816 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005817 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005818 D.setInvalidType();
5819 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005820
John McCalla3f81372010-04-13 00:04:31 +00005821 // Diagnose "&operator bool()" and other such nonsense. This
5822 // is actually a gcc extension which we don't support.
5823 if (Proto->getResultType() != ConvType) {
5824 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5825 << Proto->getResultType();
5826 D.setInvalidType();
5827 ConvType = Proto->getResultType();
5828 }
5829
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005830 // C++ [class.conv.fct]p4:
5831 // The conversion-type-id shall not represent a function type nor
5832 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005833 if (ConvType->isArrayType()) {
5834 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5835 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005836 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005837 } else if (ConvType->isFunctionType()) {
5838 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5839 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005840 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005841 }
5842
5843 // Rebuild the function type "R" without any parameters (in case any
5844 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005845 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005846 if (D.isInvalidType())
5847 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005848
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005849 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005850 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005851 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005852 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005853 diag::warn_cxx98_compat_explicit_conversion_functions :
5854 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005855 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005856}
5857
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005858/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5859/// the declaration of the given C++ conversion function. This routine
5860/// is responsible for recording the conversion function in the C++
5861/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005862Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005863 assert(Conversion && "Expected to receive a conversion function declaration");
5864
Douglas Gregor9d350972008-12-12 08:25:50 +00005865 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005866
5867 // Make sure we aren't redeclaring the conversion function.
5868 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005869
5870 // C++ [class.conv.fct]p1:
5871 // [...] A conversion function is never used to convert a
5872 // (possibly cv-qualified) object to the (possibly cv-qualified)
5873 // same object type (or a reference to it), to a (possibly
5874 // cv-qualified) base class of that type (or a reference to it),
5875 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005876 // FIXME: Suppress this warning if the conversion function ends up being a
5877 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005878 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005879 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005880 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005881 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005882 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5883 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005884 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005885 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005886 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5887 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005888 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005889 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005890 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005891 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005892 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005893 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005894 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005895 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005896 }
5897
Douglas Gregore80622f2010-09-29 04:25:11 +00005898 if (FunctionTemplateDecl *ConversionTemplate
5899 = Conversion->getDescribedFunctionTemplate())
5900 return ConversionTemplate;
5901
John McCalld226f652010-08-21 09:40:31 +00005902 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005903}
5904
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005905//===----------------------------------------------------------------------===//
5906// Namespace Handling
5907//===----------------------------------------------------------------------===//
5908
Richard Smithd1a55a62012-10-04 22:13:39 +00005909/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
5910/// reopened.
5911static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
5912 SourceLocation Loc,
5913 IdentifierInfo *II, bool *IsInline,
5914 NamespaceDecl *PrevNS) {
5915 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00005916
Richard Smithc969e6a2012-10-05 01:46:25 +00005917 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
5918 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
5919 // inline namespaces, with the intention of bringing names into namespace std.
5920 //
5921 // We support this just well enough to get that case working; this is not
5922 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00005923 if (*IsInline && II && II->getName().startswith("__atomic") &&
5924 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00005925 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00005926 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
5927 NS = NS->getPreviousDecl())
5928 NS->setInline(*IsInline);
5929 // Patch up the lookup table for the containing namespace. This isn't really
5930 // correct, but it's good enough for this particular case.
5931 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
5932 E = PrevNS->decls_end(); I != E; ++I)
5933 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
5934 PrevNS->getParent()->makeDeclVisibleInContext(ND);
5935 return;
5936 }
5937
5938 if (PrevNS->isInline())
5939 // The user probably just forgot the 'inline', so suggest that it
5940 // be added back.
5941 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5942 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
5943 else
5944 S.Diag(Loc, diag::err_inline_namespace_mismatch)
5945 << IsInline;
5946
5947 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
5948 *IsInline = PrevNS->isInline();
5949}
John McCallea318642010-08-26 09:15:37 +00005950
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005951/// ActOnStartNamespaceDef - This is called at the start of a namespace
5952/// definition.
John McCalld226f652010-08-21 09:40:31 +00005953Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005954 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005955 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005956 SourceLocation IdentLoc,
5957 IdentifierInfo *II,
5958 SourceLocation LBrace,
5959 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005960 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5961 // For anonymous namespace, take the location of the left brace.
5962 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005963 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005964 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005965 bool IsStd = false;
5966 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005967 Scope *DeclRegionScope = NamespcScope->getParent();
5968
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005969 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005970 if (II) {
5971 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005972 // The identifier in an original-namespace-definition shall not
5973 // have been previously defined in the declarative region in
5974 // which the original-namespace-definition appears. The
5975 // identifier in an original-namespace-definition is the name of
5976 // the namespace. Subsequently in that declarative region, it is
5977 // treated as an original-namespace-name.
5978 //
5979 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005980 // look through using directives, just look for any ordinary names.
5981
5982 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005983 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5984 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005985 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00005986 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
5987 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5988 ++I) {
5989 if ((*I)->getIdentifierNamespace() & IDNS) {
5990 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00005991 break;
5992 }
5993 }
5994
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005995 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5996
5997 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005998 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00005999 if (IsInline != PrevNS->isInline())
6000 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6001 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006002 } else if (PrevDecl) {
6003 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006004 Diag(Loc, diag::err_redefinition_different_kind)
6005 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006006 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006007 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006008 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006009 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006010 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006011 // This is the first "real" definition of the namespace "std", so update
6012 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006013 PrevNS = getStdNamespace();
6014 IsStd = true;
6015 AddToKnown = !IsInline;
6016 } else {
6017 // We've seen this namespace for the first time.
6018 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006019 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006020 } else {
John McCall9aeed322009-10-01 00:25:31 +00006021 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006022
6023 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006024 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006025 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006026 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006027 } else {
6028 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006029 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006030 }
6031
Richard Smithd1a55a62012-10-04 22:13:39 +00006032 if (PrevNS && IsInline != PrevNS->isInline())
6033 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6034 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006035 }
6036
6037 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6038 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006039 if (IsInvalid)
6040 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006041
6042 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006043
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006044 // FIXME: Should we be merging attributes?
6045 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006046 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006047
6048 if (IsStd)
6049 StdNamespace = Namespc;
6050 if (AddToKnown)
6051 KnownNamespaces[Namespc] = false;
6052
6053 if (II) {
6054 PushOnScopeChains(Namespc, DeclRegionScope);
6055 } else {
6056 // Link the anonymous namespace into its parent.
6057 DeclContext *Parent = CurContext->getRedeclContext();
6058 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6059 TU->setAnonymousNamespace(Namespc);
6060 } else {
6061 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006062 }
John McCall9aeed322009-10-01 00:25:31 +00006063
Douglas Gregora4181472010-03-24 00:46:35 +00006064 CurContext->addDecl(Namespc);
6065
John McCall9aeed322009-10-01 00:25:31 +00006066 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6067 // behaves as if it were replaced by
6068 // namespace unique { /* empty body */ }
6069 // using namespace unique;
6070 // namespace unique { namespace-body }
6071 // where all occurrences of 'unique' in a translation unit are
6072 // replaced by the same identifier and this identifier differs
6073 // from all other identifiers in the entire program.
6074
6075 // We just create the namespace with an empty name and then add an
6076 // implicit using declaration, just like the standard suggests.
6077 //
6078 // CodeGen enforces the "universally unique" aspect by giving all
6079 // declarations semantically contained within an anonymous
6080 // namespace internal linkage.
6081
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006082 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006083 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006084 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006085 /* 'using' */ LBrace,
6086 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006087 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006088 /* identifier */ SourceLocation(),
6089 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006090 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006091 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006092 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006093 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006094 }
6095
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006096 ActOnDocumentableDecl(Namespc);
6097
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006098 // Although we could have an invalid decl (i.e. the namespace name is a
6099 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006100 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6101 // for the namespace has the declarations that showed up in that particular
6102 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006103 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006104 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006105}
6106
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006107/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6108/// is a namespace alias, returns the namespace it points to.
6109static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6110 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6111 return AD->getNamespace();
6112 return dyn_cast_or_null<NamespaceDecl>(D);
6113}
6114
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006115/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6116/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006117void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006118 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6119 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006120 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006121 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006122 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006123 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006124}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006125
John McCall384aff82010-08-25 07:42:41 +00006126CXXRecordDecl *Sema::getStdBadAlloc() const {
6127 return cast_or_null<CXXRecordDecl>(
6128 StdBadAlloc.get(Context.getExternalSource()));
6129}
6130
6131NamespaceDecl *Sema::getStdNamespace() const {
6132 return cast_or_null<NamespaceDecl>(
6133 StdNamespace.get(Context.getExternalSource()));
6134}
6135
Douglas Gregor66992202010-06-29 17:53:46 +00006136/// \brief Retrieve the special "std" namespace, which may require us to
6137/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006138NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006139 if (!StdNamespace) {
6140 // The "std" namespace has not yet been defined, so build one implicitly.
6141 StdNamespace = NamespaceDecl::Create(Context,
6142 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006143 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006144 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006145 &PP.getIdentifierTable().get("std"),
6146 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006147 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006148 }
6149
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006150 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006151}
6152
Sebastian Redl395e04d2012-01-17 22:49:33 +00006153bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006154 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006155 "Looking for std::initializer_list outside of C++.");
6156
6157 // We're looking for implicit instantiations of
6158 // template <typename E> class std::initializer_list.
6159
6160 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6161 return false;
6162
Sebastian Redl84760e32012-01-17 22:49:58 +00006163 ClassTemplateDecl *Template = 0;
6164 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006165
Sebastian Redl84760e32012-01-17 22:49:58 +00006166 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006167
Sebastian Redl84760e32012-01-17 22:49:58 +00006168 ClassTemplateSpecializationDecl *Specialization =
6169 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6170 if (!Specialization)
6171 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006172
Sebastian Redl84760e32012-01-17 22:49:58 +00006173 Template = Specialization->getSpecializedTemplate();
6174 Arguments = Specialization->getTemplateArgs().data();
6175 } else if (const TemplateSpecializationType *TST =
6176 Ty->getAs<TemplateSpecializationType>()) {
6177 Template = dyn_cast_or_null<ClassTemplateDecl>(
6178 TST->getTemplateName().getAsTemplateDecl());
6179 Arguments = TST->getArgs();
6180 }
6181 if (!Template)
6182 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006183
6184 if (!StdInitializerList) {
6185 // Haven't recognized std::initializer_list yet, maybe this is it.
6186 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6187 if (TemplateClass->getIdentifier() !=
6188 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006189 !getStdNamespace()->InEnclosingNamespaceSetOf(
6190 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006191 return false;
6192 // This is a template called std::initializer_list, but is it the right
6193 // template?
6194 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006195 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006196 return false;
6197 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6198 return false;
6199
6200 // It's the right template.
6201 StdInitializerList = Template;
6202 }
6203
6204 if (Template != StdInitializerList)
6205 return false;
6206
6207 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006208 if (Element)
6209 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006210 return true;
6211}
6212
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006213static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6214 NamespaceDecl *Std = S.getStdNamespace();
6215 if (!Std) {
6216 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6217 return 0;
6218 }
6219
6220 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6221 Loc, Sema::LookupOrdinaryName);
6222 if (!S.LookupQualifiedName(Result, Std)) {
6223 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6224 return 0;
6225 }
6226 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6227 if (!Template) {
6228 Result.suppressDiagnostics();
6229 // We found something weird. Complain about the first thing we found.
6230 NamedDecl *Found = *Result.begin();
6231 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6232 return 0;
6233 }
6234
6235 // We found some template called std::initializer_list. Now verify that it's
6236 // correct.
6237 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006238 if (Params->getMinRequiredArguments() != 1 ||
6239 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006240 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6241 return 0;
6242 }
6243
6244 return Template;
6245}
6246
6247QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6248 if (!StdInitializerList) {
6249 StdInitializerList = LookupStdInitializerList(*this, Loc);
6250 if (!StdInitializerList)
6251 return QualType();
6252 }
6253
6254 TemplateArgumentListInfo Args(Loc, Loc);
6255 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6256 Context.getTrivialTypeSourceInfo(Element,
6257 Loc)));
6258 return Context.getCanonicalType(
6259 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6260}
6261
Sebastian Redl98d36062012-01-17 22:50:14 +00006262bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6263 // C++ [dcl.init.list]p2:
6264 // A constructor is an initializer-list constructor if its first parameter
6265 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6266 // std::initializer_list<E> for some type E, and either there are no other
6267 // parameters or else all other parameters have default arguments.
6268 if (Ctor->getNumParams() < 1 ||
6269 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6270 return false;
6271
6272 QualType ArgType = Ctor->getParamDecl(0)->getType();
6273 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6274 ArgType = RT->getPointeeType().getUnqualifiedType();
6275
6276 return isStdInitializerList(ArgType, 0);
6277}
6278
Douglas Gregor9172aa62011-03-26 22:25:30 +00006279/// \brief Determine whether a using statement is in a context where it will be
6280/// apply in all contexts.
6281static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6282 switch (CurContext->getDeclKind()) {
6283 case Decl::TranslationUnit:
6284 return true;
6285 case Decl::LinkageSpec:
6286 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6287 default:
6288 return false;
6289 }
6290}
6291
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006292namespace {
6293
6294// Callback to only accept typo corrections that are namespaces.
6295class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6296 public:
6297 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6298 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6299 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6300 }
6301 return false;
6302 }
6303};
6304
6305}
6306
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006307static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6308 CXXScopeSpec &SS,
6309 SourceLocation IdentLoc,
6310 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006311 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006312 R.clear();
6313 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006314 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006315 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006316 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6317 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006318 if (DeclContext *DC = S.computeDeclContext(SS, false))
6319 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6320 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006321 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6322 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006323 else
6324 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6325 << Ident << CorrectedQuotedStr
6326 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006327
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006328 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6329 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006330
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006331 R.addDecl(Corrected.getCorrectionDecl());
6332 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006333 }
6334 return false;
6335}
6336
John McCalld226f652010-08-21 09:40:31 +00006337Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006338 SourceLocation UsingLoc,
6339 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006340 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006341 SourceLocation IdentLoc,
6342 IdentifierInfo *NamespcName,
6343 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006344 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6345 assert(NamespcName && "Invalid NamespcName.");
6346 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006347
6348 // This can only happen along a recovery path.
6349 while (S->getFlags() & Scope::TemplateParamScope)
6350 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006351 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006352
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006353 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006354 NestedNameSpecifier *Qualifier = 0;
6355 if (SS.isSet())
6356 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6357
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006358 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006359 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6360 LookupParsedName(R, S, &SS);
6361 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006362 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006363
Douglas Gregor66992202010-06-29 17:53:46 +00006364 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006365 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006366 // Allow "using namespace std;" or "using namespace ::std;" even if
6367 // "std" hasn't been defined yet, for GCC compatibility.
6368 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6369 NamespcName->isStr("std")) {
6370 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006371 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006372 R.resolveKind();
6373 }
6374 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006375 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006376 }
6377
John McCallf36e02d2009-10-09 21:13:30 +00006378 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006379 NamedDecl *Named = R.getFoundDecl();
6380 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6381 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006382 // C++ [namespace.udir]p1:
6383 // A using-directive specifies that the names in the nominated
6384 // namespace can be used in the scope in which the
6385 // using-directive appears after the using-directive. During
6386 // unqualified name lookup (3.4.1), the names appear as if they
6387 // were declared in the nearest enclosing namespace which
6388 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006389 // namespace. [Note: in this context, "contains" means "contains
6390 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006391
6392 // Find enclosing context containing both using-directive and
6393 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006394 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006395 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6396 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6397 CommonAncestor = CommonAncestor->getParent();
6398
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006399 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006400 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006401 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006402
Douglas Gregor9172aa62011-03-26 22:25:30 +00006403 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006404 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006405 Diag(IdentLoc, diag::warn_using_directive_in_header);
6406 }
6407
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006408 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006409 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006410 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006411 }
6412
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006413 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006414 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006415}
6416
6417void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006418 // If the scope has an associated entity and the using directive is at
6419 // namespace or translation unit scope, add the UsingDirectiveDecl into
6420 // its lookup structure so qualified name lookup can find it.
6421 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6422 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006423 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006424 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006425 // Otherwise, it is at block sope. The using-directives will affect lookup
6426 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006427 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006428}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006429
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006430
John McCalld226f652010-08-21 09:40:31 +00006431Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006432 AccessSpecifier AS,
6433 bool HasUsingKeyword,
6434 SourceLocation UsingLoc,
6435 CXXScopeSpec &SS,
6436 UnqualifiedId &Name,
6437 AttributeList *AttrList,
6438 bool IsTypeName,
6439 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006440 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006441
Douglas Gregor12c118a2009-11-04 16:30:06 +00006442 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006443 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006444 case UnqualifiedId::IK_Identifier:
6445 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006446 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006447 case UnqualifiedId::IK_ConversionFunctionId:
6448 break;
6449
6450 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006451 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006452 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006453 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006454 getLangOpts().CPlusPlus11 ?
Richard Smitha1366cb2012-04-27 19:33:05 +00006455 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
6456 // instead once inheriting constructors work.
6457 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00006458 diag::err_using_decl_constructor)
6459 << SS.getRange();
6460
Richard Smith80ad52f2013-01-02 11:42:31 +00006461 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006462
John McCalld226f652010-08-21 09:40:31 +00006463 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006464
6465 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006466 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006467 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006468 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006469
6470 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006471 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006472 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006473 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006474 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006475
6476 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6477 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006478 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006479 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006480
John McCall60fa3cf2009-12-11 02:10:03 +00006481 // Warn about using declarations.
6482 // TODO: store that the declaration was written without 'using' and
6483 // talk about access decls instead of using decls in the
6484 // diagnostics.
6485 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006486 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006487
6488 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006489 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006490 }
6491
Douglas Gregor56c04582010-12-16 00:46:58 +00006492 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6493 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6494 return 0;
6495
John McCall9488ea12009-11-17 05:59:44 +00006496 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006497 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006498 /* IsInstantiation */ false,
6499 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006500 if (UD)
6501 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006502
John McCalld226f652010-08-21 09:40:31 +00006503 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006504}
6505
Douglas Gregor09acc982010-07-07 23:08:52 +00006506/// \brief Determine whether a using declaration considers the given
6507/// declarations as "equivalent", e.g., if they are redeclarations of
6508/// the same entity or are both typedefs of the same type.
6509static bool
6510IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6511 bool &SuppressRedeclaration) {
6512 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6513 SuppressRedeclaration = false;
6514 return true;
6515 }
6516
Richard Smith162e1c12011-04-15 14:24:37 +00006517 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6518 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006519 SuppressRedeclaration = true;
6520 return Context.hasSameType(TD1->getUnderlyingType(),
6521 TD2->getUnderlyingType());
6522 }
6523
6524 return false;
6525}
6526
6527
John McCall9f54ad42009-12-10 09:41:52 +00006528/// Determines whether to create a using shadow decl for a particular
6529/// decl, given the set of decls existing prior to this using lookup.
6530bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6531 const LookupResult &Previous) {
6532 // Diagnose finding a decl which is not from a base class of the
6533 // current class. We do this now because there are cases where this
6534 // function will silently decide not to build a shadow decl, which
6535 // will pre-empt further diagnostics.
6536 //
6537 // We don't need to do this in C++0x because we do the check once on
6538 // the qualifier.
6539 //
6540 // FIXME: diagnose the following if we care enough:
6541 // struct A { int foo; };
6542 // struct B : A { using A::foo; };
6543 // template <class T> struct C : A {};
6544 // template <class T> struct D : C<T> { using B::foo; } // <---
6545 // This is invalid (during instantiation) in C++03 because B::foo
6546 // resolves to the using decl in B, which is not a base class of D<T>.
6547 // We can't diagnose it immediately because C<T> is an unknown
6548 // specialization. The UsingShadowDecl in D<T> then points directly
6549 // to A::foo, which will look well-formed when we instantiate.
6550 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006551 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006552 DeclContext *OrigDC = Orig->getDeclContext();
6553
6554 // Handle enums and anonymous structs.
6555 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6556 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6557 while (OrigRec->isAnonymousStructOrUnion())
6558 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6559
6560 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6561 if (OrigDC == CurContext) {
6562 Diag(Using->getLocation(),
6563 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006564 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006565 Diag(Orig->getLocation(), diag::note_using_decl_target);
6566 return true;
6567 }
6568
Douglas Gregordc355712011-02-25 00:36:19 +00006569 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006570 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006571 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006572 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006573 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006574 Diag(Orig->getLocation(), diag::note_using_decl_target);
6575 return true;
6576 }
6577 }
6578
6579 if (Previous.empty()) return false;
6580
6581 NamedDecl *Target = Orig;
6582 if (isa<UsingShadowDecl>(Target))
6583 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6584
John McCalld7533ec2009-12-11 02:33:26 +00006585 // If the target happens to be one of the previous declarations, we
6586 // don't have a conflict.
6587 //
6588 // FIXME: but we might be increasing its access, in which case we
6589 // should redeclare it.
6590 NamedDecl *NonTag = 0, *Tag = 0;
6591 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6592 I != E; ++I) {
6593 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006594 bool Result;
6595 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6596 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006597
6598 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6599 }
6600
John McCall9f54ad42009-12-10 09:41:52 +00006601 if (Target->isFunctionOrFunctionTemplate()) {
6602 FunctionDecl *FD;
6603 if (isa<FunctionTemplateDecl>(Target))
6604 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6605 else
6606 FD = cast<FunctionDecl>(Target);
6607
6608 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006609 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006610 case Ovl_Overload:
6611 return false;
6612
6613 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006614 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006615 break;
6616
6617 // We found a decl with the exact signature.
6618 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006619 // If we're in a record, we want to hide the target, so we
6620 // return true (without a diagnostic) to tell the caller not to
6621 // build a shadow decl.
6622 if (CurContext->isRecord())
6623 return true;
6624
6625 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006626 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006627 break;
6628 }
6629
6630 Diag(Target->getLocation(), diag::note_using_decl_target);
6631 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6632 return true;
6633 }
6634
6635 // Target is not a function.
6636
John McCall9f54ad42009-12-10 09:41:52 +00006637 if (isa<TagDecl>(Target)) {
6638 // No conflict between a tag and a non-tag.
6639 if (!Tag) return false;
6640
John McCall41ce66f2009-12-10 19:51:03 +00006641 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006642 Diag(Target->getLocation(), diag::note_using_decl_target);
6643 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6644 return true;
6645 }
6646
6647 // No conflict between a tag and a non-tag.
6648 if (!NonTag) return false;
6649
John McCall41ce66f2009-12-10 19:51:03 +00006650 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006651 Diag(Target->getLocation(), diag::note_using_decl_target);
6652 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6653 return true;
6654}
6655
John McCall9488ea12009-11-17 05:59:44 +00006656/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006657UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006658 UsingDecl *UD,
6659 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006660
6661 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006662 NamedDecl *Target = Orig;
6663 if (isa<UsingShadowDecl>(Target)) {
6664 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6665 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006666 }
6667
6668 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006669 = UsingShadowDecl::Create(Context, CurContext,
6670 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006671 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006672
6673 Shadow->setAccess(UD->getAccess());
6674 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6675 Shadow->setInvalidDecl();
6676
John McCall9488ea12009-11-17 05:59:44 +00006677 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006678 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006679 else
John McCall604e7f12009-12-08 07:46:18 +00006680 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006681
John McCall604e7f12009-12-08 07:46:18 +00006682
John McCall9f54ad42009-12-10 09:41:52 +00006683 return Shadow;
6684}
John McCall604e7f12009-12-08 07:46:18 +00006685
John McCall9f54ad42009-12-10 09:41:52 +00006686/// Hides a using shadow declaration. This is required by the current
6687/// using-decl implementation when a resolvable using declaration in a
6688/// class is followed by a declaration which would hide or override
6689/// one or more of the using decl's targets; for example:
6690///
6691/// struct Base { void foo(int); };
6692/// struct Derived : Base {
6693/// using Base::foo;
6694/// void foo(int);
6695/// };
6696///
6697/// The governing language is C++03 [namespace.udecl]p12:
6698///
6699/// When a using-declaration brings names from a base class into a
6700/// derived class scope, member functions in the derived class
6701/// override and/or hide member functions with the same name and
6702/// parameter types in a base class (rather than conflicting).
6703///
6704/// There are two ways to implement this:
6705/// (1) optimistically create shadow decls when they're not hidden
6706/// by existing declarations, or
6707/// (2) don't create any shadow decls (or at least don't make them
6708/// visible) until we've fully parsed/instantiated the class.
6709/// The problem with (1) is that we might have to retroactively remove
6710/// a shadow decl, which requires several O(n) operations because the
6711/// decl structures are (very reasonably) not designed for removal.
6712/// (2) avoids this but is very fiddly and phase-dependent.
6713void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006714 if (Shadow->getDeclName().getNameKind() ==
6715 DeclarationName::CXXConversionFunctionName)
6716 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6717
John McCall9f54ad42009-12-10 09:41:52 +00006718 // Remove it from the DeclContext...
6719 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006720
John McCall9f54ad42009-12-10 09:41:52 +00006721 // ...and the scope, if applicable...
6722 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006723 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006724 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006725 }
6726
John McCall9f54ad42009-12-10 09:41:52 +00006727 // ...and the using decl.
6728 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6729
6730 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006731 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006732}
6733
John McCall7ba107a2009-11-18 02:36:19 +00006734/// Builds a using declaration.
6735///
6736/// \param IsInstantiation - Whether this call arises from an
6737/// instantiation of an unresolved using declaration. We treat
6738/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006739NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6740 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006741 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006742 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006743 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006744 bool IsInstantiation,
6745 bool IsTypeName,
6746 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006747 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006748 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006749 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006750
Anders Carlsson550b14b2009-08-28 05:49:21 +00006751 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006752
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006753 if (SS.isEmpty()) {
6754 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006755 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006756 }
Mike Stump1eb44332009-09-09 15:08:12 +00006757
John McCall9f54ad42009-12-10 09:41:52 +00006758 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006759 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006760 ForRedeclaration);
6761 Previous.setHideTags(false);
6762 if (S) {
6763 LookupName(Previous, S);
6764
6765 // It is really dumb that we have to do this.
6766 LookupResult::Filter F = Previous.makeFilter();
6767 while (F.hasNext()) {
6768 NamedDecl *D = F.next();
6769 if (!isDeclInScope(D, CurContext, S))
6770 F.erase();
6771 }
6772 F.done();
6773 } else {
6774 assert(IsInstantiation && "no scope in non-instantiation");
6775 assert(CurContext->isRecord() && "scope not record in instantiation");
6776 LookupQualifiedName(Previous, CurContext);
6777 }
6778
John McCall9f54ad42009-12-10 09:41:52 +00006779 // Check for invalid redeclarations.
6780 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6781 return 0;
6782
6783 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006784 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6785 return 0;
6786
John McCallaf8e6ed2009-11-12 03:15:40 +00006787 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006788 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006789 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006790 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006791 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006792 // FIXME: not all declaration name kinds are legal here
6793 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6794 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006795 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006796 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006797 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006798 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6799 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006800 }
John McCalled976492009-12-04 22:46:56 +00006801 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006802 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6803 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006804 }
John McCalled976492009-12-04 22:46:56 +00006805 D->setAccess(AS);
6806 CurContext->addDecl(D);
6807
6808 if (!LookupContext) return D;
6809 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006810
John McCall77bb1aa2010-05-01 00:40:08 +00006811 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006812 UD->setInvalidDecl();
6813 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006814 }
6815
Richard Smithc5a89a12012-04-02 01:30:27 +00006816 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006817 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006818 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006819 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006820 return UD;
6821 }
6822
6823 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006824
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006825 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006826
John McCall604e7f12009-12-08 07:46:18 +00006827 // Unlike most lookups, we don't always want to hide tag
6828 // declarations: tag names are visible through the using declaration
6829 // even if hidden by ordinary names, *except* in a dependent context
6830 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006831 if (!IsInstantiation)
6832 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006833
John McCallb9abd8722012-04-07 03:04:20 +00006834 // For the purposes of this lookup, we have a base object type
6835 // equal to that of the current context.
6836 if (CurContext->isRecord()) {
6837 R.setBaseObjectType(
6838 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6839 }
6840
John McCalla24dc2e2009-11-17 02:14:36 +00006841 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006842
John McCallf36e02d2009-10-09 21:13:30 +00006843 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006844 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006845 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006846 UD->setInvalidDecl();
6847 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006848 }
6849
John McCalled976492009-12-04 22:46:56 +00006850 if (R.isAmbiguous()) {
6851 UD->setInvalidDecl();
6852 return UD;
6853 }
Mike Stump1eb44332009-09-09 15:08:12 +00006854
John McCall7ba107a2009-11-18 02:36:19 +00006855 if (IsTypeName) {
6856 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006857 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006858 Diag(IdentLoc, diag::err_using_typename_non_type);
6859 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6860 Diag((*I)->getUnderlyingDecl()->getLocation(),
6861 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006862 UD->setInvalidDecl();
6863 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006864 }
6865 } else {
6866 // If we asked for a non-typename and we got a type, error out,
6867 // but only if this is an instantiation of an unresolved using
6868 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006869 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006870 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6871 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006872 UD->setInvalidDecl();
6873 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006874 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006875 }
6876
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006877 // C++0x N2914 [namespace.udecl]p6:
6878 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006879 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006880 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6881 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006882 UD->setInvalidDecl();
6883 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006884 }
Mike Stump1eb44332009-09-09 15:08:12 +00006885
John McCall9f54ad42009-12-10 09:41:52 +00006886 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6887 if (!CheckUsingShadowDecl(UD, *I, Previous))
6888 BuildUsingShadowDecl(S, UD, *I);
6889 }
John McCall9488ea12009-11-17 05:59:44 +00006890
6891 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006892}
6893
Sebastian Redlf677ea32011-02-05 19:23:19 +00006894/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006895bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6896 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006897
Douglas Gregordc355712011-02-25 00:36:19 +00006898 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006899 assert(SourceType &&
6900 "Using decl naming constructor doesn't have type in scope spec.");
6901 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6902
6903 // Check whether the named type is a direct base class.
6904 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6905 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6906 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6907 BaseIt != BaseE; ++BaseIt) {
6908 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6909 if (CanonicalSourceType == BaseType)
6910 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006911 if (BaseIt->getType()->isDependentType())
6912 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006913 }
6914
6915 if (BaseIt == BaseE) {
6916 // Did not find SourceType in the bases.
6917 Diag(UD->getUsingLocation(),
6918 diag::err_using_decl_constructor_not_in_direct_base)
6919 << UD->getNameInfo().getSourceRange()
6920 << QualType(SourceType, 0) << TargetClass;
6921 return true;
6922 }
6923
Richard Smithc5a89a12012-04-02 01:30:27 +00006924 if (!CurContext->isDependentContext())
6925 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006926
6927 return false;
6928}
6929
John McCall9f54ad42009-12-10 09:41:52 +00006930/// Checks that the given using declaration is not an invalid
6931/// redeclaration. Note that this is checking only for the using decl
6932/// itself, not for any ill-formedness among the UsingShadowDecls.
6933bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6934 bool isTypeName,
6935 const CXXScopeSpec &SS,
6936 SourceLocation NameLoc,
6937 const LookupResult &Prev) {
6938 // C++03 [namespace.udecl]p8:
6939 // C++0x [namespace.udecl]p10:
6940 // A using-declaration is a declaration and can therefore be used
6941 // repeatedly where (and only where) multiple declarations are
6942 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006943 //
John McCall8a726212010-11-29 18:01:58 +00006944 // That's in non-member contexts.
6945 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006946 return false;
6947
6948 NestedNameSpecifier *Qual
6949 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6950
6951 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6952 NamedDecl *D = *I;
6953
6954 bool DTypename;
6955 NestedNameSpecifier *DQual;
6956 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6957 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006958 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006959 } else if (UnresolvedUsingValueDecl *UD
6960 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6961 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006962 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006963 } else if (UnresolvedUsingTypenameDecl *UD
6964 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6965 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006966 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006967 } else continue;
6968
6969 // using decls differ if one says 'typename' and the other doesn't.
6970 // FIXME: non-dependent using decls?
6971 if (isTypeName != DTypename) continue;
6972
6973 // using decls differ if they name different scopes (but note that
6974 // template instantiation can cause this check to trigger when it
6975 // didn't before instantiation).
6976 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6977 Context.getCanonicalNestedNameSpecifier(DQual))
6978 continue;
6979
6980 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006981 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006982 return true;
6983 }
6984
6985 return false;
6986}
6987
John McCall604e7f12009-12-08 07:46:18 +00006988
John McCalled976492009-12-04 22:46:56 +00006989/// Checks that the given nested-name qualifier used in a using decl
6990/// in the current context is appropriately related to the current
6991/// scope. If an error is found, diagnoses it and returns true.
6992bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6993 const CXXScopeSpec &SS,
6994 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006995 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006996
John McCall604e7f12009-12-08 07:46:18 +00006997 if (!CurContext->isRecord()) {
6998 // C++03 [namespace.udecl]p3:
6999 // C++0x [namespace.udecl]p8:
7000 // A using-declaration for a class member shall be a member-declaration.
7001
7002 // If we weren't able to compute a valid scope, it must be a
7003 // dependent class scope.
7004 if (!NamedContext || NamedContext->isRecord()) {
7005 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7006 << SS.getRange();
7007 return true;
7008 }
7009
7010 // Otherwise, everything is known to be fine.
7011 return false;
7012 }
7013
7014 // The current scope is a record.
7015
7016 // If the named context is dependent, we can't decide much.
7017 if (!NamedContext) {
7018 // FIXME: in C++0x, we can diagnose if we can prove that the
7019 // nested-name-specifier does not refer to a base class, which is
7020 // still possible in some cases.
7021
7022 // Otherwise we have to conservatively report that things might be
7023 // okay.
7024 return false;
7025 }
7026
7027 if (!NamedContext->isRecord()) {
7028 // Ideally this would point at the last name in the specifier,
7029 // but we don't have that level of source info.
7030 Diag(SS.getRange().getBegin(),
7031 diag::err_using_decl_nested_name_specifier_is_not_class)
7032 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7033 return true;
7034 }
7035
Douglas Gregor6fb07292010-12-21 07:41:49 +00007036 if (!NamedContext->isDependentContext() &&
7037 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7038 return true;
7039
Richard Smith80ad52f2013-01-02 11:42:31 +00007040 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007041 // C++0x [namespace.udecl]p3:
7042 // In a using-declaration used as a member-declaration, the
7043 // nested-name-specifier shall name a base class of the class
7044 // being defined.
7045
7046 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7047 cast<CXXRecordDecl>(NamedContext))) {
7048 if (CurContext == NamedContext) {
7049 Diag(NameLoc,
7050 diag::err_using_decl_nested_name_specifier_is_current_class)
7051 << SS.getRange();
7052 return true;
7053 }
7054
7055 Diag(SS.getRange().getBegin(),
7056 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7057 << (NestedNameSpecifier*) SS.getScopeRep()
7058 << cast<CXXRecordDecl>(CurContext)
7059 << SS.getRange();
7060 return true;
7061 }
7062
7063 return false;
7064 }
7065
7066 // C++03 [namespace.udecl]p4:
7067 // A using-declaration used as a member-declaration shall refer
7068 // to a member of a base class of the class being defined [etc.].
7069
7070 // Salient point: SS doesn't have to name a base class as long as
7071 // lookup only finds members from base classes. Therefore we can
7072 // diagnose here only if we can prove that that can't happen,
7073 // i.e. if the class hierarchies provably don't intersect.
7074
7075 // TODO: it would be nice if "definitely valid" results were cached
7076 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7077 // need to be repeated.
7078
7079 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007080 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007081
7082 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7083 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7084 Data->Bases.insert(Base);
7085 return true;
7086 }
7087
7088 bool hasDependentBases(const CXXRecordDecl *Class) {
7089 return !Class->forallBases(collect, this);
7090 }
7091
7092 /// Returns true if the base is dependent or is one of the
7093 /// accumulated base classes.
7094 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7095 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7096 return !Data->Bases.count(Base);
7097 }
7098
7099 bool mightShareBases(const CXXRecordDecl *Class) {
7100 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7101 }
7102 };
7103
7104 UserData Data;
7105
7106 // Returns false if we find a dependent base.
7107 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7108 return false;
7109
7110 // Returns false if the class has a dependent base or if it or one
7111 // of its bases is present in the base set of the current context.
7112 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7113 return false;
7114
7115 Diag(SS.getRange().getBegin(),
7116 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7117 << (NestedNameSpecifier*) SS.getScopeRep()
7118 << cast<CXXRecordDecl>(CurContext)
7119 << SS.getRange();
7120
7121 return true;
John McCalled976492009-12-04 22:46:56 +00007122}
7123
Richard Smith162e1c12011-04-15 14:24:37 +00007124Decl *Sema::ActOnAliasDeclaration(Scope *S,
7125 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007126 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007127 SourceLocation UsingLoc,
7128 UnqualifiedId &Name,
7129 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007130 // Skip up to the relevant declaration scope.
7131 while (S->getFlags() & Scope::TemplateParamScope)
7132 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007133 assert((S->getFlags() & Scope::DeclScope) &&
7134 "got alias-declaration outside of declaration scope");
7135
7136 if (Type.isInvalid())
7137 return 0;
7138
7139 bool Invalid = false;
7140 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7141 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007142 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007143
7144 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7145 return 0;
7146
7147 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007148 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007149 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007150 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7151 TInfo->getTypeLoc().getBeginLoc());
7152 }
Richard Smith162e1c12011-04-15 14:24:37 +00007153
7154 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7155 LookupName(Previous, S);
7156
7157 // Warn about shadowing the name of a template parameter.
7158 if (Previous.isSingleResult() &&
7159 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007160 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007161 Previous.clear();
7162 }
7163
7164 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7165 "name in alias declaration must be an identifier");
7166 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7167 Name.StartLocation,
7168 Name.Identifier, TInfo);
7169
7170 NewTD->setAccess(AS);
7171
7172 if (Invalid)
7173 NewTD->setInvalidDecl();
7174
Richard Smith3e4c6c42011-05-05 21:57:07 +00007175 CheckTypedefForVariablyModifiedType(S, NewTD);
7176 Invalid |= NewTD->isInvalidDecl();
7177
Richard Smith162e1c12011-04-15 14:24:37 +00007178 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007179
7180 NamedDecl *NewND;
7181 if (TemplateParamLists.size()) {
7182 TypeAliasTemplateDecl *OldDecl = 0;
7183 TemplateParameterList *OldTemplateParams = 0;
7184
7185 if (TemplateParamLists.size() != 1) {
7186 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007187 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7188 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007189 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007190 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007191
7192 // Only consider previous declarations in the same scope.
7193 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7194 /*ExplicitInstantiationOrSpecialization*/false);
7195 if (!Previous.empty()) {
7196 Redeclaration = true;
7197
7198 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7199 if (!OldDecl && !Invalid) {
7200 Diag(UsingLoc, diag::err_redefinition_different_kind)
7201 << Name.Identifier;
7202
7203 NamedDecl *OldD = Previous.getRepresentativeDecl();
7204 if (OldD->getLocation().isValid())
7205 Diag(OldD->getLocation(), diag::note_previous_definition);
7206
7207 Invalid = true;
7208 }
7209
7210 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7211 if (TemplateParameterListsAreEqual(TemplateParams,
7212 OldDecl->getTemplateParameters(),
7213 /*Complain=*/true,
7214 TPL_TemplateMatch))
7215 OldTemplateParams = OldDecl->getTemplateParameters();
7216 else
7217 Invalid = true;
7218
7219 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7220 if (!Invalid &&
7221 !Context.hasSameType(OldTD->getUnderlyingType(),
7222 NewTD->getUnderlyingType())) {
7223 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7224 // but we can't reasonably accept it.
7225 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7226 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7227 if (OldTD->getLocation().isValid())
7228 Diag(OldTD->getLocation(), diag::note_previous_definition);
7229 Invalid = true;
7230 }
7231 }
7232 }
7233
7234 // Merge any previous default template arguments into our parameters,
7235 // and check the parameter list.
7236 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7237 TPC_TypeAliasTemplate))
7238 return 0;
7239
7240 TypeAliasTemplateDecl *NewDecl =
7241 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7242 Name.Identifier, TemplateParams,
7243 NewTD);
7244
7245 NewDecl->setAccess(AS);
7246
7247 if (Invalid)
7248 NewDecl->setInvalidDecl();
7249 else if (OldDecl)
7250 NewDecl->setPreviousDeclaration(OldDecl);
7251
7252 NewND = NewDecl;
7253 } else {
7254 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7255 NewND = NewTD;
7256 }
Richard Smith162e1c12011-04-15 14:24:37 +00007257
7258 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007259 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007260
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007261 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007262 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007263}
7264
John McCalld226f652010-08-21 09:40:31 +00007265Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007266 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007267 SourceLocation AliasLoc,
7268 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007269 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007270 SourceLocation IdentLoc,
7271 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007272
Anders Carlsson81c85c42009-03-28 23:53:49 +00007273 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007274 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7275 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007276
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007277 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007278 NamedDecl *PrevDecl
7279 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7280 ForRedeclaration);
7281 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7282 PrevDecl = 0;
7283
7284 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007285 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007286 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007287 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007288 // FIXME: At some point, we'll want to create the (redundant)
7289 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007290 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007291 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007292 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007293 }
Mike Stump1eb44332009-09-09 15:08:12 +00007294
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007295 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7296 diag::err_redefinition_different_kind;
7297 Diag(AliasLoc, DiagID) << Alias;
7298 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007299 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007300 }
7301
John McCalla24dc2e2009-11-17 02:14:36 +00007302 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007303 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007304
John McCallf36e02d2009-10-09 21:13:30 +00007305 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007306 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007307 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007308 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007309 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007310 }
Mike Stump1eb44332009-09-09 15:08:12 +00007311
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007312 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007313 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007314 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007315 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007316
John McCall3dbd3d52010-02-16 06:53:13 +00007317 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007318 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007319}
7320
Sean Hunt001cad92011-05-10 00:49:42 +00007321Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007322Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7323 CXXMethodDecl *MD) {
7324 CXXRecordDecl *ClassDecl = MD->getParent();
7325
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007326 // C++ [except.spec]p14:
7327 // An implicitly declared special member function (Clause 12) shall have an
7328 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007329 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007330 if (ClassDecl->isInvalidDecl())
7331 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007332
Sebastian Redl60618fa2011-03-12 11:50:43 +00007333 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007334 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7335 BEnd = ClassDecl->bases_end();
7336 B != BEnd; ++B) {
7337 if (B->isVirtual()) // Handled below.
7338 continue;
7339
Douglas Gregor18274032010-07-03 00:47:00 +00007340 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7341 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007342 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7343 // If this is a deleted function, add it anyway. This might be conformant
7344 // with the standard. This might not. I'm not sure. It might not matter.
7345 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007346 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007347 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007348 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007349
7350 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007351 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7352 BEnd = ClassDecl->vbases_end();
7353 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007354 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7355 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007356 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7357 // If this is a deleted function, add it anyway. This might be conformant
7358 // with the standard. This might not. I'm not sure. It might not matter.
7359 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007360 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007361 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007362 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007363
7364 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007365 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7366 FEnd = ClassDecl->field_end();
7367 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007368 if (F->hasInClassInitializer()) {
7369 if (Expr *E = F->getInClassInitializer())
7370 ExceptSpec.CalledExpr(E);
7371 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007372 // DR1351:
7373 // If the brace-or-equal-initializer of a non-static data member
7374 // invokes a defaulted default constructor of its class or of an
7375 // enclosing class in a potentially evaluated subexpression, the
7376 // program is ill-formed.
7377 //
7378 // This resolution is unworkable: the exception specification of the
7379 // default constructor can be needed in an unevaluated context, in
7380 // particular, in the operand of a noexcept-expression, and we can be
7381 // unable to compute an exception specification for an enclosed class.
7382 //
7383 // We do not allow an in-class initializer to require the evaluation
7384 // of the exception specification for any in-class initializer whose
7385 // definition is not lexically complete.
7386 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007387 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007388 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007389 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7390 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7391 // If this is a deleted function, add it anyway. This might be conformant
7392 // with the standard. This might not. I'm not sure. It might not matter.
7393 // In particular, the problem is that this function never gets called. It
7394 // might just be ill-formed because this function attempts to refer to
7395 // a deleted function here.
7396 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007397 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007398 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007399 }
John McCalle23cf432010-12-14 08:05:40 +00007400
Sean Hunt001cad92011-05-10 00:49:42 +00007401 return ExceptSpec;
7402}
7403
Richard Smithafb49182012-11-29 01:34:07 +00007404namespace {
7405/// RAII object to register a special member as being currently declared.
7406struct DeclaringSpecialMember {
7407 Sema &S;
7408 Sema::SpecialMemberDecl D;
7409 bool WasAlreadyBeingDeclared;
7410
7411 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7412 : S(S), D(RD, CSM) {
7413 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7414 if (WasAlreadyBeingDeclared)
7415 // This almost never happens, but if it does, ensure that our cache
7416 // doesn't contain a stale result.
7417 S.SpecialMemberCache.clear();
7418
7419 // FIXME: Register a note to be produced if we encounter an error while
7420 // declaring the special member.
7421 }
7422 ~DeclaringSpecialMember() {
7423 if (!WasAlreadyBeingDeclared)
7424 S.SpecialMembersBeingDeclared.erase(D);
7425 }
7426
7427 /// \brief Are we already trying to declare this special member?
7428 bool isAlreadyBeingDeclared() const {
7429 return WasAlreadyBeingDeclared;
7430 }
7431};
7432}
7433
Sean Hunt001cad92011-05-10 00:49:42 +00007434CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7435 CXXRecordDecl *ClassDecl) {
7436 // C++ [class.ctor]p5:
7437 // A default constructor for a class X is a constructor of class X
7438 // that can be called without an argument. If there is no
7439 // user-declared constructor for class X, a default constructor is
7440 // implicitly declared. An implicitly-declared default constructor
7441 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007442 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007443 "Should not build implicit default constructor!");
7444
Richard Smithafb49182012-11-29 01:34:07 +00007445 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7446 if (DSM.isAlreadyBeingDeclared())
7447 return 0;
7448
Richard Smith7756afa2012-06-10 05:43:50 +00007449 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7450 CXXDefaultConstructor,
7451 false);
7452
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007453 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007454 CanQualType ClassType
7455 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007456 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007457 DeclarationName Name
7458 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007459 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007460 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007461 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007462 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007463 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007464 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007465 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007466 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007467
7468 // Build an exception specification pointing back at this constructor.
7469 FunctionProtoType::ExtProtoInfo EPI;
7470 EPI.ExceptionSpecType = EST_Unevaluated;
7471 EPI.ExceptionSpecDecl = DefaultCon;
7472 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7473
Richard Smithbc2a35d2012-12-08 08:32:28 +00007474 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7475 // constructors is easy to compute.
7476 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7477
7478 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7479 DefaultCon->setDeletedAsWritten();
7480
Douglas Gregor18274032010-07-03 00:47:00 +00007481 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007482 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007483
Douglas Gregor23c94db2010-07-02 17:43:08 +00007484 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007485 PushOnScopeChains(DefaultCon, S, false);
7486 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007487
Douglas Gregor32df23e2010-07-01 22:02:46 +00007488 return DefaultCon;
7489}
7490
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007491void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7492 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007493 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007494 !Constructor->doesThisDeclarationHaveABody() &&
7495 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007496 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007497
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007498 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007499 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007500
Eli Friedman9a14db32012-10-18 20:14:08 +00007501 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007502 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007503 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007504 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007505 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007506 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007507 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007508 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007509 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007510
7511 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007512 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007513
7514 Constructor->setUsed();
7515 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007516
7517 if (ASTMutationListener *L = getASTMutationListener()) {
7518 L->CompletedImplicitDefinition(Constructor);
7519 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007520}
7521
Richard Smith7a614d82011-06-11 17:19:42 +00007522void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007523 // Check that any explicitly-defaulted methods have exception specifications
7524 // compatible with their implicit exception specifications.
7525 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007526}
7527
Sebastian Redlf677ea32011-02-05 19:23:19 +00007528void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7529 // We start with an initial pass over the base classes to collect those that
7530 // inherit constructors from. If there are none, we can forgo all further
7531 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007532 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007533 BasesVector BasesToInheritFrom;
7534 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7535 BaseE = ClassDecl->bases_end();
7536 BaseIt != BaseE; ++BaseIt) {
7537 if (BaseIt->getInheritConstructors()) {
7538 QualType Base = BaseIt->getType();
7539 if (Base->isDependentType()) {
7540 // If we inherit constructors from anything that is dependent, just
7541 // abort processing altogether. We'll get another chance for the
7542 // instantiations.
7543 return;
7544 }
7545 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7546 }
7547 }
7548 if (BasesToInheritFrom.empty())
7549 return;
7550
7551 // Now collect the constructors that we already have in the current class.
7552 // Those take precedence over inherited constructors.
7553 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7554 // unless there is a user-declared constructor with the same signature in
7555 // the class where the using-declaration appears.
7556 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7557 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7558 CtorE = ClassDecl->ctor_end();
7559 CtorIt != CtorE; ++CtorIt) {
7560 ExistingConstructors.insert(
7561 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7562 }
7563
Sebastian Redlf677ea32011-02-05 19:23:19 +00007564 DeclarationName CreatedCtorName =
7565 Context.DeclarationNames.getCXXConstructorName(
7566 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7567
7568 // Now comes the true work.
7569 // First, we keep a map from constructor types to the base that introduced
7570 // them. Needed for finding conflicting constructors. We also keep the
7571 // actually inserted declarations in there, for pretty diagnostics.
7572 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7573 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7574 ConstructorToSourceMap InheritedConstructors;
7575 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7576 BaseE = BasesToInheritFrom.end();
7577 BaseIt != BaseE; ++BaseIt) {
7578 const RecordType *Base = *BaseIt;
7579 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7580 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7581 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7582 CtorE = BaseDecl->ctor_end();
7583 CtorIt != CtorE; ++CtorIt) {
7584 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00007585 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00007586 DeclarationName Name =
7587 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00007588 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7589 LookupQualifiedName(Result, CurContext);
7590 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007591 SourceLocation UsingLoc = UD ? UD->getLocation() :
7592 ClassDecl->getLocation();
7593
7594 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7595 // from the class X named in the using-declaration consists of actual
7596 // constructors and notional constructors that result from the
7597 // transformation of defaulted parameters as follows:
7598 // - all non-template default constructors of X, and
7599 // - for each non-template constructor of X that has at least one
7600 // parameter with a default argument, the set of constructors that
7601 // results from omitting any ellipsis parameter specification and
7602 // successively omitting parameters with a default argument from the
7603 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00007604 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007605 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7606 const FunctionProtoType *BaseCtorType =
7607 BaseCtor->getType()->getAs<FunctionProtoType>();
7608
7609 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7610 maxParams = BaseCtor->getNumParams();
7611 params <= maxParams; ++params) {
7612 // Skip default constructors. They're never inherited.
7613 if (params == 0)
7614 continue;
7615 // Skip copy and move constructors for the same reason.
7616 if (CanBeCopyOrMove && params == 1)
7617 continue;
7618
7619 // Build up a function type for this particular constructor.
7620 // FIXME: The working paper does not consider that the exception spec
7621 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007622 // source. This code doesn't yet, either. When it does, this code will
7623 // need to be delayed until after exception specifications and in-class
7624 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007625 const Type *NewCtorType;
7626 if (params == maxParams)
7627 NewCtorType = BaseCtorType;
7628 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007629 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007630 for (unsigned i = 0; i < params; ++i) {
7631 Args.push_back(BaseCtorType->getArgType(i));
7632 }
7633 FunctionProtoType::ExtProtoInfo ExtInfo =
7634 BaseCtorType->getExtProtoInfo();
7635 ExtInfo.Variadic = false;
7636 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7637 Args.data(), params, ExtInfo)
7638 .getTypePtr();
7639 }
7640 const Type *CanonicalNewCtorType =
7641 Context.getCanonicalType(NewCtorType);
7642
7643 // Now that we have the type, first check if the class already has a
7644 // constructor with this signature.
7645 if (ExistingConstructors.count(CanonicalNewCtorType))
7646 continue;
7647
7648 // Then we check if we have already declared an inherited constructor
7649 // with this signature.
7650 std::pair<ConstructorToSourceMap::iterator, bool> result =
7651 InheritedConstructors.insert(std::make_pair(
7652 CanonicalNewCtorType,
7653 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7654 if (!result.second) {
7655 // Already in the map. If it came from a different class, that's an
7656 // error. Not if it's from the same.
7657 CanQualType PreviousBase = result.first->second.first;
7658 if (CanonicalBase != PreviousBase) {
7659 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7660 const CXXConstructorDecl *PrevBaseCtor =
7661 PrevCtor->getInheritedConstructor();
7662 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7663
7664 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7665 Diag(BaseCtor->getLocation(),
7666 diag::note_using_decl_constructor_conflict_current_ctor);
7667 Diag(PrevBaseCtor->getLocation(),
7668 diag::note_using_decl_constructor_conflict_previous_ctor);
7669 Diag(PrevCtor->getLocation(),
7670 diag::note_using_decl_constructor_conflict_previous_using);
7671 }
7672 continue;
7673 }
7674
7675 // OK, we're there, now add the constructor.
7676 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007677 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007678 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7679 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007680 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7681 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007682 /*ImplicitlyDeclared=*/true,
7683 // FIXME: Due to a defect in the standard, we treat inherited
7684 // constructors as constexpr even if that makes them ill-formed.
7685 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007686 NewCtor->setAccess(BaseCtor->getAccess());
7687
7688 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007689 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007690 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007691 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7692 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007693 /*IdentifierInfo=*/0,
7694 BaseCtorType->getArgType(i),
7695 /*TInfo=*/0, SC_None,
7696 SC_None, /*DefaultArg=*/0));
7697 }
David Blaikie4278c652011-09-21 18:16:56 +00007698 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007699 NewCtor->setInheritedConstructor(BaseCtor);
7700
Sebastian Redlf677ea32011-02-05 19:23:19 +00007701 ClassDecl->addDecl(NewCtor);
7702 result.first->second.second = NewCtor;
7703 }
7704 }
7705 }
7706}
7707
Sean Huntcb45a0f2011-05-12 22:46:25 +00007708Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007709Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7710 CXXRecordDecl *ClassDecl = MD->getParent();
7711
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007712 // C++ [except.spec]p14:
7713 // An implicitly declared special member function (Clause 12) shall have
7714 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007715 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007716 if (ClassDecl->isInvalidDecl())
7717 return ExceptSpec;
7718
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007719 // Direct base-class destructors.
7720 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7721 BEnd = ClassDecl->bases_end();
7722 B != BEnd; ++B) {
7723 if (B->isVirtual()) // Handled below.
7724 continue;
7725
7726 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007727 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007728 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007729 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007730
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007731 // Virtual base-class destructors.
7732 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7733 BEnd = ClassDecl->vbases_end();
7734 B != BEnd; ++B) {
7735 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007736 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007737 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007738 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007739
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007740 // Field destructors.
7741 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7742 FEnd = ClassDecl->field_end();
7743 F != FEnd; ++F) {
7744 if (const RecordType *RecordTy
7745 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007746 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007747 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007748 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007749
Sean Huntcb45a0f2011-05-12 22:46:25 +00007750 return ExceptSpec;
7751}
7752
7753CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7754 // C++ [class.dtor]p2:
7755 // If a class has no user-declared destructor, a destructor is
7756 // declared implicitly. An implicitly-declared destructor is an
7757 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00007758 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00007759
Richard Smithafb49182012-11-29 01:34:07 +00007760 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7761 if (DSM.isAlreadyBeingDeclared())
7762 return 0;
7763
Douglas Gregor4923aa22010-07-02 20:37:36 +00007764 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007765 CanQualType ClassType
7766 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007767 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007768 DeclarationName Name
7769 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007770 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007771 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007772 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7773 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007774 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007775 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007776 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007777 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007778
7779 // Build an exception specification pointing back at this destructor.
7780 FunctionProtoType::ExtProtoInfo EPI;
7781 EPI.ExceptionSpecType = EST_Unevaluated;
7782 EPI.ExceptionSpecDecl = Destructor;
7783 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7784
Richard Smithbc2a35d2012-12-08 08:32:28 +00007785 AddOverriddenMethods(ClassDecl, Destructor);
7786
7787 // We don't need to use SpecialMemberIsTrivial here; triviality for
7788 // destructors is easy to compute.
7789 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7790
7791 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7792 Destructor->setDeletedAsWritten();
7793
Douglas Gregor4923aa22010-07-02 20:37:36 +00007794 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007795 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007796
Douglas Gregor4923aa22010-07-02 20:37:36 +00007797 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007798 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007799 PushOnScopeChains(Destructor, S, false);
7800 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007801
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007802 return Destructor;
7803}
7804
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007805void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007806 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007807 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007808 !Destructor->doesThisDeclarationHaveABody() &&
7809 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007810 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007811 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007812 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007813
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007814 if (Destructor->isInvalidDecl())
7815 return;
7816
Eli Friedman9a14db32012-10-18 20:14:08 +00007817 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007818
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007819 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007820 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7821 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007822
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007823 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007824 Diag(CurrentLocation, diag::note_member_synthesized_at)
7825 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7826
7827 Destructor->setInvalidDecl();
7828 return;
7829 }
7830
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007831 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007832 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007833 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007834 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007835 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007836
7837 if (ASTMutationListener *L = getASTMutationListener()) {
7838 L->CompletedImplicitDefinition(Destructor);
7839 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007840}
7841
Richard Smitha4156b82012-04-21 18:42:51 +00007842/// \brief Perform any semantic analysis which needs to be delayed until all
7843/// pending class member declarations have been parsed.
7844void Sema::ActOnFinishCXXMemberDecls() {
Richard Smitha4156b82012-04-21 18:42:51 +00007845 // Perform any deferred checking of exception specifications for virtual
7846 // destructors.
7847 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7848 i != e; ++i) {
7849 const CXXDestructorDecl *Dtor =
7850 DelayedDestructorExceptionSpecChecks[i].first;
7851 assert(!Dtor->getParent()->isDependentType() &&
7852 "Should not ever add destructors of templates into the list.");
7853 CheckOverridingFunctionExceptionSpec(Dtor,
7854 DelayedDestructorExceptionSpecChecks[i].second);
7855 }
7856 DelayedDestructorExceptionSpecChecks.clear();
7857}
7858
Richard Smithb9d0b762012-07-27 04:22:15 +00007859void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7860 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00007861 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00007862 "adjusting dtor exception specs was introduced in c++11");
7863
Sebastian Redl0ee33912011-05-19 05:13:44 +00007864 // C++11 [class.dtor]p3:
7865 // A declaration of a destructor that does not have an exception-
7866 // specification is implicitly considered to have the same exception-
7867 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007868 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007869 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007870 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007871 return;
7872
Chandler Carruth3f224b22011-09-20 04:55:26 +00007873 // Replace the destructor's type, building off the existing one. Fortunately,
7874 // the only thing of interest in the destructor type is its extended info.
7875 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007876 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7877 EPI.ExceptionSpecType = EST_Unevaluated;
7878 EPI.ExceptionSpecDecl = Destructor;
7879 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007880
Sebastian Redl0ee33912011-05-19 05:13:44 +00007881 // FIXME: If the destructor has a body that could throw, and the newly created
7882 // spec doesn't allow exceptions, we should emit a warning, because this
7883 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007884 // However, we don't have a body or an exception specification yet, so it
7885 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007886}
7887
Richard Smith8c889532012-11-14 00:50:40 +00007888/// When generating a defaulted copy or move assignment operator, if a field
7889/// should be copied with __builtin_memcpy rather than via explicit assignments,
7890/// do so. This optimization only applies for arrays of scalars, and for arrays
7891/// of class type where the selected copy/move-assignment operator is trivial.
7892static StmtResult
7893buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
7894 Expr *To, Expr *From) {
7895 // Compute the size of the memory buffer to be copied.
7896 QualType SizeType = S.Context.getSizeType();
7897 llvm::APInt Size(S.Context.getTypeSize(SizeType),
7898 S.Context.getTypeSizeInChars(T).getQuantity());
7899
7900 // Take the address of the field references for "from" and "to". We
7901 // directly construct UnaryOperators here because semantic analysis
7902 // does not permit us to take the address of an xvalue.
7903 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
7904 S.Context.getPointerType(From->getType()),
7905 VK_RValue, OK_Ordinary, Loc);
7906 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
7907 S.Context.getPointerType(To->getType()),
7908 VK_RValue, OK_Ordinary, Loc);
7909
7910 const Type *E = T->getBaseElementTypeUnsafe();
7911 bool NeedsCollectableMemCpy =
7912 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
7913
7914 // Create a reference to the __builtin_objc_memmove_collectable function
7915 StringRef MemCpyName = NeedsCollectableMemCpy ?
7916 "__builtin_objc_memmove_collectable" :
7917 "__builtin_memcpy";
7918 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
7919 Sema::LookupOrdinaryName);
7920 S.LookupName(R, S.TUScope, true);
7921
7922 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
7923 if (!MemCpy)
7924 // Something went horribly wrong earlier, and we will have complained
7925 // about it.
7926 return StmtError();
7927
7928 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
7929 VK_RValue, Loc, 0);
7930 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
7931
7932 Expr *CallArgs[] = {
7933 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
7934 };
7935 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
7936 Loc, CallArgs, Loc);
7937
7938 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7939 return S.Owned(Call.takeAs<Stmt>());
7940}
7941
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007942/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007943/// \c To.
7944///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007945/// This routine is used to copy/move the members of a class with an
7946/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007947/// copied are arrays, this routine builds for loops to copy them.
7948///
7949/// \param S The Sema object used for type-checking.
7950///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007951/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007952///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007953/// \param T The type of the expressions being copied/moved. Both expressions
7954/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007955///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007956/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007957///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007958/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007959///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007960/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007961/// Otherwise, it's a non-static member subobject.
7962///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007963/// \param Copying Whether we're copying or moving.
7964///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007965/// \param Depth Internal parameter recording the depth of the recursion.
7966///
Richard Smith8c889532012-11-14 00:50:40 +00007967/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
7968/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00007969static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00007970buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
7971 Expr *To, Expr *From,
7972 bool CopyingBaseSubobject, bool Copying,
7973 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00007974 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007975 // Each subobject is assigned in the manner appropriate to its type:
7976 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007977 // - if the subobject is of class type, as if by a call to operator= with
7978 // the subobject as the object expression and the corresponding
7979 // subobject of x as a single function argument (as if by explicit
7980 // qualification; that is, ignoring any possible virtual overriding
7981 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00007982 //
7983 // C++03 [class.copy]p13:
7984 // - if the subobject is of class type, the copy assignment operator for
7985 // the class is used (as if by explicit qualification; that is,
7986 // ignoring any possible virtual overriding functions in more derived
7987 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007988 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7989 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00007990
Douglas Gregor06a9f362010-05-01 20:49:11 +00007991 // Look for operator=.
7992 DeclarationName Name
7993 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7994 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7995 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007996
Richard Smith044c8aa2012-11-13 00:54:12 +00007997 // Prior to C++11, filter out any result that isn't a copy/move-assignment
7998 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00007999 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008000 LookupResult::Filter F = OpLookup.makeFilter();
8001 while (F.hasNext()) {
8002 NamedDecl *D = F.next();
8003 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8004 if (Method->isCopyAssignmentOperator() ||
8005 (!Copying && Method->isMoveAssignmentOperator()))
8006 continue;
8007
8008 F.erase();
8009 }
8010 F.done();
John McCallb0207482010-03-16 06:11:48 +00008011 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008012
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008013 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008014 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008015 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008016 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008017 // ambiguities), we need to cast "this" to that subobject type; to
8018 // ensure that we don't go through the virtual call mechanism, we need
8019 // to qualify the operator= name with the base class (see below). However,
8020 // this means that if the base class has a protected copy assignment
8021 // operator, the protected member access check will fail. So, we
8022 // rewrite "protected" access to "public" access in this case, since we
8023 // know by construction that we're calling from a derived class.
8024 if (CopyingBaseSubobject) {
8025 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8026 L != LEnd; ++L) {
8027 if (L.getAccess() == AS_protected)
8028 L.setAccess(AS_public);
8029 }
8030 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008031
Douglas Gregor06a9f362010-05-01 20:49:11 +00008032 // Create the nested-name-specifier that will be used to qualify the
8033 // reference to operator=; this is required to suppress the virtual
8034 // call mechanism.
8035 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008036 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008037 SS.MakeTrivial(S.Context,
8038 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008039 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008040 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008041
Douglas Gregor06a9f362010-05-01 20:49:11 +00008042 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008043 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008044 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008045 /*TemplateKWLoc=*/SourceLocation(),
8046 /*FirstQualifierInScope=*/0,
8047 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008048 /*TemplateArgs=*/0,
8049 /*SuppressQualifierCheck=*/true);
8050 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008051 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008052
Douglas Gregor06a9f362010-05-01 20:49:11 +00008053 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008054
Richard Smith044c8aa2012-11-13 00:54:12 +00008055 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008056 OpEqualRef.takeAs<Expr>(),
8057 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008058 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008059 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008060
Richard Smith8c889532012-11-14 00:50:40 +00008061 // If we built a call to a trivial 'operator=' while copying an array,
8062 // bail out. We'll replace the whole shebang with a memcpy.
8063 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8064 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8065 return StmtResult((Stmt*)0);
8066
Richard Smith044c8aa2012-11-13 00:54:12 +00008067 // Convert to an expression-statement, and clean up any produced
8068 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008069 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008070 }
John McCallb0207482010-03-16 06:11:48 +00008071
Richard Smith044c8aa2012-11-13 00:54:12 +00008072 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008073 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008074 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008075 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008076 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008077 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008078 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008079 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008080 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008081
8082 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008083 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008084
Douglas Gregor06a9f362010-05-01 20:49:11 +00008085 // Construct a loop over the array bounds, e.g.,
8086 //
8087 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8088 //
8089 // that will copy each of the array elements.
8090 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008091
Douglas Gregor06a9f362010-05-01 20:49:11 +00008092 // Create the iteration variable.
8093 IdentifierInfo *IterationVarName = 0;
8094 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008095 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008096 llvm::raw_svector_ostream OS(Str);
8097 OS << "__i" << Depth;
8098 IterationVarName = &S.Context.Idents.get(OS.str());
8099 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008100 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008101 IterationVarName, SizeType,
8102 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00008103 SC_None, SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008104
Douglas Gregor06a9f362010-05-01 20:49:11 +00008105 // Initialize the iteration variable to zero.
8106 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008107 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008108
8109 // Create a reference to the iteration variable; we'll use this several
8110 // times throughout.
8111 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008112 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008113 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008114 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8115 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8116
Douglas Gregor06a9f362010-05-01 20:49:11 +00008117 // Create the DeclStmt that holds the iteration variable.
8118 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008119
Douglas Gregor06a9f362010-05-01 20:49:11 +00008120 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008121 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008122 IterationVarRefRVal,
8123 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008124 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008125 IterationVarRefRVal,
8126 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008127 if (!Copying) // Cast to rvalue
8128 From = CastForMoving(S, From);
8129
8130 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008131 StmtResult Copy =
8132 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8133 To, From, CopyingBaseSubobject,
8134 Copying, Depth + 1);
8135 // Bail out if copying fails or if we determined that we should use memcpy.
8136 if (Copy.isInvalid() || !Copy.get())
8137 return Copy;
8138
8139 // Create the comparison against the array bound.
8140 llvm::APInt Upper
8141 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8142 Expr *Comparison
8143 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8144 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8145 BO_NE, S.Context.BoolTy,
8146 VK_RValue, OK_Ordinary, Loc, false);
8147
8148 // Create the pre-increment of the iteration variable.
8149 Expr *Increment
8150 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8151 VK_LValue, OK_Ordinary, Loc);
8152
Douglas Gregor06a9f362010-05-01 20:49:11 +00008153 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008154 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008155 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008156 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008157 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008158}
8159
Richard Smith8c889532012-11-14 00:50:40 +00008160static StmtResult
8161buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8162 Expr *To, Expr *From,
8163 bool CopyingBaseSubobject, bool Copying) {
8164 // Maybe we should use a memcpy?
8165 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8166 T.isTriviallyCopyableType(S.Context))
8167 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8168
8169 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8170 CopyingBaseSubobject,
8171 Copying, 0));
8172
8173 // If we ended up picking a trivial assignment operator for an array of a
8174 // non-trivially-copyable class type, just emit a memcpy.
8175 if (!Result.isInvalid() && !Result.get())
8176 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8177
8178 return Result;
8179}
8180
Richard Smithb9d0b762012-07-27 04:22:15 +00008181Sema::ImplicitExceptionSpecification
8182Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8183 CXXRecordDecl *ClassDecl = MD->getParent();
8184
8185 ImplicitExceptionSpecification ExceptSpec(*this);
8186 if (ClassDecl->isInvalidDecl())
8187 return ExceptSpec;
8188
8189 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8190 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8191 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8192
Douglas Gregorb87786f2010-07-01 17:48:08 +00008193 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008194 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008195 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008196
8197 // It is unspecified whether or not an implicit copy assignment operator
8198 // attempts to deduplicate calls to assignment operators of virtual bases are
8199 // made. As such, this exception specification is effectively unspecified.
8200 // Based on a similar decision made for constness in C++0x, we're erring on
8201 // the side of assuming such calls to be made regardless of whether they
8202 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008203 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8204 BaseEnd = ClassDecl->bases_end();
8205 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008206 if (Base->isVirtual())
8207 continue;
8208
Douglas Gregora376d102010-07-02 21:50:04 +00008209 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008210 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008211 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8212 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008213 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008214 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008215
8216 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8217 BaseEnd = ClassDecl->vbases_end();
8218 Base != BaseEnd; ++Base) {
8219 CXXRecordDecl *BaseClassDecl
8220 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8221 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8222 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008223 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008224 }
8225
Douglas Gregorb87786f2010-07-01 17:48:08 +00008226 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8227 FieldEnd = ClassDecl->field_end();
8228 Field != FieldEnd;
8229 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008230 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008231 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8232 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008233 LookupCopyingAssignment(FieldClassDecl,
8234 ArgQuals | FieldType.getCVRQualifiers(),
8235 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008236 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008237 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008238 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008239
Richard Smithb9d0b762012-07-27 04:22:15 +00008240 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008241}
8242
8243CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8244 // Note: The following rules are largely analoguous to the copy
8245 // constructor rules. Note that virtual bases are not taken into account
8246 // for determining the argument type of the operator. Note also that
8247 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008248 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008249
Richard Smithafb49182012-11-29 01:34:07 +00008250 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8251 if (DSM.isAlreadyBeingDeclared())
8252 return 0;
8253
Sean Hunt30de05c2011-05-14 05:23:20 +00008254 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8255 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008256 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008257 ArgType = ArgType.withConst();
8258 ArgType = Context.getLValueReferenceType(ArgType);
8259
Douglas Gregord3c35902010-07-01 16:36:15 +00008260 // An implicitly-declared copy assignment operator is an inline public
8261 // member of its class.
8262 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008263 SourceLocation ClassLoc = ClassDecl->getLocation();
8264 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008265 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008266 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00008267 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00008268 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008269 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008270 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008271 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008272 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008273 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008274
8275 // Build an exception specification pointing back at this member.
8276 FunctionProtoType::ExtProtoInfo EPI;
8277 EPI.ExceptionSpecType = EST_Unevaluated;
8278 EPI.ExceptionSpecDecl = CopyAssignment;
8279 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8280
Douglas Gregord3c35902010-07-01 16:36:15 +00008281 // Add the parameter to the operator.
8282 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008283 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008284 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008285 SC_None,
8286 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008287 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008288
Richard Smithbc2a35d2012-12-08 08:32:28 +00008289 AddOverriddenMethods(ClassDecl, CopyAssignment);
8290
8291 CopyAssignment->setTrivial(
8292 ClassDecl->needsOverloadResolutionForCopyAssignment()
8293 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8294 : ClassDecl->hasTrivialCopyAssignment());
8295
Nico Weberafcc96a2012-01-23 03:19:29 +00008296 // C++0x [class.copy]p19:
8297 // .... If the class definition does not explicitly declare a copy
8298 // assignment operator, there is no user-declared move constructor, and
8299 // there is no user-declared move assignment operator, a copy assignment
8300 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008301 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00008302 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008303
Richard Smithbc2a35d2012-12-08 08:32:28 +00008304 // Note that we have added this copy-assignment operator.
8305 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8306
8307 if (Scope *S = getScopeForContext(ClassDecl))
8308 PushOnScopeChains(CopyAssignment, S, false);
8309 ClassDecl->addDecl(CopyAssignment);
8310
Douglas Gregord3c35902010-07-01 16:36:15 +00008311 return CopyAssignment;
8312}
8313
Douglas Gregor06a9f362010-05-01 20:49:11 +00008314void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8315 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008316 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008317 CopyAssignOperator->isOverloadedOperator() &&
8318 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008319 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8320 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008321 "DefineImplicitCopyAssignment called for wrong function");
8322
8323 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8324
8325 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8326 CopyAssignOperator->setInvalidDecl();
8327 return;
8328 }
8329
8330 CopyAssignOperator->setUsed();
8331
Eli Friedman9a14db32012-10-18 20:14:08 +00008332 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008333 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008334
8335 // C++0x [class.copy]p30:
8336 // The implicitly-defined or explicitly-defaulted copy assignment operator
8337 // for a non-union class X performs memberwise copy assignment of its
8338 // subobjects. The direct base classes of X are assigned first, in the
8339 // order of their declaration in the base-specifier-list, and then the
8340 // immediate non-static data members of X are assigned, in the order in
8341 // which they were declared in the class definition.
8342
8343 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008344 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008345
8346 // The parameter for the "other" object, which we are copying from.
8347 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8348 Qualifiers OtherQuals = Other->getType().getQualifiers();
8349 QualType OtherRefType = Other->getType();
8350 if (const LValueReferenceType *OtherRef
8351 = OtherRefType->getAs<LValueReferenceType>()) {
8352 OtherRefType = OtherRef->getPointeeType();
8353 OtherQuals = OtherRefType.getQualifiers();
8354 }
8355
8356 // Our location for everything implicitly-generated.
8357 SourceLocation Loc = CopyAssignOperator->getLocation();
8358
8359 // Construct a reference to the "other" object. We'll be using this
8360 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008361 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008362 assert(OtherRef && "Reference to parameter cannot fail!");
8363
8364 // Construct the "this" pointer. We'll be using this throughout the generated
8365 // ASTs.
8366 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8367 assert(This && "Reference to this cannot fail!");
8368
8369 // Assign base classes.
8370 bool Invalid = false;
8371 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8372 E = ClassDecl->bases_end(); Base != E; ++Base) {
8373 // Form the assignment:
8374 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8375 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008376 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008377 Invalid = true;
8378 continue;
8379 }
8380
John McCallf871d0c2010-08-07 06:22:56 +00008381 CXXCastPath BasePath;
8382 BasePath.push_back(Base);
8383
Douglas Gregor06a9f362010-05-01 20:49:11 +00008384 // Construct the "from" expression, which is an implicit cast to the
8385 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008386 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008387 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8388 CK_UncheckedDerivedToBase,
8389 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008390
8391 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008392 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008393
8394 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008395 To = ImpCastExprToType(To.take(),
8396 Context.getCVRQualifiedType(BaseType,
8397 CopyAssignOperator->getTypeQualifiers()),
8398 CK_UncheckedDerivedToBase,
8399 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008400
8401 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008402 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008403 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008404 /*CopyingBaseSubobject=*/true,
8405 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008406 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008407 Diag(CurrentLocation, diag::note_member_synthesized_at)
8408 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8409 CopyAssignOperator->setInvalidDecl();
8410 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008411 }
8412
8413 // Success! Record the copy.
8414 Statements.push_back(Copy.takeAs<Expr>());
8415 }
8416
Douglas Gregor06a9f362010-05-01 20:49:11 +00008417 // Assign non-static members.
8418 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8419 FieldEnd = ClassDecl->field_end();
8420 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008421 if (Field->isUnnamedBitfield())
8422 continue;
8423
Douglas Gregor06a9f362010-05-01 20:49:11 +00008424 // Check for members of reference type; we can't copy those.
8425 if (Field->getType()->isReferenceType()) {
8426 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8427 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8428 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008429 Diag(CurrentLocation, diag::note_member_synthesized_at)
8430 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008431 Invalid = true;
8432 continue;
8433 }
8434
8435 // Check for members of const-qualified, non-class type.
8436 QualType BaseType = Context.getBaseElementType(Field->getType());
8437 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8438 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8439 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8440 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008441 Diag(CurrentLocation, diag::note_member_synthesized_at)
8442 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008443 Invalid = true;
8444 continue;
8445 }
John McCallb77115d2011-06-17 00:18:42 +00008446
8447 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008448 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8449 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008450
8451 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008452 if (FieldType->isIncompleteArrayType()) {
8453 assert(ClassDecl->hasFlexibleArrayMember() &&
8454 "Incomplete array type is not valid");
8455 continue;
8456 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008457
8458 // Build references to the field in the object we're copying from and to.
8459 CXXScopeSpec SS; // Intentionally empty
8460 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8461 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008462 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008463 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008464 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008465 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008466 SS, SourceLocation(), 0,
8467 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008468 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008469 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008470 SS, SourceLocation(), 0,
8471 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008472 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8473 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008474
Douglas Gregor06a9f362010-05-01 20:49:11 +00008475 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008476 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008477 To.get(), From.get(),
8478 /*CopyingBaseSubobject=*/false,
8479 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008480 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008481 Diag(CurrentLocation, diag::note_member_synthesized_at)
8482 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8483 CopyAssignOperator->setInvalidDecl();
8484 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008485 }
8486
8487 // Success! Record the copy.
8488 Statements.push_back(Copy.takeAs<Stmt>());
8489 }
8490
8491 if (!Invalid) {
8492 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008493 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008494
John McCall60d7b3a2010-08-24 06:29:42 +00008495 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008496 if (Return.isInvalid())
8497 Invalid = true;
8498 else {
8499 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008500
8501 if (Trap.hasErrorOccurred()) {
8502 Diag(CurrentLocation, diag::note_member_synthesized_at)
8503 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8504 Invalid = true;
8505 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008506 }
8507 }
8508
8509 if (Invalid) {
8510 CopyAssignOperator->setInvalidDecl();
8511 return;
8512 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008513
8514 StmtResult Body;
8515 {
8516 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008517 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008518 /*isStmtExpr=*/false);
8519 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8520 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008521 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008522
8523 if (ASTMutationListener *L = getASTMutationListener()) {
8524 L->CompletedImplicitDefinition(CopyAssignOperator);
8525 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008526}
8527
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008528Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008529Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8530 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008531
Richard Smithb9d0b762012-07-27 04:22:15 +00008532 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008533 if (ClassDecl->isInvalidDecl())
8534 return ExceptSpec;
8535
8536 // C++0x [except.spec]p14:
8537 // An implicitly declared special member function (Clause 12) shall have an
8538 // exception-specification. [...]
8539
8540 // It is unspecified whether or not an implicit move assignment operator
8541 // attempts to deduplicate calls to assignment operators of virtual bases are
8542 // made. As such, this exception specification is effectively unspecified.
8543 // Based on a similar decision made for constness in C++0x, we're erring on
8544 // the side of assuming such calls to be made regardless of whether they
8545 // actually happen.
8546 // Note that a move constructor is not implicitly declared when there are
8547 // virtual bases, but it can still be user-declared and explicitly defaulted.
8548 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8549 BaseEnd = ClassDecl->bases_end();
8550 Base != BaseEnd; ++Base) {
8551 if (Base->isVirtual())
8552 continue;
8553
8554 CXXRecordDecl *BaseClassDecl
8555 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8556 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008557 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008558 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008559 }
8560
8561 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8562 BaseEnd = ClassDecl->vbases_end();
8563 Base != BaseEnd; ++Base) {
8564 CXXRecordDecl *BaseClassDecl
8565 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8566 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008567 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008568 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008569 }
8570
8571 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8572 FieldEnd = ClassDecl->field_end();
8573 Field != FieldEnd;
8574 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008575 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008576 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008577 if (CXXMethodDecl *MoveAssign =
8578 LookupMovingAssignment(FieldClassDecl,
8579 FieldType.getCVRQualifiers(),
8580 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008581 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008582 }
8583 }
8584
8585 return ExceptSpec;
8586}
8587
Richard Smith1c931be2012-04-02 18:40:40 +00008588/// Determine whether the class type has any direct or indirect virtual base
8589/// classes which have a non-trivial move assignment operator.
8590static bool
8591hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8592 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8593 BaseEnd = ClassDecl->vbases_end();
8594 Base != BaseEnd; ++Base) {
8595 CXXRecordDecl *BaseClass =
8596 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8597
8598 // Try to declare the move assignment. If it would be deleted, then the
8599 // class does not have a non-trivial move assignment.
8600 if (BaseClass->needsImplicitMoveAssignment())
8601 S.DeclareImplicitMoveAssignment(BaseClass);
8602
Richard Smith426391c2012-11-16 00:53:38 +00008603 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008604 return true;
8605 }
8606
8607 return false;
8608}
8609
8610/// Determine whether the given type either has a move constructor or is
8611/// trivially copyable.
8612static bool
8613hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8614 Type = S.Context.getBaseElementType(Type);
8615
8616 // FIXME: Technically, non-trivially-copyable non-class types, such as
8617 // reference types, are supposed to return false here, but that appears
8618 // to be a standard defect.
8619 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008620 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008621 return true;
8622
8623 if (Type.isTriviallyCopyableType(S.Context))
8624 return true;
8625
8626 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008627 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8628 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008629 if (ClassDecl->needsImplicitMoveConstructor())
8630 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008631 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008632 }
8633
Richard Smithe5411b72012-12-01 02:35:44 +00008634 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8635 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008636 if (ClassDecl->needsImplicitMoveAssignment())
8637 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008638 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008639}
8640
8641/// Determine whether all non-static data members and direct or virtual bases
8642/// of class \p ClassDecl have either a move operation, or are trivially
8643/// copyable.
8644static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8645 bool IsConstructor) {
8646 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8647 BaseEnd = ClassDecl->bases_end();
8648 Base != BaseEnd; ++Base) {
8649 if (Base->isVirtual())
8650 continue;
8651
8652 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8653 return false;
8654 }
8655
8656 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8657 BaseEnd = ClassDecl->vbases_end();
8658 Base != BaseEnd; ++Base) {
8659 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8660 return false;
8661 }
8662
8663 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8664 FieldEnd = ClassDecl->field_end();
8665 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008666 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008667 return false;
8668 }
8669
8670 return true;
8671}
8672
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008673CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008674 // C++11 [class.copy]p20:
8675 // If the definition of a class X does not explicitly declare a move
8676 // assignment operator, one will be implicitly declared as defaulted
8677 // if and only if:
8678 //
8679 // - [first 4 bullets]
8680 assert(ClassDecl->needsImplicitMoveAssignment());
8681
Richard Smithafb49182012-11-29 01:34:07 +00008682 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8683 if (DSM.isAlreadyBeingDeclared())
8684 return 0;
8685
Richard Smith1c931be2012-04-02 18:40:40 +00008686 // [Checked after we build the declaration]
8687 // - the move assignment operator would not be implicitly defined as
8688 // deleted,
8689
8690 // [DR1402]:
8691 // - X has no direct or indirect virtual base class with a non-trivial
8692 // move assignment operator, and
8693 // - each of X's non-static data members and direct or virtual base classes
8694 // has a type that either has a move assignment operator or is trivially
8695 // copyable.
8696 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8697 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8698 ClassDecl->setFailedImplicitMoveAssignment();
8699 return 0;
8700 }
8701
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008702 // Note: The following rules are largely analoguous to the move
8703 // constructor rules.
8704
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008705 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8706 QualType RetType = Context.getLValueReferenceType(ArgType);
8707 ArgType = Context.getRValueReferenceType(ArgType);
8708
8709 // An implicitly-declared move assignment operator is an inline public
8710 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008711 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8712 SourceLocation ClassLoc = ClassDecl->getLocation();
8713 DeclarationNameInfo NameInfo(Name, ClassLoc);
8714 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008715 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008716 /*TInfo=*/0, /*isStatic=*/false,
8717 /*StorageClassAsWritten=*/SC_None,
8718 /*isInline=*/true,
8719 /*isConstexpr=*/false,
8720 SourceLocation());
8721 MoveAssignment->setAccess(AS_public);
8722 MoveAssignment->setDefaulted();
8723 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008724
Richard Smithb9d0b762012-07-27 04:22:15 +00008725 // Build an exception specification pointing back at this member.
8726 FunctionProtoType::ExtProtoInfo EPI;
8727 EPI.ExceptionSpecType = EST_Unevaluated;
8728 EPI.ExceptionSpecDecl = MoveAssignment;
8729 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8730
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008731 // Add the parameter to the operator.
8732 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8733 ClassLoc, ClassLoc, /*Id=*/0,
8734 ArgType, /*TInfo=*/0,
8735 SC_None,
8736 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008737 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008738
Richard Smithbc2a35d2012-12-08 08:32:28 +00008739 AddOverriddenMethods(ClassDecl, MoveAssignment);
8740
8741 MoveAssignment->setTrivial(
8742 ClassDecl->needsOverloadResolutionForMoveAssignment()
8743 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8744 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008745
8746 // C++0x [class.copy]p9:
8747 // If the definition of a class X does not explicitly declare a move
8748 // assignment operator, one will be implicitly declared as defaulted if and
8749 // only if:
8750 // [...]
8751 // - the move assignment operator would not be implicitly defined as
8752 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008753 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008754 // Cache this result so that we don't try to generate this over and over
8755 // on every lookup, leaking memory and wasting time.
8756 ClassDecl->setFailedImplicitMoveAssignment();
8757 return 0;
8758 }
8759
Richard Smithbc2a35d2012-12-08 08:32:28 +00008760 // Note that we have added this copy-assignment operator.
8761 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8762
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008763 if (Scope *S = getScopeForContext(ClassDecl))
8764 PushOnScopeChains(MoveAssignment, S, false);
8765 ClassDecl->addDecl(MoveAssignment);
8766
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008767 return MoveAssignment;
8768}
8769
8770void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8771 CXXMethodDecl *MoveAssignOperator) {
8772 assert((MoveAssignOperator->isDefaulted() &&
8773 MoveAssignOperator->isOverloadedOperator() &&
8774 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008775 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8776 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008777 "DefineImplicitMoveAssignment called for wrong function");
8778
8779 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8780
8781 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8782 MoveAssignOperator->setInvalidDecl();
8783 return;
8784 }
8785
8786 MoveAssignOperator->setUsed();
8787
Eli Friedman9a14db32012-10-18 20:14:08 +00008788 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008789 DiagnosticErrorTrap Trap(Diags);
8790
8791 // C++0x [class.copy]p28:
8792 // The implicitly-defined or move assignment operator for a non-union class
8793 // X performs memberwise move assignment of its subobjects. The direct base
8794 // classes of X are assigned first, in the order of their declaration in the
8795 // base-specifier-list, and then the immediate non-static data members of X
8796 // are assigned, in the order in which they were declared in the class
8797 // definition.
8798
8799 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008800 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008801
8802 // The parameter for the "other" object, which we are move from.
8803 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8804 QualType OtherRefType = Other->getType()->
8805 getAs<RValueReferenceType>()->getPointeeType();
8806 assert(OtherRefType.getQualifiers() == 0 &&
8807 "Bad argument type of defaulted move assignment");
8808
8809 // Our location for everything implicitly-generated.
8810 SourceLocation Loc = MoveAssignOperator->getLocation();
8811
8812 // Construct a reference to the "other" object. We'll be using this
8813 // throughout the generated ASTs.
8814 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8815 assert(OtherRef && "Reference to parameter cannot fail!");
8816 // Cast to rvalue.
8817 OtherRef = CastForMoving(*this, OtherRef);
8818
8819 // Construct the "this" pointer. We'll be using this throughout the generated
8820 // ASTs.
8821 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8822 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008823
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008824 // Assign base classes.
8825 bool Invalid = false;
8826 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8827 E = ClassDecl->bases_end(); Base != E; ++Base) {
8828 // Form the assignment:
8829 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8830 QualType BaseType = Base->getType().getUnqualifiedType();
8831 if (!BaseType->isRecordType()) {
8832 Invalid = true;
8833 continue;
8834 }
8835
8836 CXXCastPath BasePath;
8837 BasePath.push_back(Base);
8838
8839 // Construct the "from" expression, which is an implicit cast to the
8840 // appropriately-qualified base type.
8841 Expr *From = OtherRef;
8842 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008843 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008844
8845 // Dereference "this".
8846 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8847
8848 // Implicitly cast "this" to the appropriately-qualified base type.
8849 To = ImpCastExprToType(To.take(),
8850 Context.getCVRQualifiedType(BaseType,
8851 MoveAssignOperator->getTypeQualifiers()),
8852 CK_UncheckedDerivedToBase,
8853 VK_LValue, &BasePath);
8854
8855 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00008856 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008857 To.get(), From,
8858 /*CopyingBaseSubobject=*/true,
8859 /*Copying=*/false);
8860 if (Move.isInvalid()) {
8861 Diag(CurrentLocation, diag::note_member_synthesized_at)
8862 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8863 MoveAssignOperator->setInvalidDecl();
8864 return;
8865 }
8866
8867 // Success! Record the move.
8868 Statements.push_back(Move.takeAs<Expr>());
8869 }
8870
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008871 // Assign non-static members.
8872 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8873 FieldEnd = ClassDecl->field_end();
8874 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008875 if (Field->isUnnamedBitfield())
8876 continue;
8877
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008878 // Check for members of reference type; we can't move those.
8879 if (Field->getType()->isReferenceType()) {
8880 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8881 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8882 Diag(Field->getLocation(), diag::note_declared_at);
8883 Diag(CurrentLocation, diag::note_member_synthesized_at)
8884 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8885 Invalid = true;
8886 continue;
8887 }
8888
8889 // Check for members of const-qualified, non-class type.
8890 QualType BaseType = Context.getBaseElementType(Field->getType());
8891 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8892 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8893 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8894 Diag(Field->getLocation(), diag::note_declared_at);
8895 Diag(CurrentLocation, diag::note_member_synthesized_at)
8896 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8897 Invalid = true;
8898 continue;
8899 }
8900
8901 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008902 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8903 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008904
8905 QualType FieldType = Field->getType().getNonReferenceType();
8906 if (FieldType->isIncompleteArrayType()) {
8907 assert(ClassDecl->hasFlexibleArrayMember() &&
8908 "Incomplete array type is not valid");
8909 continue;
8910 }
8911
8912 // Build references to the field in the object we're copying from and to.
8913 CXXScopeSpec SS; // Intentionally empty
8914 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8915 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008916 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008917 MemberLookup.resolveKind();
8918 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8919 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008920 SS, SourceLocation(), 0,
8921 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008922 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8923 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008924 SS, SourceLocation(), 0,
8925 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008926 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8927 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8928
8929 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8930 "Member reference with rvalue base must be rvalue except for reference "
8931 "members, which aren't allowed for move assignment.");
8932
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008933 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008934 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008935 To.get(), From.get(),
8936 /*CopyingBaseSubobject=*/false,
8937 /*Copying=*/false);
8938 if (Move.isInvalid()) {
8939 Diag(CurrentLocation, diag::note_member_synthesized_at)
8940 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8941 MoveAssignOperator->setInvalidDecl();
8942 return;
8943 }
Richard Smithe7ce7092012-11-12 23:33:00 +00008944
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008945 // Success! Record the copy.
8946 Statements.push_back(Move.takeAs<Stmt>());
8947 }
8948
8949 if (!Invalid) {
8950 // Add a "return *this;"
8951 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8952
8953 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8954 if (Return.isInvalid())
8955 Invalid = true;
8956 else {
8957 Statements.push_back(Return.takeAs<Stmt>());
8958
8959 if (Trap.hasErrorOccurred()) {
8960 Diag(CurrentLocation, diag::note_member_synthesized_at)
8961 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8962 Invalid = true;
8963 }
8964 }
8965 }
8966
8967 if (Invalid) {
8968 MoveAssignOperator->setInvalidDecl();
8969 return;
8970 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008971
8972 StmtResult Body;
8973 {
8974 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008975 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008976 /*isStmtExpr=*/false);
8977 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8978 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008979 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8980
8981 if (ASTMutationListener *L = getASTMutationListener()) {
8982 L->CompletedImplicitDefinition(MoveAssignOperator);
8983 }
8984}
8985
Richard Smithb9d0b762012-07-27 04:22:15 +00008986Sema::ImplicitExceptionSpecification
8987Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
8988 CXXRecordDecl *ClassDecl = MD->getParent();
8989
8990 ImplicitExceptionSpecification ExceptSpec(*this);
8991 if (ClassDecl->isInvalidDecl())
8992 return ExceptSpec;
8993
8994 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8995 assert(T->getNumArgs() >= 1 && "not a copy ctor");
8996 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8997
Douglas Gregor0d405db2010-07-01 20:59:04 +00008998 // C++ [except.spec]p14:
8999 // An implicitly declared special member function (Clause 12) shall have an
9000 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009001 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9002 BaseEnd = ClassDecl->bases_end();
9003 Base != BaseEnd;
9004 ++Base) {
9005 // Virtual bases are handled below.
9006 if (Base->isVirtual())
9007 continue;
9008
Douglas Gregor22584312010-07-02 23:41:54 +00009009 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009010 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009011 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009012 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009013 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009014 }
9015 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9016 BaseEnd = ClassDecl->vbases_end();
9017 Base != BaseEnd;
9018 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009019 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009020 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009021 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009022 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009023 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009024 }
9025 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9026 FieldEnd = ClassDecl->field_end();
9027 Field != FieldEnd;
9028 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009029 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009030 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9031 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009032 LookupCopyingConstructor(FieldClassDecl,
9033 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009034 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009035 }
9036 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009037
Richard Smithb9d0b762012-07-27 04:22:15 +00009038 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009039}
9040
9041CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9042 CXXRecordDecl *ClassDecl) {
9043 // C++ [class.copy]p4:
9044 // If the class definition does not explicitly declare a copy
9045 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009046 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009047
Richard Smithafb49182012-11-29 01:34:07 +00009048 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9049 if (DSM.isAlreadyBeingDeclared())
9050 return 0;
9051
Sean Hunt49634cf2011-05-13 06:10:58 +00009052 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9053 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009054 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009055 if (Const)
9056 ArgType = ArgType.withConst();
9057 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009058
Richard Smith7756afa2012-06-10 05:43:50 +00009059 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9060 CXXCopyConstructor,
9061 Const);
9062
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009063 DeclarationName Name
9064 = Context.DeclarationNames.getCXXConstructorName(
9065 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009066 SourceLocation ClassLoc = ClassDecl->getLocation();
9067 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009068
9069 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009070 // member of its class.
9071 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009072 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009073 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009074 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009075 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009076 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009077
Richard Smithb9d0b762012-07-27 04:22:15 +00009078 // Build an exception specification pointing back at this member.
9079 FunctionProtoType::ExtProtoInfo EPI;
9080 EPI.ExceptionSpecType = EST_Unevaluated;
9081 EPI.ExceptionSpecDecl = CopyConstructor;
9082 CopyConstructor->setType(
9083 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9084
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009085 // Add the parameter to the constructor.
9086 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009087 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009088 /*IdentifierInfo=*/0,
9089 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009090 SC_None,
9091 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009092 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009093
Richard Smithbc2a35d2012-12-08 08:32:28 +00009094 CopyConstructor->setTrivial(
9095 ClassDecl->needsOverloadResolutionForCopyConstructor()
9096 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9097 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009098
Nico Weberafcc96a2012-01-23 03:19:29 +00009099 // C++11 [class.copy]p8:
9100 // ... If the class definition does not explicitly declare a copy
9101 // constructor, there is no user-declared move constructor, and there is no
9102 // user-declared move assignment operator, a copy constructor is implicitly
9103 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009104 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00009105 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00009106
Richard Smithbc2a35d2012-12-08 08:32:28 +00009107 // Note that we have declared this constructor.
9108 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9109
9110 if (Scope *S = getScopeForContext(ClassDecl))
9111 PushOnScopeChains(CopyConstructor, S, false);
9112 ClassDecl->addDecl(CopyConstructor);
9113
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009114 return CopyConstructor;
9115}
9116
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009117void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009118 CXXConstructorDecl *CopyConstructor) {
9119 assert((CopyConstructor->isDefaulted() &&
9120 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009121 !CopyConstructor->doesThisDeclarationHaveABody() &&
9122 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009123 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009124
Anders Carlsson63010a72010-04-23 16:24:12 +00009125 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009126 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009127
Eli Friedman9a14db32012-10-18 20:14:08 +00009128 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009129 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009130
David Blaikie93c86172013-01-17 05:26:25 +00009131 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009132 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009133 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009134 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009135 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009136 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009137 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009138 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9139 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009140 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009141 /*isStmtExpr=*/false)
9142 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009143 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009144 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009145
9146 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009147 if (ASTMutationListener *L = getASTMutationListener()) {
9148 L->CompletedImplicitDefinition(CopyConstructor);
9149 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009150}
9151
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009152Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009153Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9154 CXXRecordDecl *ClassDecl = MD->getParent();
9155
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009156 // C++ [except.spec]p14:
9157 // An implicitly declared special member function (Clause 12) shall have an
9158 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009159 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009160 if (ClassDecl->isInvalidDecl())
9161 return ExceptSpec;
9162
9163 // Direct base-class constructors.
9164 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9165 BEnd = ClassDecl->bases_end();
9166 B != BEnd; ++B) {
9167 if (B->isVirtual()) // Handled below.
9168 continue;
9169
9170 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9171 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009172 CXXConstructorDecl *Constructor =
9173 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009174 // If this is a deleted function, add it anyway. This might be conformant
9175 // with the standard. This might not. I'm not sure. It might not matter.
9176 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009177 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009178 }
9179 }
9180
9181 // Virtual base-class constructors.
9182 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9183 BEnd = ClassDecl->vbases_end();
9184 B != BEnd; ++B) {
9185 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9186 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009187 CXXConstructorDecl *Constructor =
9188 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009189 // If this is a deleted function, add it anyway. This might be conformant
9190 // with the standard. This might not. I'm not sure. It might not matter.
9191 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009192 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009193 }
9194 }
9195
9196 // Field constructors.
9197 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9198 FEnd = ClassDecl->field_end();
9199 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009200 QualType FieldType = Context.getBaseElementType(F->getType());
9201 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9202 CXXConstructorDecl *Constructor =
9203 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009204 // If this is a deleted function, add it anyway. This might be conformant
9205 // with the standard. This might not. I'm not sure. It might not matter.
9206 // In particular, the problem is that this function never gets called. It
9207 // might just be ill-formed because this function attempts to refer to
9208 // a deleted function here.
9209 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009210 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009211 }
9212 }
9213
9214 return ExceptSpec;
9215}
9216
9217CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9218 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009219 // C++11 [class.copy]p9:
9220 // If the definition of a class X does not explicitly declare a move
9221 // constructor, one will be implicitly declared as defaulted if and only if:
9222 //
9223 // - [first 4 bullets]
9224 assert(ClassDecl->needsImplicitMoveConstructor());
9225
Richard Smithafb49182012-11-29 01:34:07 +00009226 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9227 if (DSM.isAlreadyBeingDeclared())
9228 return 0;
9229
Richard Smith1c931be2012-04-02 18:40:40 +00009230 // [Checked after we build the declaration]
9231 // - the move assignment operator would not be implicitly defined as
9232 // deleted,
9233
9234 // [DR1402]:
9235 // - each of X's non-static data members and direct or virtual base classes
9236 // has a type that either has a move constructor or is trivially copyable.
9237 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9238 ClassDecl->setFailedImplicitMoveConstructor();
9239 return 0;
9240 }
9241
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009242 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9243 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009244
Richard Smith7756afa2012-06-10 05:43:50 +00009245 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9246 CXXMoveConstructor,
9247 false);
9248
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009249 DeclarationName Name
9250 = Context.DeclarationNames.getCXXConstructorName(
9251 Context.getCanonicalType(ClassType));
9252 SourceLocation ClassLoc = ClassDecl->getLocation();
9253 DeclarationNameInfo NameInfo(Name, ClassLoc);
9254
9255 // C++0x [class.copy]p11:
9256 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009257 // member of its class.
9258 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009259 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009260 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009261 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009262 MoveConstructor->setAccess(AS_public);
9263 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009264
Richard Smithb9d0b762012-07-27 04:22:15 +00009265 // Build an exception specification pointing back at this member.
9266 FunctionProtoType::ExtProtoInfo EPI;
9267 EPI.ExceptionSpecType = EST_Unevaluated;
9268 EPI.ExceptionSpecDecl = MoveConstructor;
9269 MoveConstructor->setType(
9270 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9271
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009272 // Add the parameter to the constructor.
9273 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9274 ClassLoc, ClassLoc,
9275 /*IdentifierInfo=*/0,
9276 ArgType, /*TInfo=*/0,
9277 SC_None,
9278 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009279 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009280
Richard Smithbc2a35d2012-12-08 08:32:28 +00009281 MoveConstructor->setTrivial(
9282 ClassDecl->needsOverloadResolutionForMoveConstructor()
9283 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9284 : ClassDecl->hasTrivialMoveConstructor());
9285
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009286 // C++0x [class.copy]p9:
9287 // If the definition of a class X does not explicitly declare a move
9288 // constructor, one will be implicitly declared as defaulted if and only if:
9289 // [...]
9290 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009291 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009292 // Cache this result so that we don't try to generate this over and over
9293 // on every lookup, leaking memory and wasting time.
9294 ClassDecl->setFailedImplicitMoveConstructor();
9295 return 0;
9296 }
9297
9298 // Note that we have declared this constructor.
9299 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9300
9301 if (Scope *S = getScopeForContext(ClassDecl))
9302 PushOnScopeChains(MoveConstructor, S, false);
9303 ClassDecl->addDecl(MoveConstructor);
9304
9305 return MoveConstructor;
9306}
9307
9308void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9309 CXXConstructorDecl *MoveConstructor) {
9310 assert((MoveConstructor->isDefaulted() &&
9311 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009312 !MoveConstructor->doesThisDeclarationHaveABody() &&
9313 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009314 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9315
9316 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9317 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9318
Eli Friedman9a14db32012-10-18 20:14:08 +00009319 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009320 DiagnosticErrorTrap Trap(Diags);
9321
David Blaikie93c86172013-01-17 05:26:25 +00009322 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009323 Trap.hasErrorOccurred()) {
9324 Diag(CurrentLocation, diag::note_member_synthesized_at)
9325 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9326 MoveConstructor->setInvalidDecl();
9327 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009328 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009329 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9330 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009331 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009332 /*isStmtExpr=*/false)
9333 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009334 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009335 }
9336
9337 MoveConstructor->setUsed();
9338
9339 if (ASTMutationListener *L = getASTMutationListener()) {
9340 L->CompletedImplicitDefinition(MoveConstructor);
9341 }
9342}
9343
Douglas Gregore4e68d42012-02-15 19:33:52 +00009344bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9345 return FD->isDeleted() &&
9346 (FD->isDefaulted() || FD->isImplicit()) &&
9347 isa<CXXMethodDecl>(FD);
9348}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009349
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009350/// \brief Mark the call operator of the given lambda closure type as "used".
9351static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9352 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009353 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009354 Lambda->lookup(
9355 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009356 CallOperator->setReferenced();
9357 CallOperator->setUsed();
9358}
9359
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009360void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9361 SourceLocation CurrentLocation,
9362 CXXConversionDecl *Conv)
9363{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009364 CXXRecordDecl *Lambda = Conv->getParent();
9365
9366 // Make sure that the lambda call operator is marked used.
9367 markLambdaCallOperatorUsed(*this, Lambda);
9368
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009369 Conv->setUsed();
9370
Eli Friedman9a14db32012-10-18 20:14:08 +00009371 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009372 DiagnosticErrorTrap Trap(Diags);
9373
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009374 // Return the address of the __invoke function.
9375 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9376 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009377 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009378 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9379 VK_LValue, Conv->getLocation()).take();
9380 assert(FunctionRef && "Can't refer to __invoke function?");
9381 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009382 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009383 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009384 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009385
9386 // Fill in the __invoke function with a dummy implementation. IR generation
9387 // will fill in the actual details.
9388 Invoke->setUsed();
9389 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009390 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009391
9392 if (ASTMutationListener *L = getASTMutationListener()) {
9393 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009394 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009395 }
9396}
9397
9398void Sema::DefineImplicitLambdaToBlockPointerConversion(
9399 SourceLocation CurrentLocation,
9400 CXXConversionDecl *Conv)
9401{
9402 Conv->setUsed();
9403
Eli Friedman9a14db32012-10-18 20:14:08 +00009404 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009405 DiagnosticErrorTrap Trap(Diags);
9406
Douglas Gregorac1303e2012-02-22 05:02:47 +00009407 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009408 Expr *This = ActOnCXXThis(CurrentLocation).take();
9409 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009410
Eli Friedman23f02672012-03-01 04:01:32 +00009411 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9412 Conv->getLocation(),
9413 Conv, DerefThis);
9414
9415 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9416 // behavior. Note that only the general conversion function does this
9417 // (since it's unusable otherwise); in the case where we inline the
9418 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009419 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009420 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9421 CK_CopyAndAutoreleaseBlockObject,
9422 BuildBlock.get(), 0, VK_RValue);
9423
9424 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009425 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009426 Conv->setInvalidDecl();
9427 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009428 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009429
Douglas Gregorac1303e2012-02-22 05:02:47 +00009430 // Create the return statement that returns the block from the conversion
9431 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009432 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009433 if (Return.isInvalid()) {
9434 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9435 Conv->setInvalidDecl();
9436 return;
9437 }
9438
9439 // Set the body of the conversion function.
9440 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009441 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009442 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009443 Conv->getLocation()));
9444
Douglas Gregorac1303e2012-02-22 05:02:47 +00009445 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009446 if (ASTMutationListener *L = getASTMutationListener()) {
9447 L->CompletedImplicitDefinition(Conv);
9448 }
9449}
9450
Douglas Gregorf52757d2012-03-10 06:53:13 +00009451/// \brief Determine whether the given list arguments contains exactly one
9452/// "real" (non-default) argument.
9453static bool hasOneRealArgument(MultiExprArg Args) {
9454 switch (Args.size()) {
9455 case 0:
9456 return false;
9457
9458 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009459 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009460 return false;
9461
9462 // fall through
9463 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009464 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009465 }
9466
9467 return false;
9468}
9469
John McCall60d7b3a2010-08-24 06:29:42 +00009470ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009471Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009472 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009473 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009474 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009475 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009476 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009477 unsigned ConstructKind,
9478 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009479 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009480
Douglas Gregor2f599792010-04-02 18:24:57 +00009481 // C++0x [class.copy]p34:
9482 // When certain criteria are met, an implementation is allowed to
9483 // omit the copy/move construction of a class object, even if the
9484 // copy/move constructor and/or destructor for the object have
9485 // side effects. [...]
9486 // - when a temporary class object that has not been bound to a
9487 // reference (12.2) would be copied/moved to a class object
9488 // with the same cv-unqualified type, the copy/move operation
9489 // can be omitted by constructing the temporary object
9490 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009491 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009492 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009493 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009494 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009495 }
Mike Stump1eb44332009-09-09 15:08:12 +00009496
9497 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009498 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009499 IsListInitialization, RequiresZeroInit,
9500 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009501}
9502
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009503/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9504/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009505ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009506Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9507 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009508 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009509 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009510 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009511 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009512 unsigned ConstructKind,
9513 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009514 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009515 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009516 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +00009517 HadMultipleCandidates,
9518 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009519 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9520 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009521}
9522
John McCall68c6c9a2010-02-02 09:10:11 +00009523void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009524 if (VD->isInvalidDecl()) return;
9525
John McCall68c6c9a2010-02-02 09:10:11 +00009526 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009527 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009528 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009529 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009530
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009531 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009532 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009533 CheckDestructorAccess(VD->getLocation(), Destructor,
9534 PDiag(diag::err_access_dtor_var)
9535 << VD->getDeclName()
9536 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009537 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009538
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009539 if (!VD->hasGlobalStorage()) return;
9540
9541 // Emit warning for non-trivial dtor in global scope (a real global,
9542 // class-static, function-static).
9543 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9544
9545 // TODO: this should be re-enabled for static locals by !CXAAtExit
9546 if (!VD->isStaticLocal())
9547 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009548}
9549
Douglas Gregor39da0b82009-09-09 23:08:42 +00009550/// \brief Given a constructor and the set of arguments provided for the
9551/// constructor, convert the arguments and add any required default arguments
9552/// to form a proper call to this constructor.
9553///
9554/// \returns true if an error occurred, false otherwise.
9555bool
9556Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9557 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009558 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009559 SmallVectorImpl<Expr*> &ConvertedArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009560 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009561 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9562 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009563 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009564
9565 const FunctionProtoType *Proto
9566 = Constructor->getType()->getAs<FunctionProtoType>();
9567 assert(Proto && "Constructor without a prototype?");
9568 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009569
9570 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009571 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009572 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009573 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009574 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009575
9576 VariadicCallType CallType =
9577 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009578 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009579 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9580 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009581 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009582 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009583
9584 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9585
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00009586 CheckConstructorCall(Constructor,
9587 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9588 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +00009589 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009590
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009591 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009592}
9593
Anders Carlsson20d45d22009-12-12 00:32:00 +00009594static inline bool
9595CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9596 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009597 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009598 if (isa<NamespaceDecl>(DC)) {
9599 return SemaRef.Diag(FnDecl->getLocation(),
9600 diag::err_operator_new_delete_declared_in_namespace)
9601 << FnDecl->getDeclName();
9602 }
9603
9604 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009605 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009606 return SemaRef.Diag(FnDecl->getLocation(),
9607 diag::err_operator_new_delete_declared_static)
9608 << FnDecl->getDeclName();
9609 }
9610
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009611 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009612}
9613
Anders Carlsson156c78e2009-12-13 17:53:43 +00009614static inline bool
9615CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9616 CanQualType ExpectedResultType,
9617 CanQualType ExpectedFirstParamType,
9618 unsigned DependentParamTypeDiag,
9619 unsigned InvalidParamTypeDiag) {
9620 QualType ResultType =
9621 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9622
9623 // Check that the result type is not dependent.
9624 if (ResultType->isDependentType())
9625 return SemaRef.Diag(FnDecl->getLocation(),
9626 diag::err_operator_new_delete_dependent_result_type)
9627 << FnDecl->getDeclName() << ExpectedResultType;
9628
9629 // Check that the result type is what we expect.
9630 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9631 return SemaRef.Diag(FnDecl->getLocation(),
9632 diag::err_operator_new_delete_invalid_result_type)
9633 << FnDecl->getDeclName() << ExpectedResultType;
9634
9635 // A function template must have at least 2 parameters.
9636 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9637 return SemaRef.Diag(FnDecl->getLocation(),
9638 diag::err_operator_new_delete_template_too_few_parameters)
9639 << FnDecl->getDeclName();
9640
9641 // The function decl must have at least 1 parameter.
9642 if (FnDecl->getNumParams() == 0)
9643 return SemaRef.Diag(FnDecl->getLocation(),
9644 diag::err_operator_new_delete_too_few_parameters)
9645 << FnDecl->getDeclName();
9646
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009647 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009648 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9649 if (FirstParamType->isDependentType())
9650 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9651 << FnDecl->getDeclName() << ExpectedFirstParamType;
9652
9653 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009654 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009655 ExpectedFirstParamType)
9656 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9657 << FnDecl->getDeclName() << ExpectedFirstParamType;
9658
9659 return false;
9660}
9661
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009662static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009663CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009664 // C++ [basic.stc.dynamic.allocation]p1:
9665 // A program is ill-formed if an allocation function is declared in a
9666 // namespace scope other than global scope or declared static in global
9667 // scope.
9668 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9669 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009670
9671 CanQualType SizeTy =
9672 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9673
9674 // C++ [basic.stc.dynamic.allocation]p1:
9675 // The return type shall be void*. The first parameter shall have type
9676 // std::size_t.
9677 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9678 SizeTy,
9679 diag::err_operator_new_dependent_param_type,
9680 diag::err_operator_new_param_type))
9681 return true;
9682
9683 // C++ [basic.stc.dynamic.allocation]p1:
9684 // The first parameter shall not have an associated default argument.
9685 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009686 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009687 diag::err_operator_new_default_arg)
9688 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9689
9690 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009691}
9692
9693static bool
Richard Smith444d3842012-10-20 08:26:51 +00009694CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009695 // C++ [basic.stc.dynamic.deallocation]p1:
9696 // A program is ill-formed if deallocation functions are declared in a
9697 // namespace scope other than global scope or declared static in global
9698 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009699 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9700 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009701
9702 // C++ [basic.stc.dynamic.deallocation]p2:
9703 // Each deallocation function shall return void and its first parameter
9704 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009705 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9706 SemaRef.Context.VoidPtrTy,
9707 diag::err_operator_delete_dependent_param_type,
9708 diag::err_operator_delete_param_type))
9709 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009710
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009711 return false;
9712}
9713
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009714/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9715/// of this overloaded operator is well-formed. If so, returns false;
9716/// otherwise, emits appropriate diagnostics and returns true.
9717bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009718 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009719 "Expected an overloaded operator declaration");
9720
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009721 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9722
Mike Stump1eb44332009-09-09 15:08:12 +00009723 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009724 // The allocation and deallocation functions, operator new,
9725 // operator new[], operator delete and operator delete[], are
9726 // described completely in 3.7.3. The attributes and restrictions
9727 // found in the rest of this subclause do not apply to them unless
9728 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009729 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009730 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009731
Anders Carlssona3ccda52009-12-12 00:26:23 +00009732 if (Op == OO_New || Op == OO_Array_New)
9733 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009734
9735 // C++ [over.oper]p6:
9736 // An operator function shall either be a non-static member
9737 // function or be a non-member function and have at least one
9738 // parameter whose type is a class, a reference to a class, an
9739 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009740 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9741 if (MethodDecl->isStatic())
9742 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009743 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009744 } else {
9745 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009746 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9747 ParamEnd = FnDecl->param_end();
9748 Param != ParamEnd; ++Param) {
9749 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009750 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9751 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009752 ClassOrEnumParam = true;
9753 break;
9754 }
9755 }
9756
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009757 if (!ClassOrEnumParam)
9758 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009759 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009760 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009761 }
9762
9763 // C++ [over.oper]p8:
9764 // An operator function cannot have default arguments (8.3.6),
9765 // except where explicitly stated below.
9766 //
Mike Stump1eb44332009-09-09 15:08:12 +00009767 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009768 // (C++ [over.call]p1).
9769 if (Op != OO_Call) {
9770 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9771 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009772 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009773 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009774 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009775 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009776 }
9777 }
9778
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009779 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9780 { false, false, false }
9781#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9782 , { Unary, Binary, MemberOnly }
9783#include "clang/Basic/OperatorKinds.def"
9784 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009785
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009786 bool CanBeUnaryOperator = OperatorUses[Op][0];
9787 bool CanBeBinaryOperator = OperatorUses[Op][1];
9788 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009789
9790 // C++ [over.oper]p8:
9791 // [...] Operator functions cannot have more or fewer parameters
9792 // than the number required for the corresponding operator, as
9793 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009794 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009795 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009796 if (Op != OO_Call &&
9797 ((NumParams == 1 && !CanBeUnaryOperator) ||
9798 (NumParams == 2 && !CanBeBinaryOperator) ||
9799 (NumParams < 1) || (NumParams > 2))) {
9800 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009801 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009802 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009803 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009804 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009805 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009806 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009807 assert(CanBeBinaryOperator &&
9808 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009809 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009810 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009811
Chris Lattner416e46f2008-11-21 07:57:12 +00009812 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009813 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009814 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009815
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009816 // Overloaded operators other than operator() cannot be variadic.
9817 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009818 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009819 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009820 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009821 }
9822
9823 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009824 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9825 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009826 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009827 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009828 }
9829
9830 // C++ [over.inc]p1:
9831 // The user-defined function called operator++ implements the
9832 // prefix and postfix ++ operator. If this function is a member
9833 // function with no parameters, or a non-member function with one
9834 // parameter of class or enumeration type, it defines the prefix
9835 // increment operator ++ for objects of that type. If the function
9836 // is a member function with one parameter (which shall be of type
9837 // int) or a non-member function with two parameters (the second
9838 // of which shall be of type int), it defines the postfix
9839 // increment operator ++ for objects of that type.
9840 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9841 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9842 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009843 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009844 ParamIsInt = BT->getKind() == BuiltinType::Int;
9845
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009846 if (!ParamIsInt)
9847 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009848 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009849 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009850 }
9851
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009852 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009853}
Chris Lattner5a003a42008-12-17 07:09:26 +00009854
Sean Hunta6c058d2010-01-13 09:01:02 +00009855/// CheckLiteralOperatorDeclaration - Check whether the declaration
9856/// of this literal operator function is well-formed. If so, returns
9857/// false; otherwise, emits appropriate diagnostics and returns true.
9858bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009859 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009860 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9861 << FnDecl->getDeclName();
9862 return true;
9863 }
9864
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009865 if (FnDecl->isExternC()) {
9866 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9867 return true;
9868 }
9869
Sean Hunta6c058d2010-01-13 09:01:02 +00009870 bool Valid = false;
9871
Richard Smith36f5cfe2012-03-09 08:00:36 +00009872 // This might be the definition of a literal operator template.
9873 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9874 // This might be a specialization of a literal operator template.
9875 if (!TpDecl)
9876 TpDecl = FnDecl->getPrimaryTemplate();
9877
Sean Hunt216c2782010-04-07 23:11:06 +00009878 // template <char...> type operator "" name() is the only valid template
9879 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009880 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009881 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009882 // Must have only one template parameter
9883 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9884 if (Params->size() == 1) {
9885 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009886 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009887
Sean Hunt216c2782010-04-07 23:11:06 +00009888 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009889 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9890 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9891 Valid = true;
9892 }
9893 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009894 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009895 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009896 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9897
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009898 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009899
Sean Hunt30019c02010-04-07 22:57:35 +00009900 // unsigned long long int, long double, and any character type are allowed
9901 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009902 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9903 Context.hasSameType(T, Context.LongDoubleTy) ||
9904 Context.hasSameType(T, Context.CharTy) ||
9905 Context.hasSameType(T, Context.WCharTy) ||
9906 Context.hasSameType(T, Context.Char16Ty) ||
9907 Context.hasSameType(T, Context.Char32Ty)) {
9908 if (++Param == FnDecl->param_end())
9909 Valid = true;
9910 goto FinishedParams;
9911 }
9912
Sean Hunt30019c02010-04-07 22:57:35 +00009913 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009914 const PointerType *PT = T->getAs<PointerType>();
9915 if (!PT)
9916 goto FinishedParams;
9917 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009918 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009919 goto FinishedParams;
9920 T = T.getUnqualifiedType();
9921
9922 // Move on to the second parameter;
9923 ++Param;
9924
9925 // If there is no second parameter, the first must be a const char *
9926 if (Param == FnDecl->param_end()) {
9927 if (Context.hasSameType(T, Context.CharTy))
9928 Valid = true;
9929 goto FinishedParams;
9930 }
9931
9932 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9933 // are allowed as the first parameter to a two-parameter function
9934 if (!(Context.hasSameType(T, Context.CharTy) ||
9935 Context.hasSameType(T, Context.WCharTy) ||
9936 Context.hasSameType(T, Context.Char16Ty) ||
9937 Context.hasSameType(T, Context.Char32Ty)))
9938 goto FinishedParams;
9939
9940 // The second and final parameter must be an std::size_t
9941 T = (*Param)->getType().getUnqualifiedType();
9942 if (Context.hasSameType(T, Context.getSizeType()) &&
9943 ++Param == FnDecl->param_end())
9944 Valid = true;
9945 }
9946
9947 // FIXME: This diagnostic is absolutely terrible.
9948FinishedParams:
9949 if (!Valid) {
9950 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9951 << FnDecl->getDeclName();
9952 return true;
9953 }
9954
Richard Smitha9e88b22012-03-09 08:16:22 +00009955 // A parameter-declaration-clause containing a default argument is not
9956 // equivalent to any of the permitted forms.
9957 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9958 ParamEnd = FnDecl->param_end();
9959 Param != ParamEnd; ++Param) {
9960 if ((*Param)->hasDefaultArg()) {
9961 Diag((*Param)->getDefaultArgRange().getBegin(),
9962 diag::err_literal_operator_default_argument)
9963 << (*Param)->getDefaultArgRange();
9964 break;
9965 }
9966 }
9967
Richard Smith2fb4ae32012-03-08 02:39:21 +00009968 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +00009969 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9970 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +00009971 // C++11 [usrlit.suffix]p1:
9972 // Literal suffix identifiers that do not start with an underscore
9973 // are reserved for future standardization.
9974 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +00009975 }
Richard Smith2fb4ae32012-03-08 02:39:21 +00009976
Sean Hunta6c058d2010-01-13 09:01:02 +00009977 return false;
9978}
9979
Douglas Gregor074149e2009-01-05 19:45:36 +00009980/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9981/// linkage specification, including the language and (if present)
9982/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9983/// the location of the language string literal, which is provided
9984/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9985/// the '{' brace. Otherwise, this linkage specification does not
9986/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009987Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9988 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009989 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009990 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009991 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009992 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009993 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009994 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009995 Language = LinkageSpecDecl::lang_cxx;
9996 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009997 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009998 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009999 }
Mike Stump1eb44332009-09-09 15:08:12 +000010000
Chris Lattnercc98eac2008-12-17 07:13:27 +000010001 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010002
Douglas Gregor074149e2009-01-05 19:45:36 +000010003 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010004 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010005 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010006 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010007 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010008}
10009
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010010/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010011/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10012/// valid, it's the position of the closing '}' brace in a linkage
10013/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010014Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010015 Decl *LinkageSpec,
10016 SourceLocation RBraceLoc) {
10017 if (LinkageSpec) {
10018 if (RBraceLoc.isValid()) {
10019 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10020 LSDecl->setRBraceLoc(RBraceLoc);
10021 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010022 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010023 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010024 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010025}
10026
Douglas Gregord308e622009-05-18 20:51:54 +000010027/// \brief Perform semantic analysis for the variable declaration that
10028/// occurs within a C++ catch clause, returning the newly-created
10029/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010030VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010031 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010032 SourceLocation StartLoc,
10033 SourceLocation Loc,
10034 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010035 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010036 QualType ExDeclType = TInfo->getType();
10037
Sebastian Redl4b07b292008-12-22 19:15:10 +000010038 // Arrays and functions decay.
10039 if (ExDeclType->isArrayType())
10040 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10041 else if (ExDeclType->isFunctionType())
10042 ExDeclType = Context.getPointerType(ExDeclType);
10043
10044 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10045 // The exception-declaration shall not denote a pointer or reference to an
10046 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010047 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010048 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010049 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010050 Invalid = true;
10051 }
Douglas Gregord308e622009-05-18 20:51:54 +000010052
Sebastian Redl4b07b292008-12-22 19:15:10 +000010053 QualType BaseType = ExDeclType;
10054 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010055 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010056 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010057 BaseType = Ptr->getPointeeType();
10058 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010059 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010060 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010061 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010062 BaseType = Ref->getPointeeType();
10063 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010064 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010065 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010066 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010067 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010068 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010069
Mike Stump1eb44332009-09-09 15:08:12 +000010070 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010071 RequireNonAbstractType(Loc, ExDeclType,
10072 diag::err_abstract_type_in_decl,
10073 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010074 Invalid = true;
10075
John McCall5a180392010-07-24 00:37:23 +000010076 // Only the non-fragile NeXT runtime currently supports C++ catches
10077 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010078 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010079 QualType T = ExDeclType;
10080 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10081 T = RT->getPointeeType();
10082
10083 if (T->isObjCObjectType()) {
10084 Diag(Loc, diag::err_objc_object_catch);
10085 Invalid = true;
10086 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010087 // FIXME: should this be a test for macosx-fragile specifically?
10088 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010089 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010090 }
10091 }
10092
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010093 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10094 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010095 ExDecl->setExceptionVariable(true);
10096
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010097 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010098 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010099 Invalid = true;
10100
Douglas Gregorc41b8782011-07-06 18:14:43 +000010101 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010102 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +000010103 // C++ [except.handle]p16:
10104 // The object declared in an exception-declaration or, if the
10105 // exception-declaration does not specify a name, a temporary (12.2) is
10106 // copy-initialized (8.5) from the exception object. [...]
10107 // The object is destroyed when the handler exits, after the destruction
10108 // of any automatic objects initialized within the handler.
10109 //
10110 // We just pretend to initialize the object with itself, then make sure
10111 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010112 QualType initType = ExDeclType;
10113
10114 InitializedEntity entity =
10115 InitializedEntity::InitializeVariable(ExDecl);
10116 InitializationKind initKind =
10117 InitializationKind::CreateCopy(Loc, SourceLocation());
10118
10119 Expr *opaqueValue =
10120 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10121 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10122 ExprResult result = sequence.Perform(*this, entity, initKind,
10123 MultiExprArg(&opaqueValue, 1));
10124 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010125 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010126 else {
10127 // If the constructor used was non-trivial, set this as the
10128 // "initializer".
10129 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10130 if (!construct->getConstructor()->isTrivial()) {
10131 Expr *init = MaybeCreateExprWithCleanups(construct);
10132 ExDecl->setInit(init);
10133 }
10134
10135 // And make sure it's destructable.
10136 FinalizeVarWithDestructor(ExDecl, recordType);
10137 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010138 }
10139 }
10140
Douglas Gregord308e622009-05-18 20:51:54 +000010141 if (Invalid)
10142 ExDecl->setInvalidDecl();
10143
10144 return ExDecl;
10145}
10146
10147/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10148/// handler.
John McCalld226f652010-08-21 09:40:31 +000010149Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010150 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010151 bool Invalid = D.isInvalidType();
10152
10153 // Check for unexpanded parameter packs.
10154 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10155 UPPC_ExceptionType)) {
10156 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10157 D.getIdentifierLoc());
10158 Invalid = true;
10159 }
10160
Sebastian Redl4b07b292008-12-22 19:15:10 +000010161 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010162 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010163 LookupOrdinaryName,
10164 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010165 // The scope should be freshly made just for us. There is just no way
10166 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010167 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010168 if (PrevDecl->isTemplateParameter()) {
10169 // Maybe we will complain about the shadowed template parameter.
10170 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010171 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010172 }
10173 }
10174
Chris Lattnereaaebc72009-04-25 08:06:05 +000010175 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010176 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10177 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010178 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010179 }
10180
Douglas Gregor83cb9422010-09-09 17:09:21 +000010181 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010182 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010183 D.getIdentifierLoc(),
10184 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010185 if (Invalid)
10186 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010187
Sebastian Redl4b07b292008-12-22 19:15:10 +000010188 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010189 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010190 PushOnScopeChains(ExDecl, S);
10191 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010192 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010193
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010194 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010195 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010196}
Anders Carlssonfb311762009-03-14 00:25:26 +000010197
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010198Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010199 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010200 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010201 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010202 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010203
Richard Smithe3f470a2012-07-11 22:37:56 +000010204 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10205 return 0;
10206
10207 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10208 AssertMessage, RParenLoc, false);
10209}
10210
10211Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10212 Expr *AssertExpr,
10213 StringLiteral *AssertMessage,
10214 SourceLocation RParenLoc,
10215 bool Failed) {
10216 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10217 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010218 // In a static_assert-declaration, the constant-expression shall be a
10219 // constant expression that can be contextually converted to bool.
10220 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10221 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010222 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010223
Richard Smithdaaefc52011-12-14 23:32:26 +000010224 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010225 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010226 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010227 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010228 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010229
Richard Smithe3f470a2012-07-11 22:37:56 +000010230 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010231 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010232 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010233 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010234 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010235 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010236 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010237 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010238 }
Mike Stump1eb44332009-09-09 15:08:12 +000010239
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010240 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010241 AssertExpr, AssertMessage, RParenLoc,
10242 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010243
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010244 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010245 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010246}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010247
Douglas Gregor1d869352010-04-07 16:53:43 +000010248/// \brief Perform semantic analysis of the given friend type declaration.
10249///
10250/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010251FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010252 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010253 TypeSourceInfo *TSInfo) {
10254 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10255
10256 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010257 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010258
Richard Smith6b130222011-10-18 21:39:00 +000010259 // C++03 [class.friend]p2:
10260 // An elaborated-type-specifier shall be used in a friend declaration
10261 // for a class.*
10262 //
10263 // * The class-key of the elaborated-type-specifier is required.
10264 if (!ActiveTemplateInstantiations.empty()) {
10265 // Do not complain about the form of friend template types during
10266 // template instantiation; we will already have complained when the
10267 // template was declared.
10268 } else if (!T->isElaboratedTypeSpecifier()) {
10269 // If we evaluated the type to a record type, suggest putting
10270 // a tag in front.
10271 if (const RecordType *RT = T->getAs<RecordType>()) {
10272 RecordDecl *RD = RT->getDecl();
10273
10274 std::string InsertionText = std::string(" ") + RD->getKindName();
10275
10276 Diag(TypeRange.getBegin(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010277 getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +000010278 diag::warn_cxx98_compat_unelaborated_friend_type :
10279 diag::ext_unelaborated_friend_type)
10280 << (unsigned) RD->getTagKind()
10281 << T
10282 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10283 InsertionText);
10284 } else {
10285 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010286 getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +000010287 diag::warn_cxx98_compat_nonclass_type_friend :
10288 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010289 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010290 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010291 }
Richard Smith6b130222011-10-18 21:39:00 +000010292 } else if (T->getAs<EnumType>()) {
10293 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010294 getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +000010295 diag::warn_cxx98_compat_enum_friend :
10296 diag::ext_enum_friend)
10297 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010298 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010299 }
10300
Richard Smithd6f80da2012-09-20 01:31:00 +000010301 // C++11 [class.friend]p3:
10302 // A friend declaration that does not declare a function shall have one
10303 // of the following forms:
10304 // friend elaborated-type-specifier ;
10305 // friend simple-type-specifier ;
10306 // friend typename-specifier ;
Richard Smith80ad52f2013-01-02 11:42:31 +000010307 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
Richard Smithd6f80da2012-09-20 01:31:00 +000010308 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10309
Douglas Gregor06245bf2010-04-07 17:57:12 +000010310 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010311 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010312 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010313 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010314}
10315
John McCall9a34edb2010-10-19 01:40:49 +000010316/// Handle a friend tag declaration where the scope specifier was
10317/// templated.
10318Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10319 unsigned TagSpec, SourceLocation TagLoc,
10320 CXXScopeSpec &SS,
10321 IdentifierInfo *Name, SourceLocation NameLoc,
10322 AttributeList *Attr,
10323 MultiTemplateParamsArg TempParamLists) {
10324 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10325
10326 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010327 bool Invalid = false;
10328
10329 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010330 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010331 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010332 TempParamLists.size(),
10333 /*friend*/ true,
10334 isExplicitSpecialization,
10335 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010336 if (TemplateParams->size() > 0) {
10337 // This is a declaration of a class template.
10338 if (Invalid)
10339 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010340
Eric Christopher4110e132011-07-21 05:34:24 +000010341 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10342 SS, Name, NameLoc, Attr,
10343 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010344 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010345 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010346 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010347 } else {
10348 // The "template<>" header is extraneous.
10349 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10350 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10351 isExplicitSpecialization = true;
10352 }
10353 }
10354
10355 if (Invalid) return 0;
10356
John McCall9a34edb2010-10-19 01:40:49 +000010357 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010358 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010359 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010360 isAllExplicitSpecializations = false;
10361 break;
10362 }
10363 }
10364
10365 // FIXME: don't ignore attributes.
10366
10367 // If it's explicit specializations all the way down, just forget
10368 // about the template header and build an appropriate non-templated
10369 // friend. TODO: for source fidelity, remember the headers.
10370 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010371 if (SS.isEmpty()) {
10372 bool Owned = false;
10373 bool IsDependent = false;
10374 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10375 Attr, AS_public,
10376 /*ModulePrivateLoc=*/SourceLocation(),
10377 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010378 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010379 /*ScopedEnumUsesClassTag=*/false,
10380 /*UnderlyingType=*/TypeResult());
10381 }
10382
Douglas Gregor2494dd02011-03-01 01:34:45 +000010383 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010384 ElaboratedTypeKeyword Keyword
10385 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010386 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010387 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010388 if (T.isNull())
10389 return 0;
10390
10391 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10392 if (isa<DependentNameType>(T)) {
10393 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010394 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010395 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010396 TL.setNameLoc(NameLoc);
10397 } else {
10398 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010399 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010400 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010401 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10402 }
10403
10404 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10405 TSI, FriendLoc);
10406 Friend->setAccess(AS_public);
10407 CurContext->addDecl(Friend);
10408 return Friend;
10409 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010410
10411 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10412
10413
John McCall9a34edb2010-10-19 01:40:49 +000010414
10415 // Handle the case of a templated-scope friend class. e.g.
10416 // template <class T> class A<T>::B;
10417 // FIXME: we don't support these right now.
10418 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10419 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10420 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10421 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010422 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010423 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010424 TL.setNameLoc(NameLoc);
10425
10426 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10427 TSI, FriendLoc);
10428 Friend->setAccess(AS_public);
10429 Friend->setUnsupportedFriend(true);
10430 CurContext->addDecl(Friend);
10431 return Friend;
10432}
10433
10434
John McCalldd4a3b02009-09-16 22:47:08 +000010435/// Handle a friend type declaration. This works in tandem with
10436/// ActOnTag.
10437///
10438/// Notes on friend class templates:
10439///
10440/// We generally treat friend class declarations as if they were
10441/// declaring a class. So, for example, the elaborated type specifier
10442/// in a friend declaration is required to obey the restrictions of a
10443/// class-head (i.e. no typedefs in the scope chain), template
10444/// parameters are required to match up with simple template-ids, &c.
10445/// However, unlike when declaring a template specialization, it's
10446/// okay to refer to a template specialization without an empty
10447/// template parameter declaration, e.g.
10448/// friend class A<T>::B<unsigned>;
10449/// We permit this as a special case; if there are any template
10450/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010451/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010452Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010453 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010454 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010455
10456 assert(DS.isFriendSpecified());
10457 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10458
John McCalldd4a3b02009-09-16 22:47:08 +000010459 // Try to convert the decl specifier to a type. This works for
10460 // friend templates because ActOnTag never produces a ClassTemplateDecl
10461 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010462 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010463 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10464 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010465 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010466 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010467
Douglas Gregor6ccab972010-12-16 01:14:37 +000010468 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10469 return 0;
10470
John McCalldd4a3b02009-09-16 22:47:08 +000010471 // This is definitely an error in C++98. It's probably meant to
10472 // be forbidden in C++0x, too, but the specification is just
10473 // poorly written.
10474 //
10475 // The problem is with declarations like the following:
10476 // template <T> friend A<T>::foo;
10477 // where deciding whether a class C is a friend or not now hinges
10478 // on whether there exists an instantiation of A that causes
10479 // 'foo' to equal C. There are restrictions on class-heads
10480 // (which we declare (by fiat) elaborated friend declarations to
10481 // be) that makes this tractable.
10482 //
10483 // FIXME: handle "template <> friend class A<T>;", which
10484 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010485 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010486 Diag(Loc, diag::err_tagless_friend_type_template)
10487 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010488 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010489 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010490
John McCall02cace72009-08-28 07:59:38 +000010491 // C++98 [class.friend]p1: A friend of a class is a function
10492 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010493 // This is fixed in DR77, which just barely didn't make the C++03
10494 // deadline. It's also a very silly restriction that seriously
10495 // affects inner classes and which nobody else seems to implement;
10496 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010497 //
10498 // But note that we could warn about it: it's always useless to
10499 // friend one of your own members (it's not, however, worthless to
10500 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010501
John McCalldd4a3b02009-09-16 22:47:08 +000010502 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010503 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010504 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010505 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010506 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010507 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010508 DS.getFriendSpecLoc());
10509 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010510 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010511
10512 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010513 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010514
John McCalldd4a3b02009-09-16 22:47:08 +000010515 D->setAccess(AS_public);
10516 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010517
John McCalld226f652010-08-21 09:40:31 +000010518 return D;
John McCall02cace72009-08-28 07:59:38 +000010519}
10520
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000010521NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10522 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010523 const DeclSpec &DS = D.getDeclSpec();
10524
10525 assert(DS.isFriendSpecified());
10526 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10527
10528 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010529 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010530
10531 // C++ [class.friend]p1
10532 // A friend of a class is a function or class....
10533 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010534 // It *doesn't* see through dependent types, which is correct
10535 // according to [temp.arg.type]p3:
10536 // If a declaration acquires a function type through a
10537 // type dependent on a template-parameter and this causes
10538 // a declaration that does not use the syntactic form of a
10539 // function declarator to have a function type, the program
10540 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010541 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010542 Diag(Loc, diag::err_unexpected_friend);
10543
10544 // It might be worthwhile to try to recover by creating an
10545 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010546 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010547 }
10548
10549 // C++ [namespace.memdef]p3
10550 // - If a friend declaration in a non-local class first declares a
10551 // class or function, the friend class or function is a member
10552 // of the innermost enclosing namespace.
10553 // - The name of the friend is not found by simple name lookup
10554 // until a matching declaration is provided in that namespace
10555 // scope (either before or after the class declaration granting
10556 // friendship).
10557 // - If a friend function is called, its name may be found by the
10558 // name lookup that considers functions from namespaces and
10559 // classes associated with the types of the function arguments.
10560 // - When looking for a prior declaration of a class or a function
10561 // declared as a friend, scopes outside the innermost enclosing
10562 // namespace scope are not considered.
10563
John McCall337ec3d2010-10-12 23:13:28 +000010564 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010565 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10566 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010567 assert(Name);
10568
Douglas Gregor6ccab972010-12-16 01:14:37 +000010569 // Check for unexpanded parameter packs.
10570 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10571 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10572 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10573 return 0;
10574
John McCall67d1a672009-08-06 02:15:43 +000010575 // The context we found the declaration in, or in which we should
10576 // create the declaration.
10577 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010578 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010579 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010580 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010581
John McCall337ec3d2010-10-12 23:13:28 +000010582 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010583
John McCall337ec3d2010-10-12 23:13:28 +000010584 // There are four cases here.
10585 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010586 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010587 // there as appropriate.
10588 // Recover from invalid scope qualifiers as if they just weren't there.
10589 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010590 // C++0x [namespace.memdef]p3:
10591 // If the name in a friend declaration is neither qualified nor
10592 // a template-id and the declaration is a function or an
10593 // elaborated-type-specifier, the lookup to determine whether
10594 // the entity has been previously declared shall not consider
10595 // any scopes outside the innermost enclosing namespace.
10596 // C++0x [class.friend]p11:
10597 // If a friend declaration appears in a local class and the name
10598 // specified is an unqualified name, a prior declaration is
10599 // looked up without considering scopes that are outside the
10600 // innermost enclosing non-class scope. For a friend function
10601 // declaration, if there is no prior declaration, the program is
10602 // ill-formed.
10603 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010604 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010605
John McCall29ae6e52010-10-13 05:45:15 +000010606 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010607 DC = CurContext;
10608 while (true) {
10609 // Skip class contexts. If someone can cite chapter and verse
10610 // for this behavior, that would be nice --- it's what GCC and
10611 // EDG do, and it seems like a reasonable intent, but the spec
10612 // really only says that checks for unqualified existing
10613 // declarations should stop at the nearest enclosing namespace,
10614 // not that they should only consider the nearest enclosing
10615 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010616 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010617 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010618
John McCall68263142009-11-18 22:49:29 +000010619 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010620
10621 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010622 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010623 break;
John McCall29ae6e52010-10-13 05:45:15 +000010624
John McCall8a407372010-10-14 22:22:28 +000010625 if (isTemplateId) {
10626 if (isa<TranslationUnitDecl>(DC)) break;
10627 } else {
10628 if (DC->isFileContext()) break;
10629 }
John McCall67d1a672009-08-06 02:15:43 +000010630 DC = DC->getParent();
10631 }
10632
10633 // C++ [class.friend]p1: A friend of a class is a function or
10634 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010635 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010636 // Most C++ 98 compilers do seem to give an error here, so
10637 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010638 if (!Previous.empty() && DC->Equals(CurContext))
10639 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010640 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010641 diag::warn_cxx98_compat_friend_is_member :
10642 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010643
John McCall380aaa42010-10-13 06:22:15 +000010644 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010645
Douglas Gregor883af832011-10-10 01:11:59 +000010646 // C++ [class.friend]p6:
10647 // A function can be defined in a friend declaration of a class if and
10648 // only if the class is a non-local class (9.8), the function name is
10649 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010650 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010651 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10652 }
10653
John McCall337ec3d2010-10-12 23:13:28 +000010654 // - There's a non-dependent scope specifier, in which case we
10655 // compute it and do a previous lookup there for a function
10656 // or function template.
10657 } else if (!SS.getScopeRep()->isDependent()) {
10658 DC = computeDeclContext(SS);
10659 if (!DC) return 0;
10660
10661 if (RequireCompleteDeclContext(SS, DC)) return 0;
10662
10663 LookupQualifiedName(Previous, DC);
10664
10665 // Ignore things found implicitly in the wrong scope.
10666 // TODO: better diagnostics for this case. Suggesting the right
10667 // qualified scope would be nice...
10668 LookupResult::Filter F = Previous.makeFilter();
10669 while (F.hasNext()) {
10670 NamedDecl *D = F.next();
10671 if (!DC->InEnclosingNamespaceSetOf(
10672 D->getDeclContext()->getRedeclContext()))
10673 F.erase();
10674 }
10675 F.done();
10676
10677 if (Previous.empty()) {
10678 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010679 Diag(Loc, diag::err_qualified_friend_not_found)
10680 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010681 return 0;
10682 }
10683
10684 // C++ [class.friend]p1: A friend of a class is a function or
10685 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010686 if (DC->Equals(CurContext))
10687 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010688 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010689 diag::warn_cxx98_compat_friend_is_member :
10690 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010691
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010692 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010693 // C++ [class.friend]p6:
10694 // A function can be defined in a friend declaration of a class if and
10695 // only if the class is a non-local class (9.8), the function name is
10696 // unqualified, and the function has namespace scope.
10697 SemaDiagnosticBuilder DB
10698 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10699
10700 DB << SS.getScopeRep();
10701 if (DC->isFileContext())
10702 DB << FixItHint::CreateRemoval(SS.getRange());
10703 SS.clear();
10704 }
John McCall337ec3d2010-10-12 23:13:28 +000010705
10706 // - There's a scope specifier that does not match any template
10707 // parameter lists, in which case we use some arbitrary context,
10708 // create a method or method template, and wait for instantiation.
10709 // - There's a scope specifier that does match some template
10710 // parameter lists, which we don't handle right now.
10711 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010712 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010713 // C++ [class.friend]p6:
10714 // A function can be defined in a friend declaration of a class if and
10715 // only if the class is a non-local class (9.8), the function name is
10716 // unqualified, and the function has namespace scope.
10717 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10718 << SS.getScopeRep();
10719 }
10720
John McCall337ec3d2010-10-12 23:13:28 +000010721 DC = CurContext;
10722 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010723 }
Douglas Gregor883af832011-10-10 01:11:59 +000010724
John McCall29ae6e52010-10-13 05:45:15 +000010725 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010726 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010727 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10728 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10729 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010730 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010731 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10732 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010733 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010734 }
John McCall67d1a672009-08-06 02:15:43 +000010735 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010736
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010737 // FIXME: This is an egregious hack to cope with cases where the scope stack
10738 // does not contain the declaration context, i.e., in an out-of-line
10739 // definition of a class.
10740 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10741 if (!DCScope) {
10742 FakeDCScope.setEntity(DC);
10743 DCScope = &FakeDCScope;
10744 }
10745
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010746 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010747 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010748 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010749 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010750
Douglas Gregor182ddf02009-09-28 00:08:27 +000010751 assert(ND->getDeclContext() == DC);
10752 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010753
John McCallab88d972009-08-31 22:39:49 +000010754 // Add the function declaration to the appropriate lookup tables,
10755 // adjusting the redeclarations list as necessary. We don't
10756 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010757 //
John McCallab88d972009-08-31 22:39:49 +000010758 // Also update the scope-based lookup if the target context's
10759 // lookup context is in lexical scope.
10760 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010761 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010762 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010763 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010764 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010765 }
John McCall02cace72009-08-28 07:59:38 +000010766
10767 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010768 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010769 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010770 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010771 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010772
John McCall1f2e1a92012-08-10 03:15:35 +000010773 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010774 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010775 } else {
10776 if (DC->isRecord()) CheckFriendAccess(ND);
10777
John McCall6102ca12010-10-16 06:59:13 +000010778 FunctionDecl *FD;
10779 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10780 FD = FTD->getTemplatedDecl();
10781 else
10782 FD = cast<FunctionDecl>(ND);
10783
10784 // Mark templated-scope function declarations as unsupported.
10785 if (FD->getNumTemplateParameterLists())
10786 FrD->setUnsupportedFriend(true);
10787 }
John McCall337ec3d2010-10-12 23:13:28 +000010788
John McCalld226f652010-08-21 09:40:31 +000010789 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010790}
10791
John McCalld226f652010-08-21 09:40:31 +000010792void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10793 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010794
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000010795 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000010796 if (!Fn) {
10797 Diag(DelLoc, diag::err_deleted_non_function);
10798 return;
10799 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010800 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010801 // Don't consider the implicit declaration we generate for explicit
10802 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010803 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10804 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010805 Diag(DelLoc, diag::err_deleted_decl_not_first);
10806 Diag(Prev->getLocation(), diag::note_previous_declaration);
10807 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010808 // If the declaration wasn't the first, we delete the function anyway for
10809 // recovery.
10810 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010811 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010812}
Sebastian Redl13e88542009-04-27 21:33:24 +000010813
Sean Hunte4246a62011-05-12 06:15:49 +000010814void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000010815 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000010816
10817 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010818 if (MD->getParent()->isDependentType()) {
10819 MD->setDefaulted();
10820 MD->setExplicitlyDefaulted();
10821 return;
10822 }
10823
Sean Hunte4246a62011-05-12 06:15:49 +000010824 CXXSpecialMember Member = getSpecialMember(MD);
10825 if (Member == CXXInvalid) {
10826 Diag(DefaultLoc, diag::err_default_special_members);
10827 return;
10828 }
10829
10830 MD->setDefaulted();
10831 MD->setExplicitlyDefaulted();
10832
Sean Huntcd10dec2011-05-23 23:14:04 +000010833 // If this definition appears within the record, do the checking when
10834 // the record is complete.
10835 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000010836 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000010837 // Find the uninstantiated declaration that actually had the '= default'
10838 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000010839 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000010840
10841 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010842 return;
10843
Richard Smithb9d0b762012-07-27 04:22:15 +000010844 CheckExplicitlyDefaultedSpecialMember(MD);
10845
Richard Smith1d28caf2012-12-11 01:14:52 +000010846 // The exception specification is needed because we are defining the
10847 // function.
10848 ResolveExceptionSpec(DefaultLoc,
10849 MD->getType()->castAs<FunctionProtoType>());
10850
Sean Hunte4246a62011-05-12 06:15:49 +000010851 switch (Member) {
10852 case CXXDefaultConstructor: {
10853 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010854 if (!CD->isInvalidDecl())
10855 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10856 break;
10857 }
10858
10859 case CXXCopyConstructor: {
10860 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010861 if (!CD->isInvalidDecl())
10862 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010863 break;
10864 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010865
Sean Hunt2b188082011-05-14 05:23:28 +000010866 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010867 if (!MD->isInvalidDecl())
10868 DefineImplicitCopyAssignment(DefaultLoc, MD);
10869 break;
10870 }
10871
Sean Huntcb45a0f2011-05-12 22:46:25 +000010872 case CXXDestructor: {
10873 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010874 if (!DD->isInvalidDecl())
10875 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010876 break;
10877 }
10878
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010879 case CXXMoveConstructor: {
10880 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010881 if (!CD->isInvalidDecl())
10882 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010883 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010884 }
Sean Hunt82713172011-05-25 23:16:36 +000010885
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010886 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010887 if (!MD->isInvalidDecl())
10888 DefineImplicitMoveAssignment(DefaultLoc, MD);
10889 break;
10890 }
10891
10892 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010893 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010894 }
10895 } else {
10896 Diag(DefaultLoc, diag::err_default_special_members);
10897 }
10898}
10899
Sebastian Redl13e88542009-04-27 21:33:24 +000010900static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010901 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010902 Stmt *SubStmt = *CI;
10903 if (!SubStmt)
10904 continue;
10905 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010906 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010907 diag::err_return_in_constructor_handler);
10908 if (!isa<Expr>(SubStmt))
10909 SearchForReturnInStmt(Self, SubStmt);
10910 }
10911}
10912
10913void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10914 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10915 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10916 SearchForReturnInStmt(*this, Handler);
10917 }
10918}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010919
Aaron Ballmanfff32482012-12-09 17:45:41 +000010920bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
10921 const CXXMethodDecl *Old) {
10922 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
10923 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
10924
10925 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
10926
10927 // If the calling conventions match, everything is fine
10928 if (NewCC == OldCC)
10929 return false;
10930
10931 // If either of the calling conventions are set to "default", we need to pick
10932 // something more sensible based on the target. This supports code where the
10933 // one method explicitly sets thiscall, and another has no explicit calling
10934 // convention.
10935 CallingConv Default =
10936 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
10937 if (NewCC == CC_Default)
10938 NewCC = Default;
10939 if (OldCC == CC_Default)
10940 OldCC = Default;
10941
10942 // If the calling conventions still don't match, then report the error
10943 if (NewCC != OldCC) {
10944 Diag(New->getLocation(),
10945 diag::err_conflicting_overriding_cc_attributes)
10946 << New->getDeclName() << New->getType() << Old->getType();
10947 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10948 return true;
10949 }
10950
10951 return false;
10952}
10953
Mike Stump1eb44332009-09-09 15:08:12 +000010954bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010955 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010956 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10957 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010958
Chandler Carruth73857792010-02-15 11:53:20 +000010959 if (Context.hasSameType(NewTy, OldTy) ||
10960 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010961 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010962
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010963 // Check if the return types are covariant
10964 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010965
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010966 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010967 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10968 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010969 NewClassTy = NewPT->getPointeeType();
10970 OldClassTy = OldPT->getPointeeType();
10971 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010972 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10973 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10974 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10975 NewClassTy = NewRT->getPointeeType();
10976 OldClassTy = OldRT->getPointeeType();
10977 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010978 }
10979 }
Mike Stump1eb44332009-09-09 15:08:12 +000010980
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010981 // The return types aren't either both pointers or references to a class type.
10982 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010983 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010984 diag::err_different_return_type_for_overriding_virtual_function)
10985 << New->getDeclName() << NewTy << OldTy;
10986 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010987
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010988 return true;
10989 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010990
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010991 // C++ [class.virtual]p6:
10992 // If the return type of D::f differs from the return type of B::f, the
10993 // class type in the return type of D::f shall be complete at the point of
10994 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010995 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10996 if (!RT->isBeingDefined() &&
10997 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000010998 diag::err_covariant_return_incomplete,
10999 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011000 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011001 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011002
Douglas Gregora4923eb2009-11-16 21:35:15 +000011003 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011004 // Check if the new class derives from the old class.
11005 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11006 Diag(New->getLocation(),
11007 diag::err_covariant_return_not_derived)
11008 << New->getDeclName() << NewTy << OldTy;
11009 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11010 return true;
11011 }
Mike Stump1eb44332009-09-09 15:08:12 +000011012
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011013 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011014 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011015 diag::err_covariant_return_inaccessible_base,
11016 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11017 // FIXME: Should this point to the return type?
11018 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011019 // FIXME: this note won't trigger for delayed access control
11020 // diagnostics, and it's impossible to get an undelayed error
11021 // here from access control during the original parse because
11022 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011023 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11024 return true;
11025 }
11026 }
Mike Stump1eb44332009-09-09 15:08:12 +000011027
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011028 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011029 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011030 Diag(New->getLocation(),
11031 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011032 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011033 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11034 return true;
11035 };
Mike Stump1eb44332009-09-09 15:08:12 +000011036
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011037
11038 // The new class type must have the same or less qualifiers as the old type.
11039 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11040 Diag(New->getLocation(),
11041 diag::err_covariant_return_type_class_type_more_qualified)
11042 << New->getDeclName() << NewTy << OldTy;
11043 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11044 return true;
11045 };
Mike Stump1eb44332009-09-09 15:08:12 +000011046
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011047 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011048}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011049
Douglas Gregor4ba31362009-12-01 17:24:26 +000011050/// \brief Mark the given method pure.
11051///
11052/// \param Method the method to be marked pure.
11053///
11054/// \param InitRange the source range that covers the "0" initializer.
11055bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011056 SourceLocation EndLoc = InitRange.getEnd();
11057 if (EndLoc.isValid())
11058 Method->setRangeEnd(EndLoc);
11059
Douglas Gregor4ba31362009-12-01 17:24:26 +000011060 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11061 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011062 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011063 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011064
11065 if (!Method->isInvalidDecl())
11066 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11067 << Method->getDeclName() << InitRange;
11068 return true;
11069}
11070
Douglas Gregor552e2992012-02-21 02:22:07 +000011071/// \brief Determine whether the given declaration is a static data member.
11072static bool isStaticDataMember(Decl *D) {
11073 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11074 if (!Var)
11075 return false;
11076
11077 return Var->isStaticDataMember();
11078}
John McCall731ad842009-12-19 09:28:58 +000011079/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11080/// an initializer for the out-of-line declaration 'Dcl'. The scope
11081/// is a fresh scope pushed for just this purpose.
11082///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011083/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11084/// static data member of class X, names should be looked up in the scope of
11085/// class X.
John McCalld226f652010-08-21 09:40:31 +000011086void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011087 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011088 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011089
John McCall731ad842009-12-19 09:28:58 +000011090 // We should only get called for declarations with scope specifiers, like:
11091 // int foo::bar;
11092 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011093 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011094
11095 // If we are parsing the initializer for a static data member, push a
11096 // new expression evaluation context that is associated with this static
11097 // data member.
11098 if (isStaticDataMember(D))
11099 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011100}
11101
11102/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011103/// initializer for the out-of-line declaration 'D'.
11104void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011105 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011106 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011107
Douglas Gregor552e2992012-02-21 02:22:07 +000011108 if (isStaticDataMember(D))
11109 PopExpressionEvaluationContext();
11110
John McCall731ad842009-12-19 09:28:58 +000011111 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011112 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011113}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011114
11115/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11116/// C++ if/switch/while/for statement.
11117/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011118DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011119 // C++ 6.4p2:
11120 // The declarator shall not specify a function or an array.
11121 // The type-specifier-seq shall not contain typedef and shall not declare a
11122 // new class or enumeration.
11123 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11124 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011125
11126 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011127 if (!Dcl)
11128 return true;
11129
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011130 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11131 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011132 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011133 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011134 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011135
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011136 return Dcl;
11137}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011138
Douglas Gregordfe65432011-07-28 19:11:31 +000011139void Sema::LoadExternalVTableUses() {
11140 if (!ExternalSource)
11141 return;
11142
11143 SmallVector<ExternalVTableUse, 4> VTables;
11144 ExternalSource->ReadUsedVTables(VTables);
11145 SmallVector<VTableUse, 4> NewUses;
11146 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11147 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11148 = VTablesUsed.find(VTables[I].Record);
11149 // Even if a definition wasn't required before, it may be required now.
11150 if (Pos != VTablesUsed.end()) {
11151 if (!Pos->second && VTables[I].DefinitionRequired)
11152 Pos->second = true;
11153 continue;
11154 }
11155
11156 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11157 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11158 }
11159
11160 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11161}
11162
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011163void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11164 bool DefinitionRequired) {
11165 // Ignore any vtable uses in unevaluated operands or for classes that do
11166 // not have a vtable.
11167 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11168 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011169 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011170 return;
11171
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011172 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011173 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011174 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11175 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11176 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11177 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011178 // If we already had an entry, check to see if we are promoting this vtable
11179 // to required a definition. If so, we need to reappend to the VTableUses
11180 // list, since we may have already processed the first entry.
11181 if (DefinitionRequired && !Pos.first->second) {
11182 Pos.first->second = true;
11183 } else {
11184 // Otherwise, we can early exit.
11185 return;
11186 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011187 }
11188
11189 // Local classes need to have their virtual members marked
11190 // immediately. For all other classes, we mark their virtual members
11191 // at the end of the translation unit.
11192 if (Class->isLocalClass())
11193 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011194 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011195 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011196}
11197
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011198bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011199 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011200 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011201 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011202
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011203 // Note: The VTableUses vector could grow as a result of marking
11204 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011205 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011206 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011207 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011208 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011209 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011210 if (!Class)
11211 continue;
11212
11213 SourceLocation Loc = VTableUses[I].second;
11214
Richard Smithb9d0b762012-07-27 04:22:15 +000011215 bool DefineVTable = true;
11216
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011217 // If this class has a key function, but that key function is
11218 // defined in another translation unit, we don't need to emit the
11219 // vtable even though we're using it.
11220 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011221 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011222 switch (KeyFunction->getTemplateSpecializationKind()) {
11223 case TSK_Undeclared:
11224 case TSK_ExplicitSpecialization:
11225 case TSK_ExplicitInstantiationDeclaration:
11226 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011227 DefineVTable = false;
11228 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011229
11230 case TSK_ExplicitInstantiationDefinition:
11231 case TSK_ImplicitInstantiation:
11232 // We will be instantiating the key function.
11233 break;
11234 }
11235 } else if (!KeyFunction) {
11236 // If we have a class with no key function that is the subject
11237 // of an explicit instantiation declaration, suppress the
11238 // vtable; it will live with the explicit instantiation
11239 // definition.
11240 bool IsExplicitInstantiationDeclaration
11241 = Class->getTemplateSpecializationKind()
11242 == TSK_ExplicitInstantiationDeclaration;
11243 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11244 REnd = Class->redecls_end();
11245 R != REnd; ++R) {
11246 TemplateSpecializationKind TSK
11247 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11248 if (TSK == TSK_ExplicitInstantiationDeclaration)
11249 IsExplicitInstantiationDeclaration = true;
11250 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11251 IsExplicitInstantiationDeclaration = false;
11252 break;
11253 }
11254 }
11255
11256 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011257 DefineVTable = false;
11258 }
11259
11260 // The exception specifications for all virtual members may be needed even
11261 // if we are not providing an authoritative form of the vtable in this TU.
11262 // We may choose to emit it available_externally anyway.
11263 if (!DefineVTable) {
11264 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11265 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011266 }
11267
11268 // Mark all of the virtual members of this class as referenced, so
11269 // that we can build a vtable. Then, tell the AST consumer that a
11270 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011271 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011272 MarkVirtualMembersReferenced(Loc, Class);
11273 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11274 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11275
11276 // Optionally warn if we're emitting a weak vtable.
11277 if (Class->getLinkage() == ExternalLinkage &&
11278 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011279 const FunctionDecl *KeyFunctionDef = 0;
11280 if (!KeyFunction ||
11281 (KeyFunction->hasBody(KeyFunctionDef) &&
11282 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011283 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11284 TSK_ExplicitInstantiationDefinition
11285 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11286 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011287 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011288 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011289 VTableUses.clear();
11290
Douglas Gregor78844032011-04-22 22:25:37 +000011291 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011292}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011293
Richard Smithb9d0b762012-07-27 04:22:15 +000011294void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11295 const CXXRecordDecl *RD) {
11296 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11297 E = RD->method_end(); I != E; ++I)
11298 if ((*I)->isVirtual() && !(*I)->isPure())
11299 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11300}
11301
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011302void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11303 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011304 // Mark all functions which will appear in RD's vtable as used.
11305 CXXFinalOverriderMap FinalOverriders;
11306 RD->getFinalOverriders(FinalOverriders);
11307 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11308 E = FinalOverriders.end();
11309 I != E; ++I) {
11310 for (OverridingMethods::const_iterator OI = I->second.begin(),
11311 OE = I->second.end();
11312 OI != OE; ++OI) {
11313 assert(OI->second.size() > 0 && "no final overrider");
11314 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011315
Richard Smithff817f72012-07-07 06:59:51 +000011316 // C++ [basic.def.odr]p2:
11317 // [...] A virtual member function is used if it is not pure. [...]
11318 if (!Overrider->isPure())
11319 MarkFunctionReferenced(Loc, Overrider);
11320 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011321 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011322
11323 // Only classes that have virtual bases need a VTT.
11324 if (RD->getNumVBases() == 0)
11325 return;
11326
11327 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11328 e = RD->bases_end(); i != e; ++i) {
11329 const CXXRecordDecl *Base =
11330 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011331 if (Base->getNumVBases() == 0)
11332 continue;
11333 MarkVirtualMembersReferenced(Loc, Base);
11334 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011335}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011336
11337/// SetIvarInitializers - This routine builds initialization ASTs for the
11338/// Objective-C implementation whose ivars need be initialized.
11339void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011340 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011341 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011342 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011343 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011344 CollectIvarsToConstructOrDestruct(OID, ivars);
11345 if (ivars.empty())
11346 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011347 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011348 for (unsigned i = 0; i < ivars.size(); i++) {
11349 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011350 if (Field->isInvalidDecl())
11351 continue;
11352
Sean Huntcbb67482011-01-08 20:30:50 +000011353 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011354 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11355 InitializationKind InitKind =
11356 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11357
11358 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011359 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011360 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011361 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011362 // Note, MemberInit could actually come back empty if no initialization
11363 // is required (e.g., because it would call a trivial default constructor)
11364 if (!MemberInit.get() || MemberInit.isInvalid())
11365 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011366
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011367 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011368 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11369 SourceLocation(),
11370 MemberInit.takeAs<Expr>(),
11371 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011372 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011373
11374 // Be sure that the destructor is accessible and is marked as referenced.
11375 if (const RecordType *RecordTy
11376 = Context.getBaseElementType(Field->getType())
11377 ->getAs<RecordType>()) {
11378 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011379 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011380 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011381 CheckDestructorAccess(Field->getLocation(), Destructor,
11382 PDiag(diag::err_access_dtor_ivar)
11383 << Context.getBaseElementType(Field->getType()));
11384 }
11385 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011386 }
11387 ObjCImplementation->setIvarInitializers(Context,
11388 AllToInit.data(), AllToInit.size());
11389 }
11390}
Sean Huntfe57eef2011-05-04 05:57:24 +000011391
Sean Huntebcbe1d2011-05-04 23:29:54 +000011392static
11393void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11394 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11395 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11396 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11397 Sema &S) {
11398 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11399 CE = Current.end();
11400 if (Ctor->isInvalidDecl())
11401 return;
11402
Richard Smitha8eaf002012-08-23 06:16:52 +000011403 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11404
11405 // Target may not be determinable yet, for instance if this is a dependent
11406 // call in an uninstantiated template.
11407 if (Target) {
11408 const FunctionDecl *FNTarget = 0;
11409 (void)Target->hasBody(FNTarget);
11410 Target = const_cast<CXXConstructorDecl*>(
11411 cast_or_null<CXXConstructorDecl>(FNTarget));
11412 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011413
11414 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11415 // Avoid dereferencing a null pointer here.
11416 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11417
11418 if (!Current.insert(Canonical))
11419 return;
11420
11421 // We know that beyond here, we aren't chaining into a cycle.
11422 if (!Target || !Target->isDelegatingConstructor() ||
11423 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11424 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11425 Valid.insert(*CI);
11426 Current.clear();
11427 // We've hit a cycle.
11428 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11429 Current.count(TCanonical)) {
11430 // If we haven't diagnosed this cycle yet, do so now.
11431 if (!Invalid.count(TCanonical)) {
11432 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011433 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011434 << Ctor;
11435
Richard Smitha8eaf002012-08-23 06:16:52 +000011436 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011437 if (TCanonical != Canonical)
11438 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11439
11440 CXXConstructorDecl *C = Target;
11441 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011442 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011443 (void)C->getTargetConstructor()->hasBody(FNTarget);
11444 assert(FNTarget && "Ctor cycle through bodiless function");
11445
Richard Smitha8eaf002012-08-23 06:16:52 +000011446 C = const_cast<CXXConstructorDecl*>(
11447 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011448 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11449 }
11450 }
11451
11452 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11453 Invalid.insert(*CI);
11454 Current.clear();
11455 } else {
11456 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11457 }
11458}
11459
11460
Sean Huntfe57eef2011-05-04 05:57:24 +000011461void Sema::CheckDelegatingCtorCycles() {
11462 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11463
Sean Huntebcbe1d2011-05-04 23:29:54 +000011464 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11465 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011466
Douglas Gregor0129b562011-07-27 21:57:17 +000011467 for (DelegatingCtorDeclsType::iterator
11468 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011469 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011470 I != E; ++I)
11471 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011472
11473 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11474 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011475}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011476
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011477namespace {
11478 /// \brief AST visitor that finds references to the 'this' expression.
11479 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11480 Sema &S;
11481
11482 public:
11483 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11484
11485 bool VisitCXXThisExpr(CXXThisExpr *E) {
11486 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11487 << E->isImplicit();
11488 return false;
11489 }
11490 };
11491}
11492
11493bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11494 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11495 if (!TSInfo)
11496 return false;
11497
11498 TypeLoc TL = TSInfo->getTypeLoc();
11499 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11500 if (!ProtoTL)
11501 return false;
11502
11503 // C++11 [expr.prim.general]p3:
11504 // [The expression this] shall not appear before the optional
11505 // cv-qualifier-seq and it shall not appear within the declaration of a
11506 // static member function (although its type and value category are defined
11507 // within a static member function as they are within a non-static member
11508 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011509 // until the complete declarator is known. - end note ]
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011510 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11511 FindCXXThisExpr Finder(*this);
11512
11513 // If the return type came after the cv-qualifier-seq, check it now.
11514 if (Proto->hasTrailingReturn() &&
11515 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11516 return true;
11517
11518 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011519 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11520 return true;
11521
11522 return checkThisInStaticMemberFunctionAttributes(Method);
11523}
11524
11525bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11526 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11527 if (!TSInfo)
11528 return false;
11529
11530 TypeLoc TL = TSInfo->getTypeLoc();
11531 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11532 if (!ProtoTL)
11533 return false;
11534
11535 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11536 FindCXXThisExpr Finder(*this);
11537
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011538 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011539 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011540 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011541 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011542 case EST_DynamicNone:
11543 case EST_MSAny:
11544 case EST_None:
11545 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011546
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011547 case EST_ComputedNoexcept:
11548 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11549 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011550
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011551 case EST_Dynamic:
11552 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011553 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011554 E != EEnd; ++E) {
11555 if (!Finder.TraverseType(*E))
11556 return true;
11557 }
11558 break;
11559 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011560
11561 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011562}
11563
11564bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11565 FindCXXThisExpr Finder(*this);
11566
11567 // Check attributes.
11568 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11569 A != AEnd; ++A) {
11570 // FIXME: This should be emitted by tblgen.
11571 Expr *Arg = 0;
11572 ArrayRef<Expr *> Args;
11573 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11574 Arg = G->getArg();
11575 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11576 Arg = G->getArg();
11577 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11578 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11579 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11580 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11581 else if (ExclusiveLockFunctionAttr *ELF
11582 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11583 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11584 else if (SharedLockFunctionAttr *SLF
11585 = dyn_cast<SharedLockFunctionAttr>(*A))
11586 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11587 else if (ExclusiveTrylockFunctionAttr *ETLF
11588 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11589 Arg = ETLF->getSuccessValue();
11590 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11591 } else if (SharedTrylockFunctionAttr *STLF
11592 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11593 Arg = STLF->getSuccessValue();
11594 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11595 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11596 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11597 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11598 Arg = LR->getArg();
11599 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11600 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11601 else if (ExclusiveLocksRequiredAttr *ELR
11602 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11603 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11604 else if (SharedLocksRequiredAttr *SLR
11605 = dyn_cast<SharedLocksRequiredAttr>(*A))
11606 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11607
11608 if (Arg && !Finder.TraverseStmt(Arg))
11609 return true;
11610
11611 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11612 if (!Finder.TraverseStmt(Args[I]))
11613 return true;
11614 }
11615 }
11616
11617 return false;
11618}
11619
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011620void
11621Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11622 ArrayRef<ParsedType> DynamicExceptions,
11623 ArrayRef<SourceRange> DynamicExceptionRanges,
11624 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011625 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011626 FunctionProtoType::ExtProtoInfo &EPI) {
11627 Exceptions.clear();
11628 EPI.ExceptionSpecType = EST;
11629 if (EST == EST_Dynamic) {
11630 Exceptions.reserve(DynamicExceptions.size());
11631 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11632 // FIXME: Preserve type source info.
11633 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11634
11635 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11636 collectUnexpandedParameterPacks(ET, Unexpanded);
11637 if (!Unexpanded.empty()) {
11638 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11639 UPPC_ExceptionType,
11640 Unexpanded);
11641 continue;
11642 }
11643
11644 // Check that the type is valid for an exception spec, and
11645 // drop it if not.
11646 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11647 Exceptions.push_back(ET);
11648 }
11649 EPI.NumExceptions = Exceptions.size();
11650 EPI.Exceptions = Exceptions.data();
11651 return;
11652 }
11653
11654 if (EST == EST_ComputedNoexcept) {
11655 // If an error occurred, there's no expression here.
11656 if (NoexceptExpr) {
11657 assert((NoexceptExpr->isTypeDependent() ||
11658 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11659 Context.BoolTy) &&
11660 "Parser should have made sure that the expression is boolean");
11661 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11662 EPI.ExceptionSpecType = EST_BasicNoexcept;
11663 return;
11664 }
11665
11666 if (!NoexceptExpr->isValueDependent())
11667 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011668 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011669 /*AllowFold*/ false).take();
11670 EPI.NoexceptExpr = NoexceptExpr;
11671 }
11672 return;
11673 }
11674}
11675
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011676/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11677Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11678 // Implicitly declared functions (e.g. copy constructors) are
11679 // __host__ __device__
11680 if (D->isImplicit())
11681 return CFT_HostDevice;
11682
11683 if (D->hasAttr<CUDAGlobalAttr>())
11684 return CFT_Global;
11685
11686 if (D->hasAttr<CUDADeviceAttr>()) {
11687 if (D->hasAttr<CUDAHostAttr>())
11688 return CFT_HostDevice;
11689 else
11690 return CFT_Device;
11691 }
11692
11693 return CFT_Host;
11694}
11695
11696bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11697 CUDAFunctionTarget CalleeTarget) {
11698 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11699 // Callable from the device only."
11700 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11701 return true;
11702
11703 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11704 // Callable from the host only."
11705 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11706 // Callable from the host only."
11707 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11708 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11709 return true;
11710
11711 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11712 return true;
11713
11714 return false;
11715}