blob: 6f1b489a2d28c6ef98e7ed3f4b7122445430869a [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"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000029#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "clang/Sema/CXXFieldCollector.h"
31#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Initialization.h"
33#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ParsedTemplate.h"
35#include "clang/Sema/Scope.h"
36#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000037#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000038#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000039#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000040#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000041
42using namespace clang;
43
Chris Lattner8123a952008-04-10 02:22:51 +000044//===----------------------------------------------------------------------===//
45// CheckDefaultArgumentVisitor
46//===----------------------------------------------------------------------===//
47
Chris Lattner9e979552008-04-12 23:52:44 +000048namespace {
49 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
50 /// the default argument of a parameter to determine whether it
51 /// contains any ill-formed subexpressions. For example, this will
52 /// diagnose the use of local variables or parameters within the
53 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000054 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000055 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000056 Expr *DefaultArg;
57 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000058
Chris Lattner9e979552008-04-12 23:52:44 +000059 public:
Mike Stump1eb44332009-09-09 15:08:12 +000060 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000061 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000062
Chris Lattner9e979552008-04-12 23:52:44 +000063 bool VisitExpr(Expr *Node);
64 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000065 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000066 bool VisitLambdaExpr(LambdaExpr *Lambda);
Chris Lattner9e979552008-04-12 23:52:44 +000067 };
Chris Lattner8123a952008-04-10 02:22:51 +000068
Chris Lattner9e979552008-04-12 23:52:44 +000069 /// VisitExpr - Visit all of the children of this expression.
70 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
71 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000072 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000073 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000074 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000075 }
76
Chris Lattner9e979552008-04-12 23:52:44 +000077 /// VisitDeclRefExpr - Visit a reference to a declaration, to
78 /// determine whether this declaration can be used in the default
79 /// argument expression.
80 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000081 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000082 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
83 // C++ [dcl.fct.default]p9
84 // Default arguments are evaluated each time the function is
85 // called. The order of evaluation of function arguments is
86 // unspecified. Consequently, parameters of a function shall not
87 // be used in default argument expressions, even if they are not
88 // evaluated. Parameters of a function declared before a default
89 // argument expression are in scope and can hide namespace and
90 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000091 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000092 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000093 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000094 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000095 // C++ [dcl.fct.default]p7
96 // Local variables shall not be used in default argument
97 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000098 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +000099 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000100 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000101 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000102 }
Chris Lattner8123a952008-04-10 02:22:51 +0000103
Douglas Gregor3996f232008-11-04 13:41:56 +0000104 return false;
105 }
Chris Lattner9e979552008-04-12 23:52:44 +0000106
Douglas Gregor796da182008-11-04 14:32:21 +0000107 /// VisitCXXThisExpr - Visit a C++ "this" expression.
108 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
109 // C++ [dcl.fct.default]p8:
110 // The keyword this shall not be used in a default argument of a
111 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000112 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000113 diag::err_param_default_argument_references_this)
114 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000115 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000116
117 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
118 // C++11 [expr.lambda.prim]p13:
119 // A lambda-expression appearing in a default argument shall not
120 // implicitly or explicitly capture any entity.
121 if (Lambda->capture_begin() == Lambda->capture_end())
122 return false;
123
124 return S->Diag(Lambda->getLocStart(),
125 diag::err_lambda_capture_default_arg);
126 }
Chris Lattner8123a952008-04-10 02:22:51 +0000127}
128
Richard Smithe6975e92012-04-17 00:58:00 +0000129void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
130 CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000131 // If we have an MSAny spec already, don't bother.
132 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000133 return;
134
135 const FunctionProtoType *Proto
136 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000137 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
138 if (!Proto)
139 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000140
141 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
142
143 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000144 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000145 ClearExceptions();
146 ComputedEST = EST;
147 return;
148 }
149
Richard Smith7a614d82011-06-11 17:19:42 +0000150 // FIXME: If the call to this decl is using any of its default arguments, we
151 // need to search them for potentially-throwing calls.
152
Sean Hunt001cad92011-05-10 00:49:42 +0000153 // If this function has a basic noexcept, it doesn't affect the outcome.
154 if (EST == EST_BasicNoexcept)
155 return;
156
157 // If we have a throw-all spec at this point, ignore the function.
158 if (ComputedEST == EST_None)
159 return;
160
161 // If we're still at noexcept(true) and there's a nothrow() callee,
162 // change to that specification.
163 if (EST == EST_DynamicNone) {
164 if (ComputedEST == EST_BasicNoexcept)
165 ComputedEST = EST_DynamicNone;
166 return;
167 }
168
169 // Check out noexcept specs.
170 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000171 FunctionProtoType::NoexceptResult NR =
172 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000173 assert(NR != FunctionProtoType::NR_NoNoexcept &&
174 "Must have noexcept result for EST_ComputedNoexcept.");
175 assert(NR != FunctionProtoType::NR_Dependent &&
176 "Should not generate implicit declarations for dependent cases, "
177 "and don't know how to handle them anyway.");
178
179 // noexcept(false) -> no spec on the new function
180 if (NR == FunctionProtoType::NR_Throw) {
181 ClearExceptions();
182 ComputedEST = EST_None;
183 }
184 // noexcept(true) won't change anything either.
185 return;
186 }
187
188 assert(EST == EST_Dynamic && "EST case not considered earlier.");
189 assert(ComputedEST != EST_None &&
190 "Shouldn't collect exceptions when throw-all is guaranteed.");
191 ComputedEST = EST_Dynamic;
192 // Record the exceptions in this function's exception specification.
193 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
194 EEnd = Proto->exception_end();
195 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000196 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000197 Exceptions.push_back(*E);
198}
199
Richard Smith7a614d82011-06-11 17:19:42 +0000200void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000201 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000202 return;
203
204 // FIXME:
205 //
206 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000207 // [An] implicit exception-specification specifies the type-id T if and
208 // only if T is allowed by the exception-specification of a function directly
209 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000210 // function it directly invokes allows all exceptions, and f shall allow no
211 // exceptions if every function it directly invokes allows no exceptions.
212 //
213 // Note in particular that if an implicit exception-specification is generated
214 // for a function containing a throw-expression, that specification can still
215 // be noexcept(true).
216 //
217 // Note also that 'directly invoked' is not defined in the standard, and there
218 // is no indication that we should only consider potentially-evaluated calls.
219 //
220 // Ultimately we should implement the intent of the standard: the exception
221 // specification should be the set of exceptions which can be thrown by the
222 // implicit definition. For now, we assume that any non-nothrow expression can
223 // throw any exception.
224
Richard Smithe6975e92012-04-17 00:58:00 +0000225 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000226 ComputedEST = EST_None;
227}
228
Anders Carlssoned961f92009-08-25 02:29:20 +0000229bool
John McCall9ae2f072010-08-23 23:25:46 +0000230Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000231 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000232 if (RequireCompleteType(Param->getLocation(), Param->getType(),
233 diag::err_typecheck_decl_incomplete_type)) {
234 Param->setInvalidDecl();
235 return true;
236 }
237
Anders Carlssoned961f92009-08-25 02:29:20 +0000238 // C++ [dcl.fct.default]p5
239 // A default argument expression is implicitly converted (clause
240 // 4) to the parameter type. The default argument expression has
241 // the same semantic constraints as the initializer expression in
242 // a declaration of a variable of the parameter type, using the
243 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000244 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
245 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000246 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
247 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000248 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000249 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000250 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000251 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000252 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000253
John McCallb4eb64d2010-10-08 02:01:28 +0000254 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000255 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Anders Carlssoned961f92009-08-25 02:29:20 +0000257 // Okay: add the default argument to the parameter
258 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000260 // We have already instantiated this parameter; provide each of the
261 // instantiations with the uninstantiated default argument.
262 UnparsedDefaultArgInstantiationsMap::iterator InstPos
263 = UnparsedDefaultArgInstantiations.find(Param);
264 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
265 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
266 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
267
268 // We're done tracking this parameter's instantiations.
269 UnparsedDefaultArgInstantiations.erase(InstPos);
270 }
271
Anders Carlsson9351c172009-08-25 03:18:48 +0000272 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000273}
274
Chris Lattner8123a952008-04-10 02:22:51 +0000275/// ActOnParamDefaultArgument - Check whether the default argument
276/// provided for a function parameter is well-formed. If so, attach it
277/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000278void
John McCalld226f652010-08-21 09:40:31 +0000279Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000280 Expr *DefaultArg) {
281 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000282 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000283
John McCalld226f652010-08-21 09:40:31 +0000284 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000285 UnparsedDefaultArgLocs.erase(Param);
286
Chris Lattner3d1cee32008-04-08 05:04:30 +0000287 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000288 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000289 Diag(EqualLoc, diag::err_param_default_argument)
290 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000291 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000292 return;
293 }
294
Douglas Gregor6f526752010-12-16 08:48:57 +0000295 // Check for unexpanded parameter packs.
296 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
297 Param->setInvalidDecl();
298 return;
299 }
300
Anders Carlsson66e30672009-08-25 01:02:06 +0000301 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000302 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
303 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000304 Param->setInvalidDecl();
305 return;
306 }
Mike Stump1eb44332009-09-09 15:08:12 +0000307
John McCall9ae2f072010-08-23 23:25:46 +0000308 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000309}
310
Douglas Gregor61366e92008-12-24 00:01:03 +0000311/// ActOnParamUnparsedDefaultArgument - We've seen a default
312/// argument for a function parameter, but we can't parse it yet
313/// because we're inside a class definition. Note that this default
314/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000315void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000316 SourceLocation EqualLoc,
317 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000318 if (!param)
319 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000320
John McCalld226f652010-08-21 09:40:31 +0000321 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000322 if (Param)
323 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Anders Carlsson5e300d12009-06-12 16:51:40 +0000325 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000326}
327
Douglas Gregor72b505b2008-12-16 21:30:33 +0000328/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
329/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000330void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000331 if (!param)
332 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000333
John McCalld226f652010-08-21 09:40:31 +0000334 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Anders Carlsson5e300d12009-06-12 16:51:40 +0000338 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000339}
340
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000341/// CheckExtraCXXDefaultArguments - Check for any extra default
342/// arguments in the declarator, which is not a function declaration
343/// or definition and therefore is not permitted to have default
344/// arguments. This routine should be invoked for every declarator
345/// that is not a function declaration or definition.
346void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
347 // C++ [dcl.fct.default]p3
348 // A default argument expression shall be specified only in the
349 // parameter-declaration-clause of a function declaration or in a
350 // template-parameter (14.1). It shall not be specified for a
351 // parameter pack. If it is specified in a
352 // parameter-declaration-clause, it shall not occur within a
353 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000354 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000355 DeclaratorChunk &chunk = D.getTypeObject(i);
356 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000357 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
358 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000359 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000360 if (Param->hasUnparsedDefaultArg()) {
361 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000362 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
363 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
364 delete Toks;
365 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000366 } else if (Param->getDefaultArg()) {
367 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
368 << Param->getDefaultArg()->getSourceRange();
369 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000370 }
371 }
372 }
373 }
374}
375
Craig Topper1a6eac82012-09-21 04:33:26 +0000376/// MergeCXXFunctionDecl - Merge two declarations of the same C++
377/// function, once we already know that they have the same
378/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
379/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000380bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
381 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000382 bool Invalid = false;
383
Chris Lattner3d1cee32008-04-08 05:04:30 +0000384 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 // For non-template functions, default arguments can be added in
386 // later declarations of a function in the same
387 // scope. Declarations in different scopes have completely
388 // distinct sets of default arguments. That is, declarations in
389 // inner scopes do not acquire default arguments from
390 // declarations in outer scopes, and vice versa. In a given
391 // function declaration, all parameters subsequent to a
392 // parameter with a default argument shall have default
393 // arguments supplied in this or previous declarations. A
394 // default argument shall not be redefined by a later
395 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000396 //
397 // C++ [dcl.fct.default]p6:
398 // Except for member functions of class templates, the default arguments
399 // in a member function definition that appears outside of the class
400 // definition are added to the set of default arguments provided by the
401 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000402 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
403 ParmVarDecl *OldParam = Old->getParamDecl(p);
404 ParmVarDecl *NewParam = New->getParamDecl(p);
405
James Molloy9cda03f2012-03-13 08:55:35 +0000406 bool OldParamHasDfl = OldParam->hasDefaultArg();
407 bool NewParamHasDfl = NewParam->hasDefaultArg();
408
409 NamedDecl *ND = Old;
410 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
411 // Ignore default parameters of old decl if they are not in
412 // the same scope.
413 OldParamHasDfl = false;
414
415 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000416
Francois Pichet8d051e02011-04-10 03:03:52 +0000417 unsigned DiagDefaultParamID =
418 diag::err_param_default_argument_redefinition;
419
420 // MSVC accepts that default parameters be redefined for member functions
421 // of template class. The new default parameter's value is ignored.
422 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000423 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000424 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
425 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000426 // Merge the old default argument into the new parameter.
427 NewParam->setHasInheritedDefaultArg();
428 if (OldParam->hasUninstantiatedDefaultArg())
429 NewParam->setUninstantiatedDefaultArg(
430 OldParam->getUninstantiatedDefaultArg());
431 else
432 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000433 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000434 Invalid = false;
435 }
436 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000437
Francois Pichet8cf90492011-04-10 04:58:30 +0000438 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
439 // hint here. Alternatively, we could walk the type-source information
440 // for NewParam to find the last source location in the type... but it
441 // isn't worth the effort right now. This is the kind of test case that
442 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000443 // int f(int);
444 // void g(int (*fp)(int) = f);
445 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000446 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000447 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000448
449 // Look for the function declaration where the default argument was
450 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000451 for (FunctionDecl *Older = Old->getPreviousDecl();
452 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000453 if (!Older->getParamDecl(p)->hasDefaultArg())
454 break;
455
456 OldParam = Older->getParamDecl(p);
457 }
458
459 Diag(OldParam->getLocation(), diag::note_previous_definition)
460 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000461 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000462 // Merge the old default argument into the new parameter.
463 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000464 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000465 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000466 if (OldParam->hasUninstantiatedDefaultArg())
467 NewParam->setUninstantiatedDefaultArg(
468 OldParam->getUninstantiatedDefaultArg());
469 else
John McCall3d6c1782010-05-04 01:53:42 +0000470 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000471 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000472 if (New->getDescribedFunctionTemplate()) {
473 // Paragraph 4, quoted above, only applies to non-template functions.
474 Diag(NewParam->getLocation(),
475 diag::err_param_default_argument_template_redecl)
476 << NewParam->getDefaultArgRange();
477 Diag(Old->getLocation(), diag::note_template_prev_declaration)
478 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000479 } else if (New->getTemplateSpecializationKind()
480 != TSK_ImplicitInstantiation &&
481 New->getTemplateSpecializationKind() != TSK_Undeclared) {
482 // C++ [temp.expr.spec]p21:
483 // Default function arguments shall not be specified in a declaration
484 // or a definition for one of the following explicit specializations:
485 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000486 // - the explicit specialization of a member function template;
487 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000488 // template where the class template specialization to which the
489 // member function specialization belongs is implicitly
490 // instantiated.
491 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
492 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
493 << New->getDeclName()
494 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000495 } else if (New->getDeclContext()->isDependentContext()) {
496 // C++ [dcl.fct.default]p6 (DR217):
497 // Default arguments for a member function of a class template shall
498 // be specified on the initial declaration of the member function
499 // within the class template.
500 //
501 // Reading the tea leaves a bit in DR217 and its reference to DR205
502 // leads me to the conclusion that one cannot add default function
503 // arguments for an out-of-line definition of a member function of a
504 // dependent type.
505 int WhichKind = 2;
506 if (CXXRecordDecl *Record
507 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
508 if (Record->getDescribedClassTemplate())
509 WhichKind = 0;
510 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
511 WhichKind = 1;
512 else
513 WhichKind = 2;
514 }
515
516 Diag(NewParam->getLocation(),
517 diag::err_param_default_argument_member_template_redecl)
518 << WhichKind
519 << NewParam->getDefaultArgRange();
520 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000521 }
522 }
523
Richard Smithb8abff62012-11-28 03:45:24 +0000524 // DR1344: If a default argument is added outside a class definition and that
525 // default argument makes the function a special member function, the program
526 // is ill-formed. This can only happen for constructors.
527 if (isa<CXXConstructorDecl>(New) &&
528 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
529 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
530 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
531 if (NewSM != OldSM) {
532 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
533 assert(NewParam->hasDefaultArg());
534 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
535 << NewParam->getDefaultArgRange() << NewSM;
536 Diag(Old->getLocation(), diag::note_previous_declaration);
537 }
538 }
539
Richard Smithff234882012-02-20 23:28:05 +0000540 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000541 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000542 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000543 if (New->isConstexpr() != Old->isConstexpr()) {
544 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
545 << New << New->isConstexpr();
546 Diag(Old->getLocation(), diag::note_previous_declaration);
547 Invalid = true;
548 }
549
Douglas Gregore13ad832010-02-12 07:32:17 +0000550 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000551 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000552
Douglas Gregorcda9c672009-02-16 17:45:42 +0000553 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000554}
555
Sebastian Redl60618fa2011-03-12 11:50:43 +0000556/// \brief Merge the exception specifications of two variable declarations.
557///
558/// This is called when there's a redeclaration of a VarDecl. The function
559/// checks if the redeclaration might have an exception specification and
560/// validates compatibility and merges the specs if necessary.
561void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
562 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000563 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000564 return;
565
566 assert(Context.hasSameType(New->getType(), Old->getType()) &&
567 "Should only be called if types are otherwise the same.");
568
569 QualType NewType = New->getType();
570 QualType OldType = Old->getType();
571
572 // We're only interested in pointers and references to functions, as well
573 // as pointers to member functions.
574 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
575 NewType = R->getPointeeType();
576 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
577 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
578 NewType = P->getPointeeType();
579 OldType = OldType->getAs<PointerType>()->getPointeeType();
580 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
581 NewType = M->getPointeeType();
582 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
583 }
584
585 if (!NewType->isFunctionProtoType())
586 return;
587
588 // There's lots of special cases for functions. For function pointers, system
589 // libraries are hopefully not as broken so that we don't need these
590 // workarounds.
591 if (CheckEquivalentExceptionSpec(
592 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
593 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
594 New->setInvalidDecl();
595 }
596}
597
Chris Lattner3d1cee32008-04-08 05:04:30 +0000598/// CheckCXXDefaultArguments - Verify that the default arguments for a
599/// function declaration are well-formed according to C++
600/// [dcl.fct.default].
601void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
602 unsigned NumParams = FD->getNumParams();
603 unsigned p;
604
Douglas Gregorc6889e72012-02-14 22:28:59 +0000605 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
606 isa<CXXMethodDecl>(FD) &&
607 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
608
Chris Lattner3d1cee32008-04-08 05:04:30 +0000609 // Find first parameter with a default argument
610 for (p = 0; p < NumParams; ++p) {
611 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000612 if (Param->hasDefaultArg()) {
613 // C++11 [expr.prim.lambda]p5:
614 // [...] Default arguments (8.3.6) shall not be specified in the
615 // parameter-declaration-clause of a lambda-declarator.
616 //
617 // FIXME: Core issue 974 strikes this sentence, we only provide an
618 // extension warning.
619 if (IsLambda)
620 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
621 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000622 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000623 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000624 }
625
626 // C++ [dcl.fct.default]p4:
627 // In a given function declaration, all parameters
628 // subsequent to a parameter with a default argument shall
629 // have default arguments supplied in this or previous
630 // declarations. A default argument shall not be redefined
631 // by a later declaration (not even to the same value).
632 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000633 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000634 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000635 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000636 if (Param->isInvalidDecl())
637 /* We already complained about this parameter. */;
638 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000639 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000640 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000641 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000642 else
Mike Stump1eb44332009-09-09 15:08:12 +0000643 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000644 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000645
Chris Lattner3d1cee32008-04-08 05:04:30 +0000646 LastMissingDefaultArg = p;
647 }
648 }
649
650 if (LastMissingDefaultArg > 0) {
651 // Some default arguments were missing. Clear out all of the
652 // default arguments up to (and including) the last missing
653 // default argument, so that we leave the function parameters
654 // in a semantically valid state.
655 for (p = 0; p <= LastMissingDefaultArg; ++p) {
656 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000657 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000658 Param->setDefaultArg(0);
659 }
660 }
661 }
662}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000663
Richard Smith9f569cc2011-10-01 02:31:28 +0000664// CheckConstexprParameterTypes - Check whether a function's parameter types
665// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000666// diagnostic and return false.
667static bool CheckConstexprParameterTypes(Sema &SemaRef,
668 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000669 unsigned ArgIndex = 0;
670 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
671 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
672 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
673 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
674 SourceLocation ParamLoc = PD->getLocation();
675 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000676 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000677 diag::err_constexpr_non_literal_param,
678 ArgIndex+1, PD->getSourceRange(),
679 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000680 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000681 }
Joao Matos17d35c32012-08-31 22:18:20 +0000682 return true;
683}
684
685/// \brief Get diagnostic %select index for tag kind for
686/// record diagnostic message.
687/// WARNING: Indexes apply to particular diagnostics only!
688///
689/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000690static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000691 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000692 case TTK_Struct: return 0;
693 case TTK_Interface: return 1;
694 case TTK_Class: return 2;
695 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000696 }
Joao Matos17d35c32012-08-31 22:18:20 +0000697}
698
699// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
700// the requirements of a constexpr function definition or a constexpr
701// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000702// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000703//
Richard Smith86c3ae42012-02-13 03:54:03 +0000704// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
705bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000706 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
707 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000708 // C++11 [dcl.constexpr]p4:
709 // The definition of a constexpr constructor shall satisfy the following
710 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000711 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000712 const CXXRecordDecl *RD = MD->getParent();
713 if (RD->getNumVBases()) {
714 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
715 << isa<CXXConstructorDecl>(NewFD)
716 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
717 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
718 E = RD->vbases_end(); I != E; ++I)
719 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000720 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000721 return false;
722 }
Richard Smith35340502012-01-13 04:54:00 +0000723 }
724
725 if (!isa<CXXConstructorDecl>(NewFD)) {
726 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000727 // The definition of a constexpr function shall satisfy the following
728 // constraints:
729 // - it shall not be virtual;
730 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
731 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000732 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000733
Richard Smith86c3ae42012-02-13 03:54:03 +0000734 // If it's not obvious why this function is virtual, find an overridden
735 // function which uses the 'virtual' keyword.
736 const CXXMethodDecl *WrittenVirtual = Method;
737 while (!WrittenVirtual->isVirtualAsWritten())
738 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
739 if (WrittenVirtual != Method)
740 Diag(WrittenVirtual->getLocation(),
741 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000742 return false;
743 }
744
745 // - its return type shall be a literal type;
746 QualType RT = NewFD->getResultType();
747 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000748 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000749 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000750 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000751 }
752
Richard Smith35340502012-01-13 04:54:00 +0000753 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000754 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000755 return false;
756
Richard Smith9f569cc2011-10-01 02:31:28 +0000757 return true;
758}
759
760/// Check the given declaration statement is legal within a constexpr function
761/// body. C++0x [dcl.constexpr]p3,p4.
762///
763/// \return true if the body is OK, false if we have diagnosed a problem.
764static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
765 DeclStmt *DS) {
766 // C++0x [dcl.constexpr]p3 and p4:
767 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
768 // contain only
769 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
770 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
771 switch ((*DclIt)->getKind()) {
772 case Decl::StaticAssert:
773 case Decl::Using:
774 case Decl::UsingShadow:
775 case Decl::UsingDirective:
776 case Decl::UnresolvedUsingTypename:
777 // - static_assert-declarations
778 // - using-declarations,
779 // - using-directives,
780 continue;
781
782 case Decl::Typedef:
783 case Decl::TypeAlias: {
784 // - typedef declarations and alias-declarations that do not define
785 // classes or enumerations,
786 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
787 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
788 // Don't allow variably-modified types in constexpr functions.
789 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
790 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
791 << TL.getSourceRange() << TL.getType()
792 << isa<CXXConstructorDecl>(Dcl);
793 return false;
794 }
795 continue;
796 }
797
798 case Decl::Enum:
799 case Decl::CXXRecord:
800 // As an extension, we allow the declaration (but not the definition) of
801 // classes and enumerations in all declarations, not just in typedef and
802 // alias declarations.
803 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
804 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
805 << isa<CXXConstructorDecl>(Dcl);
806 return false;
807 }
808 continue;
809
810 case Decl::Var:
811 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
812 << isa<CXXConstructorDecl>(Dcl);
813 return false;
814
815 default:
816 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
817 << isa<CXXConstructorDecl>(Dcl);
818 return false;
819 }
820 }
821
822 return true;
823}
824
825/// Check that the given field is initialized within a constexpr constructor.
826///
827/// \param Dcl The constexpr constructor being checked.
828/// \param Field The field being checked. This may be a member of an anonymous
829/// struct or union nested within the class being checked.
830/// \param Inits All declarations, including anonymous struct/union members and
831/// indirect members, for which any initialization was provided.
832/// \param Diagnosed Set to true if an error is produced.
833static void CheckConstexprCtorInitializer(Sema &SemaRef,
834 const FunctionDecl *Dcl,
835 FieldDecl *Field,
836 llvm::SmallSet<Decl*, 16> &Inits,
837 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000838 if (Field->isUnnamedBitfield())
839 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000840
841 if (Field->isAnonymousStructOrUnion() &&
842 Field->getType()->getAsCXXRecordDecl()->isEmpty())
843 return;
844
Richard Smith9f569cc2011-10-01 02:31:28 +0000845 if (!Inits.count(Field)) {
846 if (!Diagnosed) {
847 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
848 Diagnosed = true;
849 }
850 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
851 } else if (Field->isAnonymousStructOrUnion()) {
852 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
853 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
854 I != E; ++I)
855 // If an anonymous union contains an anonymous struct of which any member
856 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000857 if (!RD->isUnion() || Inits.count(*I))
858 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000859 }
860}
861
862/// Check the body for the given constexpr function declaration only contains
863/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
864///
865/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000866bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000867 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000868 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000869 // The definition of a constexpr function shall satisfy the following
870 // constraints: [...]
871 // - its function-body shall be = delete, = default, or a
872 // compound-statement
873 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000874 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000875 // In the definition of a constexpr constructor, [...]
876 // - its function-body shall not be a function-try-block;
877 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
878 << isa<CXXConstructorDecl>(Dcl);
879 return false;
880 }
881
882 // - its function-body shall be [...] a compound-statement that contains only
883 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
884
885 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
886 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
887 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
888 switch ((*BodyIt)->getStmtClass()) {
889 case Stmt::NullStmtClass:
890 // - null statements,
891 continue;
892
893 case Stmt::DeclStmtClass:
894 // - static_assert-declarations
895 // - using-declarations,
896 // - using-directives,
897 // - typedef declarations and alias-declarations that do not define
898 // classes or enumerations,
899 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
900 return false;
901 continue;
902
903 case Stmt::ReturnStmtClass:
904 // - and exactly one return statement;
905 if (isa<CXXConstructorDecl>(Dcl))
906 break;
907
908 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000909 continue;
910
911 default:
912 break;
913 }
914
915 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
916 << isa<CXXConstructorDecl>(Dcl);
917 return false;
918 }
919
920 if (const CXXConstructorDecl *Constructor
921 = dyn_cast<CXXConstructorDecl>(Dcl)) {
922 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000923 // DR1359:
924 // - every non-variant non-static data member and base class sub-object
925 // shall be initialized;
926 // - if the class is a non-empty union, or for each non-empty anonymous
927 // union member of a non-union class, exactly one non-static data member
928 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000929 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000930 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000931 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
932 return false;
933 }
Richard Smith6e433752011-10-10 16:38:04 +0000934 } else if (!Constructor->isDependentContext() &&
935 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000936 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
937
938 // Skip detailed checking if we have enough initializers, and we would
939 // allow at most one initializer per member.
940 bool AnyAnonStructUnionMembers = false;
941 unsigned Fields = 0;
942 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
943 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000944 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000945 AnyAnonStructUnionMembers = true;
946 break;
947 }
948 }
949 if (AnyAnonStructUnionMembers ||
950 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
951 // Check initialization of non-static data members. Base classes are
952 // always initialized so do not need to be checked. Dependent bases
953 // might not have initializers in the member initializer list.
954 llvm::SmallSet<Decl*, 16> Inits;
955 for (CXXConstructorDecl::init_const_iterator
956 I = Constructor->init_begin(), E = Constructor->init_end();
957 I != E; ++I) {
958 if (FieldDecl *FD = (*I)->getMember())
959 Inits.insert(FD);
960 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
961 Inits.insert(ID->chain_begin(), ID->chain_end());
962 }
963
964 bool Diagnosed = false;
965 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
966 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000967 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000968 if (Diagnosed)
969 return false;
970 }
971 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000972 } else {
973 if (ReturnStmts.empty()) {
974 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
975 return false;
976 }
977 if (ReturnStmts.size() > 1) {
978 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
979 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
980 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
981 return false;
982 }
983 }
984
Richard Smith5ba73e12012-02-04 00:33:54 +0000985 // C++11 [dcl.constexpr]p5:
986 // if no function argument values exist such that the function invocation
987 // substitution would produce a constant expression, the program is
988 // ill-formed; no diagnostic required.
989 // C++11 [dcl.constexpr]p3:
990 // - every constructor call and implicit conversion used in initializing the
991 // return value shall be one of those allowed in a constant expression.
992 // C++11 [dcl.constexpr]p4:
993 // - every constructor involved in initializing non-static data members and
994 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +0000995 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000996 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +0000997 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +0000998 << isa<CXXConstructorDecl>(Dcl);
999 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1000 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001001 // Don't return false here: we allow this for compatibility in
1002 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001003 }
1004
Richard Smith9f569cc2011-10-01 02:31:28 +00001005 return true;
1006}
1007
Douglas Gregorb48fe382008-10-31 09:07:45 +00001008/// isCurrentClassName - Determine whether the identifier II is the
1009/// name of the class type currently being defined. In the case of
1010/// nested classes, this will only return true if II is the name of
1011/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001012bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1013 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001014 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001015
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001016 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001017 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001018 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001019 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1020 } else
1021 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1022
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001023 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001024 return &II == CurDecl->getIdentifier();
1025 else
1026 return false;
1027}
1028
Douglas Gregor229d47a2012-11-10 07:24:09 +00001029/// \brief Determine whether the given class is a base class of the given
1030/// class, including looking at dependent bases.
1031static bool findCircularInheritance(const CXXRecordDecl *Class,
1032 const CXXRecordDecl *Current) {
1033 SmallVector<const CXXRecordDecl*, 8> Queue;
1034
1035 Class = Class->getCanonicalDecl();
1036 while (true) {
1037 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1038 E = Current->bases_end();
1039 I != E; ++I) {
1040 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1041 if (!Base)
1042 continue;
1043
1044 Base = Base->getDefinition();
1045 if (!Base)
1046 continue;
1047
1048 if (Base->getCanonicalDecl() == Class)
1049 return true;
1050
1051 Queue.push_back(Base);
1052 }
1053
1054 if (Queue.empty())
1055 return false;
1056
1057 Current = Queue.back();
1058 Queue.pop_back();
1059 }
1060
1061 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001062}
1063
Mike Stump1eb44332009-09-09 15:08:12 +00001064/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001065///
1066/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1067/// and returns NULL otherwise.
1068CXXBaseSpecifier *
1069Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1070 SourceRange SpecifierRange,
1071 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001072 TypeSourceInfo *TInfo,
1073 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001074 QualType BaseType = TInfo->getType();
1075
Douglas Gregor2943aed2009-03-03 04:44:36 +00001076 // C++ [class.union]p1:
1077 // A union shall not have base classes.
1078 if (Class->isUnion()) {
1079 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1080 << SpecifierRange;
1081 return 0;
1082 }
1083
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001084 if (EllipsisLoc.isValid() &&
1085 !TInfo->getType()->containsUnexpandedParameterPack()) {
1086 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1087 << TInfo->getTypeLoc().getSourceRange();
1088 EllipsisLoc = SourceLocation();
1089 }
Douglas Gregord777e282012-11-10 01:18:17 +00001090
1091 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1092
1093 if (BaseType->isDependentType()) {
1094 // Make sure that we don't have circular inheritance among our dependent
1095 // bases. For non-dependent bases, the check for completeness below handles
1096 // this.
1097 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1098 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1099 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001100 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001101 Diag(BaseLoc, diag::err_circular_inheritance)
1102 << BaseType << Context.getTypeDeclType(Class);
1103
1104 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1105 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1106 << BaseType;
1107
1108 return 0;
1109 }
1110 }
1111
Mike Stump1eb44332009-09-09 15:08:12 +00001112 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001113 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001114 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001115 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001116
1117 // Base specifiers must be record types.
1118 if (!BaseType->isRecordType()) {
1119 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1120 return 0;
1121 }
1122
1123 // C++ [class.union]p1:
1124 // A union shall not be used as a base class.
1125 if (BaseType->isUnionType()) {
1126 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1127 return 0;
1128 }
1129
1130 // C++ [class.derived]p2:
1131 // The class-name in a base-specifier shall not be an incompletely
1132 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001133 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001134 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001135 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001136 return 0;
John McCall572fc622010-08-17 07:23:57 +00001137 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001138
Eli Friedman1d954f62009-08-15 21:55:26 +00001139 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001140 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001141 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001142 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001143 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001144 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1145 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001146
Anders Carlsson1d209272011-03-25 14:55:14 +00001147 // C++ [class]p3:
1148 // If a class is marked final and it appears as a base-type-specifier in
1149 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001150 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001151 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1152 << CXXBaseDecl->getDeclName();
1153 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1154 << CXXBaseDecl->getDeclName();
1155 return 0;
1156 }
1157
John McCall572fc622010-08-17 07:23:57 +00001158 if (BaseDecl->isInvalidDecl())
1159 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001160
1161 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001162 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001163 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001164 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001165}
1166
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001167/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1168/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001169/// example:
1170/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001171/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001172BaseResult
John McCalld226f652010-08-21 09:40:31 +00001173Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001174 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001175 ParsedType basetype, SourceLocation BaseLoc,
1176 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001177 if (!classdecl)
1178 return true;
1179
Douglas Gregor40808ce2009-03-09 23:48:35 +00001180 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001181 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001182 if (!Class)
1183 return true;
1184
Nick Lewycky56062202010-07-26 16:56:01 +00001185 TypeSourceInfo *TInfo = 0;
1186 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001187
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001188 if (EllipsisLoc.isInvalid() &&
1189 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001190 UPPC_BaseType))
1191 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001192
Douglas Gregor2943aed2009-03-03 04:44:36 +00001193 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001194 Virtual, Access, TInfo,
1195 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001196 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001197 else
1198 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001199
Douglas Gregor2943aed2009-03-03 04:44:36 +00001200 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001201}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001202
Douglas Gregor2943aed2009-03-03 04:44:36 +00001203/// \brief Performs the actual work of attaching the given base class
1204/// specifiers to a C++ class.
1205bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1206 unsigned NumBases) {
1207 if (NumBases == 0)
1208 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001209
1210 // Used to keep track of which base types we have already seen, so
1211 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001212 // that the key is always the unqualified canonical type of the base
1213 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001214 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1215
1216 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001217 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001218 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001219 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001220 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001221 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001222 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001223
1224 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1225 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001226 // C++ [class.mi]p3:
1227 // A class shall not be specified as a direct base class of a
1228 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001229 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001230 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001231 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001232 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001233
1234 // Delete the duplicate base class specifier; we're going to
1235 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001236 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001237
1238 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001239 } else {
1240 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001241 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001242 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001243 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1244 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1245 if (Class->isInterface() &&
1246 (!RD->isInterface() ||
1247 KnownBase->getAccessSpecifier() != AS_public)) {
1248 // The Microsoft extension __interface does not permit bases that
1249 // are not themselves public interfaces.
1250 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1251 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1252 << RD->getSourceRange();
1253 Invalid = true;
1254 }
1255 if (RD->hasAttr<WeakAttr>())
1256 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1257 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001258 }
1259 }
1260
1261 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001262 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001263
1264 // Delete the remaining (good) base class specifiers, since their
1265 // data has been copied into the CXXRecordDecl.
1266 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001267 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001268
1269 return Invalid;
1270}
1271
1272/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1273/// class, after checking whether there are any duplicate base
1274/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001275void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001276 unsigned NumBases) {
1277 if (!ClassDecl || !Bases || !NumBases)
1278 return;
1279
1280 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001281 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001282 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001283}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001284
John McCall3cb0ebd2010-03-10 03:28:59 +00001285static CXXRecordDecl *GetClassForType(QualType T) {
1286 if (const RecordType *RT = T->getAs<RecordType>())
1287 return cast<CXXRecordDecl>(RT->getDecl());
1288 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1289 return ICT->getDecl();
1290 else
1291 return 0;
1292}
1293
Douglas Gregora8f32e02009-10-06 17:59:45 +00001294/// \brief Determine whether the type \p Derived is a C++ class that is
1295/// derived from the type \p Base.
1296bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001297 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001298 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001299
1300 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1301 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001302 return false;
1303
John McCall3cb0ebd2010-03-10 03:28:59 +00001304 CXXRecordDecl *BaseRD = GetClassForType(Base);
1305 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001306 return false;
1307
John McCall86ff3082010-02-04 22:26:26 +00001308 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1309 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001310}
1311
1312/// \brief Determine whether the type \p Derived is a C++ class that is
1313/// derived from the type \p Base.
1314bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001315 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001316 return false;
1317
John McCall3cb0ebd2010-03-10 03:28:59 +00001318 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1319 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001320 return false;
1321
John McCall3cb0ebd2010-03-10 03:28:59 +00001322 CXXRecordDecl *BaseRD = GetClassForType(Base);
1323 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001324 return false;
1325
Douglas Gregora8f32e02009-10-06 17:59:45 +00001326 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1327}
1328
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001329void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001330 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001331 assert(BasePathArray.empty() && "Base path array must be empty!");
1332 assert(Paths.isRecordingPaths() && "Must record paths!");
1333
1334 const CXXBasePath &Path = Paths.front();
1335
1336 // We first go backward and check if we have a virtual base.
1337 // FIXME: It would be better if CXXBasePath had the base specifier for
1338 // the nearest virtual base.
1339 unsigned Start = 0;
1340 for (unsigned I = Path.size(); I != 0; --I) {
1341 if (Path[I - 1].Base->isVirtual()) {
1342 Start = I - 1;
1343 break;
1344 }
1345 }
1346
1347 // Now add all bases.
1348 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001349 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001350}
1351
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001352/// \brief Determine whether the given base path includes a virtual
1353/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001354bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1355 for (CXXCastPath::const_iterator B = BasePath.begin(),
1356 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001357 B != BEnd; ++B)
1358 if ((*B)->isVirtual())
1359 return true;
1360
1361 return false;
1362}
1363
Douglas Gregora8f32e02009-10-06 17:59:45 +00001364/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1365/// conversion (where Derived and Base are class types) is
1366/// well-formed, meaning that the conversion is unambiguous (and
1367/// that all of the base classes are accessible). Returns true
1368/// and emits a diagnostic if the code is ill-formed, returns false
1369/// otherwise. Loc is the location where this routine should point to
1370/// if there is an error, and Range is the source range to highlight
1371/// if there is an error.
1372bool
1373Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001374 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001375 unsigned AmbigiousBaseConvID,
1376 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001377 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001378 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001379 // First, determine whether the path from Derived to Base is
1380 // ambiguous. This is slightly more expensive than checking whether
1381 // the Derived to Base conversion exists, because here we need to
1382 // explore multiple paths to determine if there is an ambiguity.
1383 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1384 /*DetectVirtual=*/false);
1385 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1386 assert(DerivationOkay &&
1387 "Can only be used with a derived-to-base conversion");
1388 (void)DerivationOkay;
1389
1390 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001391 if (InaccessibleBaseID) {
1392 // Check that the base class can be accessed.
1393 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1394 InaccessibleBaseID)) {
1395 case AR_inaccessible:
1396 return true;
1397 case AR_accessible:
1398 case AR_dependent:
1399 case AR_delayed:
1400 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001401 }
John McCall6b2accb2010-02-10 09:31:12 +00001402 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001403
1404 // Build a base path if necessary.
1405 if (BasePath)
1406 BuildBasePathArray(Paths, *BasePath);
1407 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001408 }
1409
1410 // We know that the derived-to-base conversion is ambiguous, and
1411 // we're going to produce a diagnostic. Perform the derived-to-base
1412 // search just one more time to compute all of the possible paths so
1413 // that we can print them out. This is more expensive than any of
1414 // the previous derived-to-base checks we've done, but at this point
1415 // performance isn't as much of an issue.
1416 Paths.clear();
1417 Paths.setRecordingPaths(true);
1418 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1419 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1420 (void)StillOkay;
1421
1422 // Build up a textual representation of the ambiguous paths, e.g.,
1423 // D -> B -> A, that will be used to illustrate the ambiguous
1424 // conversions in the diagnostic. We only print one of the paths
1425 // to each base class subobject.
1426 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1427
1428 Diag(Loc, AmbigiousBaseConvID)
1429 << Derived << Base << PathDisplayStr << Range << Name;
1430 return true;
1431}
1432
1433bool
1434Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001435 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001436 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001437 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001438 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001439 IgnoreAccess ? 0
1440 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001441 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001442 Loc, Range, DeclarationName(),
1443 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001444}
1445
1446
1447/// @brief Builds a string representing ambiguous paths from a
1448/// specific derived class to different subobjects of the same base
1449/// class.
1450///
1451/// This function builds a string that can be used in error messages
1452/// to show the different paths that one can take through the
1453/// inheritance hierarchy to go from the derived class to different
1454/// subobjects of a base class. The result looks something like this:
1455/// @code
1456/// struct D -> struct B -> struct A
1457/// struct D -> struct C -> struct A
1458/// @endcode
1459std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1460 std::string PathDisplayStr;
1461 std::set<unsigned> DisplayedPaths;
1462 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1463 Path != Paths.end(); ++Path) {
1464 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1465 // We haven't displayed a path to this particular base
1466 // class subobject yet.
1467 PathDisplayStr += "\n ";
1468 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1469 for (CXXBasePath::const_iterator Element = Path->begin();
1470 Element != Path->end(); ++Element)
1471 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1472 }
1473 }
1474
1475 return PathDisplayStr;
1476}
1477
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001478//===----------------------------------------------------------------------===//
1479// C++ class member Handling
1480//===----------------------------------------------------------------------===//
1481
Abramo Bagnara6206d532010-06-05 05:09:32 +00001482/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001483bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1484 SourceLocation ASLoc,
1485 SourceLocation ColonLoc,
1486 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001487 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001488 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001489 ASLoc, ColonLoc);
1490 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001491 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001492}
1493
Richard Smitha4b39652012-08-06 03:25:17 +00001494/// CheckOverrideControl - Check C++11 override control semantics.
1495void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001496 if (D->isInvalidDecl())
1497 return;
1498
Chris Lattner5f9e2722011-07-23 10:55:15 +00001499 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001500
Richard Smitha4b39652012-08-06 03:25:17 +00001501 // Do we know which functions this declaration might be overriding?
1502 bool OverridesAreKnown = !MD ||
1503 (!MD->getParent()->hasAnyDependentBases() &&
1504 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001505
Richard Smitha4b39652012-08-06 03:25:17 +00001506 if (!MD || !MD->isVirtual()) {
1507 if (OverridesAreKnown) {
1508 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1509 Diag(OA->getLocation(),
1510 diag::override_keyword_only_allowed_on_virtual_member_functions)
1511 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1512 D->dropAttr<OverrideAttr>();
1513 }
1514 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1515 Diag(FA->getLocation(),
1516 diag::override_keyword_only_allowed_on_virtual_member_functions)
1517 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1518 D->dropAttr<FinalAttr>();
1519 }
1520 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001521 return;
1522 }
Richard Smitha4b39652012-08-06 03:25:17 +00001523
1524 if (!OverridesAreKnown)
1525 return;
1526
1527 // C++11 [class.virtual]p5:
1528 // If a virtual function is marked with the virt-specifier override and
1529 // does not override a member function of a base class, the program is
1530 // ill-formed.
1531 bool HasOverriddenMethods =
1532 MD->begin_overridden_methods() != MD->end_overridden_methods();
1533 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1534 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1535 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001536}
1537
Richard Smitha4b39652012-08-06 03:25:17 +00001538/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001539/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001540/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001541bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1542 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001543 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001544 return false;
1545
1546 Diag(New->getLocation(), diag::err_final_function_overridden)
1547 << New->getDeclName();
1548 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1549 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001550}
1551
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001552static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001553 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1554 // FIXME: Destruction of ObjC lifetime types has side-effects.
1555 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1556 return !RD->isCompleteDefinition() ||
1557 !RD->hasTrivialDefaultConstructor() ||
1558 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001559 return false;
1560}
1561
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001562/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1563/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001564/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001565/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1566/// present (but parsing it has been deferred).
John McCalld226f652010-08-21 09:40:31 +00001567Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001568Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001569 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001570 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001571 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001572 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001573 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1574 DeclarationName Name = NameInfo.getName();
1575 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001576
1577 // For anonymous bitfields, the location should point to the type.
1578 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001579 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001580
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001581 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001582
John McCall4bde1e12010-06-04 08:34:12 +00001583 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001584 assert(!DS.isFriendSpecified());
1585
Richard Smith1ab0d902011-06-25 02:28:38 +00001586 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001587
John McCalle402e722012-09-25 07:32:39 +00001588 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1589 // The Microsoft extension __interface only permits public member functions
1590 // and prohibits constructors, destructors, operators, non-public member
1591 // functions, static methods and data members.
1592 unsigned InvalidDecl;
1593 bool ShowDeclName = true;
1594 if (!isFunc)
1595 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1596 else if (AS != AS_public)
1597 InvalidDecl = 2;
1598 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1599 InvalidDecl = 3;
1600 else switch (Name.getNameKind()) {
1601 case DeclarationName::CXXConstructorName:
1602 InvalidDecl = 4;
1603 ShowDeclName = false;
1604 break;
1605
1606 case DeclarationName::CXXDestructorName:
1607 InvalidDecl = 5;
1608 ShowDeclName = false;
1609 break;
1610
1611 case DeclarationName::CXXOperatorName:
1612 case DeclarationName::CXXConversionFunctionName:
1613 InvalidDecl = 6;
1614 break;
1615
1616 default:
1617 InvalidDecl = 0;
1618 break;
1619 }
1620
1621 if (InvalidDecl) {
1622 if (ShowDeclName)
1623 Diag(Loc, diag::err_invalid_member_in_interface)
1624 << (InvalidDecl-1) << Name;
1625 else
1626 Diag(Loc, diag::err_invalid_member_in_interface)
1627 << (InvalidDecl-1) << "";
1628 return 0;
1629 }
1630 }
1631
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001632 // C++ 9.2p6: A member shall not be declared to have automatic storage
1633 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001634 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1635 // data members and cannot be applied to names declared const or static,
1636 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001637 switch (DS.getStorageClassSpec()) {
1638 case DeclSpec::SCS_unspecified:
1639 case DeclSpec::SCS_typedef:
1640 case DeclSpec::SCS_static:
1641 // FALL THROUGH.
1642 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001643 case DeclSpec::SCS_mutable:
1644 if (isFunc) {
1645 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001646 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001647 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001648 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001649
Sebastian Redla11f42f2008-11-17 23:24:37 +00001650 // FIXME: It would be nicer if the keyword was ignored only for this
1651 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001652 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001653 }
1654 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001655 default:
1656 if (DS.getStorageClassSpecLoc().isValid())
1657 Diag(DS.getStorageClassSpecLoc(),
1658 diag::err_storageclass_invalid_for_member);
1659 else
1660 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1661 D.getMutableDeclSpec().ClearStorageClassSpecs();
1662 }
1663
Sebastian Redl669d5d72008-11-14 23:42:31 +00001664 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1665 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001666 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001667
1668 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001669 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001670 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001671
1672 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001673 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001674 Diag(Loc, diag::err_bad_variable_name)
1675 << Name;
1676 return 0;
1677 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001678
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001679 IdentifierInfo *II = Name.getAsIdentifierInfo();
1680
Douglas Gregorf2503652011-09-21 14:40:46 +00001681 // Member field could not be with "template" keyword.
1682 // So TemplateParameterLists should be empty in this case.
1683 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001684 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001685 if (TemplateParams->size()) {
1686 // There is no such thing as a member field template.
1687 Diag(D.getIdentifierLoc(), diag::err_template_member)
1688 << II
1689 << SourceRange(TemplateParams->getTemplateLoc(),
1690 TemplateParams->getRAngleLoc());
1691 } else {
1692 // There is an extraneous 'template<>' for this member.
1693 Diag(TemplateParams->getTemplateLoc(),
1694 diag::err_template_member_noparams)
1695 << II
1696 << SourceRange(TemplateParams->getTemplateLoc(),
1697 TemplateParams->getRAngleLoc());
1698 }
1699 return 0;
1700 }
1701
Douglas Gregor922fff22010-10-13 22:19:53 +00001702 if (SS.isSet() && !SS.isInvalid()) {
1703 // The user provided a superfluous scope specifier inside a class
1704 // definition:
1705 //
1706 // class X {
1707 // int X::member;
1708 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001709 if (DeclContext *DC = computeDeclContext(SS, false))
1710 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001711 else
1712 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1713 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001714
Douglas Gregor922fff22010-10-13 22:19:53 +00001715 SS.clear();
1716 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001717
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001718 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001719 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001720 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001721 } else {
Richard Smithca523302012-06-10 03:12:00 +00001722 assert(InitStyle == ICIS_NoInit);
Richard Smith7a614d82011-06-11 17:19:42 +00001723
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001724 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001725 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001726 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001727 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001728
1729 // Non-instance-fields can't have a bitfield.
1730 if (BitWidth) {
1731 if (Member->isInvalidDecl()) {
1732 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001733 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001734 // C++ 9.6p3: A bit-field shall not be a static member.
1735 // "static member 'A' cannot be a bit-field"
1736 Diag(Loc, diag::err_static_not_bitfield)
1737 << Name << BitWidth->getSourceRange();
1738 } else if (isa<TypedefDecl>(Member)) {
1739 // "typedef member 'x' cannot be a bit-field"
1740 Diag(Loc, diag::err_typedef_not_bitfield)
1741 << Name << BitWidth->getSourceRange();
1742 } else {
1743 // A function typedef ("typedef int f(); f a;").
1744 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1745 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001746 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001747 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001748 }
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Chris Lattner8b963ef2009-03-05 23:01:03 +00001750 BitWidth = 0;
1751 Member->setInvalidDecl();
1752 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001753
1754 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001755
Douglas Gregor37b372b2009-08-20 22:52:58 +00001756 // If we have declared a member function template, set the access of the
1757 // templated declaration as well.
1758 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1759 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001760 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001761
Richard Smitha4b39652012-08-06 03:25:17 +00001762 if (VS.isOverrideSpecified())
1763 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1764 if (VS.isFinalSpecified())
1765 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001766
Douglas Gregorf5251602011-03-08 17:10:18 +00001767 if (VS.getLastLocation().isValid()) {
1768 // Update the end location of a method that has a virt-specifiers.
1769 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1770 MD->setRangeEnd(VS.getLastLocation());
1771 }
Richard Smitha4b39652012-08-06 03:25:17 +00001772
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001773 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001774
Douglas Gregor10bd3682008-11-17 22:58:34 +00001775 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001776
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001777 if (isInstField) {
1778 FieldDecl *FD = cast<FieldDecl>(Member);
1779 FieldCollector->Add(FD);
1780
1781 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1782 FD->getLocation())
1783 != DiagnosticsEngine::Ignored) {
1784 // Remember all explicit private FieldDecls that have a name, no side
1785 // effects and are not part of a dependent type declaration.
1786 if (!FD->isImplicit() && FD->getDeclName() &&
1787 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001788 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001789 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001790 !InitializationHasSideEffects(*FD))
1791 UnusedPrivateFields.insert(FD);
1792 }
1793 }
1794
John McCalld226f652010-08-21 09:40:31 +00001795 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001796}
1797
Hans Wennborg471f9852012-09-18 15:58:06 +00001798namespace {
1799 class UninitializedFieldVisitor
1800 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1801 Sema &S;
1802 ValueDecl *VD;
1803 public:
1804 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1805 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001806 S(S) {
1807 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1808 this->VD = IFD->getAnonField();
1809 else
1810 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001811 }
1812
1813 void HandleExpr(Expr *E) {
1814 if (!E) return;
1815
1816 // Expressions like x(x) sometimes lack the surrounding expressions
1817 // but need to be checked anyways.
1818 HandleValue(E);
1819 Visit(E);
1820 }
1821
1822 void HandleValue(Expr *E) {
1823 E = E->IgnoreParens();
1824
1825 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1826 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001827 return;
1828
1829 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1830 // or union.
1831 MemberExpr *FieldME = ME;
1832
Hans Wennborg471f9852012-09-18 15:58:06 +00001833 Expr *Base = E;
1834 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001835 ME = cast<MemberExpr>(Base);
1836
1837 if (isa<VarDecl>(ME->getMemberDecl()))
1838 return;
1839
1840 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1841 if (!FD->isAnonymousStructOrUnion())
1842 FieldME = ME;
1843
Hans Wennborg471f9852012-09-18 15:58:06 +00001844 Base = ME->getBase();
1845 }
1846
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001847 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00001848 unsigned diag = VD->getType()->isReferenceType()
1849 ? diag::warn_reference_field_is_uninit
1850 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001851 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001852 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001853 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00001854 }
1855
1856 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1857 HandleValue(CO->getTrueExpr());
1858 HandleValue(CO->getFalseExpr());
1859 return;
1860 }
1861
1862 if (BinaryConditionalOperator *BCO =
1863 dyn_cast<BinaryConditionalOperator>(E)) {
1864 HandleValue(BCO->getCommon());
1865 HandleValue(BCO->getFalseExpr());
1866 return;
1867 }
1868
1869 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1870 switch (BO->getOpcode()) {
1871 default:
1872 return;
1873 case(BO_PtrMemD):
1874 case(BO_PtrMemI):
1875 HandleValue(BO->getLHS());
1876 return;
1877 case(BO_Comma):
1878 HandleValue(BO->getRHS());
1879 return;
1880 }
1881 }
1882 }
1883
1884 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1885 if (E->getCastKind() == CK_LValueToRValue)
1886 HandleValue(E->getSubExpr());
1887
1888 Inherited::VisitImplicitCastExpr(E);
1889 }
1890
1891 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1892 Expr *Callee = E->getCallee();
1893 if (isa<MemberExpr>(Callee))
1894 HandleValue(Callee);
1895
1896 Inherited::VisitCXXMemberCallExpr(E);
1897 }
1898 };
1899 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1900 ValueDecl *VD) {
1901 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1902 }
1903} // namespace
1904
Richard Smith7a614d82011-06-11 17:19:42 +00001905/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001906/// in-class initializer for a non-static C++ class member, and after
1907/// instantiating an in-class initializer in a class template. Such actions
1908/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001909void
Richard Smithca523302012-06-10 03:12:00 +00001910Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001911 Expr *InitExpr) {
1912 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001913 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1914 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001915
1916 if (!InitExpr) {
1917 FD->setInvalidDecl();
1918 FD->removeInClassInitializer();
1919 return;
1920 }
1921
Peter Collingbournefef21892011-10-23 18:59:44 +00001922 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1923 FD->setInvalidDecl();
1924 FD->removeInClassInitializer();
1925 return;
1926 }
1927
Hans Wennborg471f9852012-09-18 15:58:06 +00001928 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1929 != DiagnosticsEngine::Ignored) {
1930 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1931 }
1932
Richard Smith7a614d82011-06-11 17:19:42 +00001933 ExprResult Init = InitExpr;
Douglas Gregordd084272012-09-14 04:20:37 +00001934 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent() &&
1935 !FD->getDeclContext()->isDependentContext()) {
1936 // Note: We don't type-check when we're in a dependent context, because
1937 // the initialization-substitution code does not properly handle direct
1938 // list initialization. We have the same hackaround for ctor-initializers.
Sebastian Redl772291a2012-02-19 16:31:05 +00001939 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001940 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001941 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1942 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001943 Expr **Inits = &InitExpr;
1944 unsigned NumInits = 1;
1945 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00001946 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00001947 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00001948 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00001949 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1950 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001951 if (Init.isInvalid()) {
1952 FD->setInvalidDecl();
1953 return;
1954 }
1955
Richard Smithca523302012-06-10 03:12:00 +00001956 CheckImplicitConversions(Init.get(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00001957 }
1958
1959 // C++0x [class.base.init]p7:
1960 // The initialization of each base and member constitutes a
1961 // full-expression.
1962 Init = MaybeCreateExprWithCleanups(Init);
1963 if (Init.isInvalid()) {
1964 FD->setInvalidDecl();
1965 return;
1966 }
1967
1968 InitExpr = Init.release();
1969
1970 FD->setInClassInitializer(InitExpr);
1971}
1972
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001973/// \brief Find the direct and/or virtual base specifiers that
1974/// correspond to the given base type, for use in base initialization
1975/// within a constructor.
1976static bool FindBaseInitializer(Sema &SemaRef,
1977 CXXRecordDecl *ClassDecl,
1978 QualType BaseType,
1979 const CXXBaseSpecifier *&DirectBaseSpec,
1980 const CXXBaseSpecifier *&VirtualBaseSpec) {
1981 // First, check for a direct base class.
1982 DirectBaseSpec = 0;
1983 for (CXXRecordDecl::base_class_const_iterator Base
1984 = ClassDecl->bases_begin();
1985 Base != ClassDecl->bases_end(); ++Base) {
1986 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1987 // We found a direct base of this type. That's what we're
1988 // initializing.
1989 DirectBaseSpec = &*Base;
1990 break;
1991 }
1992 }
1993
1994 // Check for a virtual base class.
1995 // FIXME: We might be able to short-circuit this if we know in advance that
1996 // there are no virtual bases.
1997 VirtualBaseSpec = 0;
1998 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1999 // We haven't found a base yet; search the class hierarchy for a
2000 // virtual base class.
2001 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2002 /*DetectVirtual=*/false);
2003 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2004 BaseType, Paths)) {
2005 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2006 Path != Paths.end(); ++Path) {
2007 if (Path->back().Base->isVirtual()) {
2008 VirtualBaseSpec = Path->back().Base;
2009 break;
2010 }
2011 }
2012 }
2013 }
2014
2015 return DirectBaseSpec || VirtualBaseSpec;
2016}
2017
Sebastian Redl6df65482011-09-24 17:48:25 +00002018/// \brief Handle a C++ member initializer using braced-init-list syntax.
2019MemInitResult
2020Sema::ActOnMemInitializer(Decl *ConstructorD,
2021 Scope *S,
2022 CXXScopeSpec &SS,
2023 IdentifierInfo *MemberOrBase,
2024 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002025 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002026 SourceLocation IdLoc,
2027 Expr *InitList,
2028 SourceLocation EllipsisLoc) {
2029 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002030 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002031 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002032}
2033
2034/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002035MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002036Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002037 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002038 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002039 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002040 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002041 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002042 SourceLocation IdLoc,
2043 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002044 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002045 SourceLocation RParenLoc,
2046 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002047 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2048 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002049 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002050 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002051 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002052}
2053
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002054namespace {
2055
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002056// Callback to only accept typo corrections that can be a valid C++ member
2057// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002058class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2059 public:
2060 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2061 : ClassDecl(ClassDecl) {}
2062
2063 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2064 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2065 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2066 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2067 else
2068 return isa<TypeDecl>(ND);
2069 }
2070 return false;
2071 }
2072
2073 private:
2074 CXXRecordDecl *ClassDecl;
2075};
2076
2077}
2078
Sebastian Redl6df65482011-09-24 17:48:25 +00002079/// \brief Handle a C++ member initializer.
2080MemInitResult
2081Sema::BuildMemInitializer(Decl *ConstructorD,
2082 Scope *S,
2083 CXXScopeSpec &SS,
2084 IdentifierInfo *MemberOrBase,
2085 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002086 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002087 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002088 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002089 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002090 if (!ConstructorD)
2091 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002093 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002094
2095 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002096 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002097 if (!Constructor) {
2098 // The user wrote a constructor initializer on a function that is
2099 // not a C++ constructor. Ignore the error for now, because we may
2100 // have more member initializers coming; we'll diagnose it just
2101 // once in ActOnMemInitializers.
2102 return true;
2103 }
2104
2105 CXXRecordDecl *ClassDecl = Constructor->getParent();
2106
2107 // C++ [class.base.init]p2:
2108 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002109 // constructor's class and, if not found in that scope, are looked
2110 // up in the scope containing the constructor's definition.
2111 // [Note: if the constructor's class contains a member with the
2112 // same name as a direct or virtual base class of the class, a
2113 // mem-initializer-id naming the member or base class and composed
2114 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002115 // mem-initializer-id for the hidden base class may be specified
2116 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002117 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002118 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002119 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002120 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00002121 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002122 ValueDecl *Member;
2123 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
2124 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002125 if (EllipsisLoc.isValid())
2126 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002127 << MemberOrBase
2128 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002129
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002130 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002131 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002132 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002133 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002134 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002135 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002136 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002137
2138 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002139 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002140 } else if (DS.getTypeSpecType() == TST_decltype) {
2141 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002142 } else {
2143 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2144 LookupParsedName(R, S, &SS);
2145
2146 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2147 if (!TyD) {
2148 if (R.isAmbiguous()) return true;
2149
John McCallfd225442010-04-09 19:01:14 +00002150 // We don't want access-control diagnostics here.
2151 R.suppressDiagnostics();
2152
Douglas Gregor7a886e12010-01-19 06:46:48 +00002153 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2154 bool NotUnknownSpecialization = false;
2155 DeclContext *DC = computeDeclContext(SS, false);
2156 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2157 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2158
2159 if (!NotUnknownSpecialization) {
2160 // When the scope specifier can refer to a member of an unknown
2161 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002162 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2163 SS.getWithLocInContext(Context),
2164 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002165 if (BaseType.isNull())
2166 return true;
2167
Douglas Gregor7a886e12010-01-19 06:46:48 +00002168 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002169 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002170 }
2171 }
2172
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002173 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002174 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002175 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002176 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002177 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002178 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002179 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2180 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002181 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002182 // We have found a non-static data member with a similar
2183 // name to what was typed; complain and initialize that
2184 // member.
2185 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2186 << MemberOrBase << true << CorrectedQuotedStr
2187 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2188 Diag(Member->getLocation(), diag::note_previous_decl)
2189 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002190
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002191 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002192 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002193 const CXXBaseSpecifier *DirectBaseSpec;
2194 const CXXBaseSpecifier *VirtualBaseSpec;
2195 if (FindBaseInitializer(*this, ClassDecl,
2196 Context.getTypeDeclType(Type),
2197 DirectBaseSpec, VirtualBaseSpec)) {
2198 // We have found a direct or virtual base class with a
2199 // similar name to what was typed; complain and initialize
2200 // that base class.
2201 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002202 << MemberOrBase << false << CorrectedQuotedStr
2203 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002204
2205 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2206 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002207 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002208 diag::note_base_class_specified_here)
2209 << BaseSpec->getType()
2210 << BaseSpec->getSourceRange();
2211
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002212 TyD = Type;
2213 }
2214 }
2215 }
2216
Douglas Gregor7a886e12010-01-19 06:46:48 +00002217 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002218 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002219 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002220 return true;
2221 }
John McCall2b194412009-12-21 10:41:20 +00002222 }
2223
Douglas Gregor7a886e12010-01-19 06:46:48 +00002224 if (BaseType.isNull()) {
2225 BaseType = Context.getTypeDeclType(TyD);
2226 if (SS.isSet()) {
2227 NestedNameSpecifier *Qualifier =
2228 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002229
Douglas Gregor7a886e12010-01-19 06:46:48 +00002230 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002231 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002232 }
John McCall2b194412009-12-21 10:41:20 +00002233 }
2234 }
Mike Stump1eb44332009-09-09 15:08:12 +00002235
John McCalla93c9342009-12-07 02:54:59 +00002236 if (!TInfo)
2237 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002238
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002239 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002240}
2241
Chandler Carruth81c64772011-09-03 01:14:15 +00002242/// Checks a member initializer expression for cases where reference (or
2243/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002244static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2245 Expr *Init,
2246 SourceLocation IdLoc) {
2247 QualType MemberTy = Member->getType();
2248
2249 // We only handle pointers and references currently.
2250 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2251 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2252 return;
2253
2254 const bool IsPointer = MemberTy->isPointerType();
2255 if (IsPointer) {
2256 if (const UnaryOperator *Op
2257 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2258 // The only case we're worried about with pointers requires taking the
2259 // address.
2260 if (Op->getOpcode() != UO_AddrOf)
2261 return;
2262
2263 Init = Op->getSubExpr();
2264 } else {
2265 // We only handle address-of expression initializers for pointers.
2266 return;
2267 }
2268 }
2269
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002270 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2271 // Taking the address of a temporary will be diagnosed as a hard error.
2272 if (IsPointer)
2273 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002274
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002275 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2276 << Member << Init->getSourceRange();
2277 } else if (const DeclRefExpr *DRE
2278 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2279 // We only warn when referring to a non-reference parameter declaration.
2280 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2281 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002282 return;
2283
2284 S.Diag(Init->getExprLoc(),
2285 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2286 : diag::warn_bind_ref_member_to_parameter)
2287 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002288 } else {
2289 // Other initializers are fine.
2290 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002291 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002292
2293 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2294 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002295}
2296
John McCallf312b1e2010-08-26 23:41:50 +00002297MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002298Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002299 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002300 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2301 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2302 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002303 "Member must be a FieldDecl or IndirectFieldDecl");
2304
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002305 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002306 return true;
2307
Douglas Gregor464b2f02010-11-05 22:21:31 +00002308 if (Member->isInvalidDecl())
2309 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002310
John McCallb4190042009-11-04 23:02:40 +00002311 // Diagnose value-uses of fields to initialize themselves, e.g.
2312 // foo(foo)
2313 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002314 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002315 Expr **Args;
2316 unsigned NumArgs;
2317 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2318 Args = ParenList->getExprs();
2319 NumArgs = ParenList->getNumExprs();
2320 } else {
2321 InitListExpr *InitList = cast<InitListExpr>(Init);
2322 Args = InitList->getInits();
2323 NumArgs = InitList->getNumInits();
2324 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002325
Richard Trieude5e75c2012-06-14 23:11:34 +00002326 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2327 != DiagnosticsEngine::Ignored)
2328 for (unsigned i = 0; i < NumArgs; ++i)
2329 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002330 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002331 // initializing the i'th field, throw a warning if any of the >= i'th
2332 // fields are used, as they are not yet initialized.
2333 // Right now we are only handling the case where the i'th field uses
2334 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002335 // Also need to take into account that some fields may be initialized by
2336 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002337 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002338
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002339 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002340
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002341 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002342 // Can't check initialization for a member of dependent type or when
2343 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002344 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002345 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002346 bool InitList = false;
2347 if (isa<InitListExpr>(Init)) {
2348 InitList = true;
2349 Args = &Init;
2350 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002351
2352 if (isStdInitializerList(Member->getType(), 0)) {
2353 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2354 << /*at end of ctor*/1 << InitRange;
2355 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002356 }
2357
Chandler Carruth894aed92010-12-06 09:23:57 +00002358 // Initialize the member.
2359 InitializedEntity MemberEntity =
2360 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2361 : InitializedEntity::InitializeMember(IndirectMember, 0);
2362 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002363 InitList ? InitializationKind::CreateDirectList(IdLoc)
2364 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2365 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002366
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002367 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2368 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002369 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002370 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002371 if (MemberInit.isInvalid())
2372 return true;
2373
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002374 CheckImplicitConversions(MemberInit.get(),
2375 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002376
2377 // C++0x [class.base.init]p7:
2378 // The initialization of each base and member constitutes a
2379 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002380 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002381 if (MemberInit.isInvalid())
2382 return true;
2383
2384 // If we are in a dependent context, template instantiation will
2385 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002386 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002387 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2388 // of the information that we have about the member
2389 // initializer. However, deconstructing the ASTs is a dicey process,
2390 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002391 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002392 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002393 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002394 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002395 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2396 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002397 }
2398
Chandler Carruth894aed92010-12-06 09:23:57 +00002399 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002400 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2401 InitRange.getBegin(), Init,
2402 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002403 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002404 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2405 InitRange.getBegin(), Init,
2406 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002407 }
Eli Friedman59c04372009-07-29 19:44:27 +00002408}
2409
John McCallf312b1e2010-08-26 23:41:50 +00002410MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002411Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002412 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002413 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002414 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002415 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002416 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002417 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002418
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002419 bool InitList = true;
2420 Expr **Args = &Init;
2421 unsigned NumArgs = 1;
2422 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2423 InitList = false;
2424 Args = ParenList->getExprs();
2425 NumArgs = ParenList->getNumExprs();
2426 }
2427
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002428 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002429 // Initialize the object.
2430 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2431 QualType(ClassDecl->getTypeForDecl(), 0));
2432 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002433 InitList ? InitializationKind::CreateDirectList(NameLoc)
2434 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2435 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002436 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2437 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002438 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002439 0);
Sean Hunt41717662011-02-26 19:13:13 +00002440 if (DelegationInit.isInvalid())
2441 return true;
2442
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002443 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2444 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002445
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002446 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002447
2448 // C++0x [class.base.init]p7:
2449 // The initialization of each base and member constitutes a
2450 // full-expression.
2451 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2452 if (DelegationInit.isInvalid())
2453 return true;
2454
Eli Friedmand21016f2012-05-19 23:35:23 +00002455 // If we are in a dependent context, template instantiation will
2456 // perform this type-checking again. Just save the arguments that we
2457 // received in a ParenListExpr.
2458 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2459 // of the information that we have about the base
2460 // initializer. However, deconstructing the ASTs is a dicey process,
2461 // and this approach is far more likely to get the corner cases right.
2462 if (CurContext->isDependentContext())
2463 DelegationInit = Owned(Init);
2464
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002465 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002466 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002467 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002468}
2469
2470MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002471Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002472 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002473 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002474 SourceLocation BaseLoc
2475 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002476
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002477 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2478 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2479 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2480
2481 // C++ [class.base.init]p2:
2482 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002483 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002484 // of that class, the mem-initializer is ill-formed. A
2485 // mem-initializer-list can initialize a base class using any
2486 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002487 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002488
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002489 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002490 if (EllipsisLoc.isValid()) {
2491 // This is a pack expansion.
2492 if (!BaseType->containsUnexpandedParameterPack()) {
2493 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002494 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002495
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002496 EllipsisLoc = SourceLocation();
2497 }
2498 } else {
2499 // Check for any unexpanded parameter packs.
2500 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2501 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002502
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002503 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002504 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002505 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002506
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002507 // Check for direct and virtual base classes.
2508 const CXXBaseSpecifier *DirectBaseSpec = 0;
2509 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2510 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002511 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2512 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002513 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002514
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002515 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2516 VirtualBaseSpec);
2517
2518 // C++ [base.class.init]p2:
2519 // Unless the mem-initializer-id names a nonstatic data member of the
2520 // constructor's class or a direct or virtual base of that class, the
2521 // mem-initializer is ill-formed.
2522 if (!DirectBaseSpec && !VirtualBaseSpec) {
2523 // If the class has any dependent bases, then it's possible that
2524 // one of those types will resolve to the same type as
2525 // BaseType. Therefore, just treat this as a dependent base
2526 // class initialization. FIXME: Should we try to check the
2527 // initialization anyway? It seems odd.
2528 if (ClassDecl->hasAnyDependentBases())
2529 Dependent = true;
2530 else
2531 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2532 << BaseType << Context.getTypeDeclType(ClassDecl)
2533 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2534 }
2535 }
2536
2537 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002538 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002539
Sebastian Redl6df65482011-09-24 17:48:25 +00002540 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2541 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002542 InitRange.getBegin(), Init,
2543 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002544 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002545
2546 // C++ [base.class.init]p2:
2547 // If a mem-initializer-id is ambiguous because it designates both
2548 // a direct non-virtual base class and an inherited virtual base
2549 // class, the mem-initializer is ill-formed.
2550 if (DirectBaseSpec && VirtualBaseSpec)
2551 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002552 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002553
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002554 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002555 if (!BaseSpec)
2556 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2557
2558 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002559 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002560 Expr **Args = &Init;
2561 unsigned NumArgs = 1;
2562 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002563 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002564 Args = ParenList->getExprs();
2565 NumArgs = ParenList->getNumExprs();
2566 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002567
2568 InitializedEntity BaseEntity =
2569 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2570 InitializationKind Kind =
2571 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2572 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2573 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002574 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2575 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002576 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002577 if (BaseInit.isInvalid())
2578 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002579
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002580 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002581
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002582 // C++0x [class.base.init]p7:
2583 // The initialization of each base and member constitutes a
2584 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002585 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002586 if (BaseInit.isInvalid())
2587 return true;
2588
2589 // If we are in a dependent context, template instantiation will
2590 // perform this type-checking again. Just save the arguments that we
2591 // received in a ParenListExpr.
2592 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2593 // of the information that we have about the base
2594 // initializer. However, deconstructing the ASTs is a dicey process,
2595 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002596 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002597 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002598
Sean Huntcbb67482011-01-08 20:30:50 +00002599 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002600 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002601 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002602 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002603 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002604}
2605
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002606// Create a static_cast\<T&&>(expr).
2607static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2608 QualType ExprType = E->getType();
2609 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2610 SourceLocation ExprLoc = E->getLocStart();
2611 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2612 TargetType, ExprLoc);
2613
2614 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2615 SourceRange(ExprLoc, ExprLoc),
2616 E->getSourceRange()).take();
2617}
2618
Anders Carlssone5ef7402010-04-23 03:10:23 +00002619/// ImplicitInitializerKind - How an implicit base or member initializer should
2620/// initialize its base or member.
2621enum ImplicitInitializerKind {
2622 IIK_Default,
2623 IIK_Copy,
2624 IIK_Move
2625};
2626
Anders Carlssondefefd22010-04-23 02:00:02 +00002627static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002628BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002629 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002630 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002631 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002632 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002633 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002634 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2635 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002636
John McCall60d7b3a2010-08-24 06:29:42 +00002637 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002638
2639 switch (ImplicitInitKind) {
2640 case IIK_Default: {
2641 InitializationKind InitKind
2642 = InitializationKind::CreateDefault(Constructor->getLocation());
2643 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002644 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002645 break;
2646 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002647
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002648 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002649 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002650 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002651 ParmVarDecl *Param = Constructor->getParamDecl(0);
2652 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002653
Anders Carlssone5ef7402010-04-23 03:10:23 +00002654 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002655 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002656 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002657 Constructor->getLocation(), ParamType,
2658 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002659
Eli Friedman5f2987c2012-02-02 03:46:19 +00002660 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2661
Anders Carlssonc7957502010-04-24 22:02:54 +00002662 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002663 QualType ArgTy =
2664 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2665 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002666
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002667 if (Moving) {
2668 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2669 }
2670
John McCallf871d0c2010-08-07 06:22:56 +00002671 CXXCastPath BasePath;
2672 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002673 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2674 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002675 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002676 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002677
Anders Carlssone5ef7402010-04-23 03:10:23 +00002678 InitializationKind InitKind
2679 = InitializationKind::CreateDirect(Constructor->getLocation(),
2680 SourceLocation(), SourceLocation());
2681 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2682 &CopyCtorArg, 1);
2683 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002684 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002685 break;
2686 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002687 }
John McCall9ae2f072010-08-23 23:25:46 +00002688
Douglas Gregor53c374f2010-12-07 00:41:46 +00002689 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002690 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002691 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002692
Anders Carlssondefefd22010-04-23 02:00:02 +00002693 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002694 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002695 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2696 SourceLocation()),
2697 BaseSpec->isVirtual(),
2698 SourceLocation(),
2699 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002700 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002701 SourceLocation());
2702
Anders Carlssondefefd22010-04-23 02:00:02 +00002703 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002704}
2705
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002706static bool RefersToRValueRef(Expr *MemRef) {
2707 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2708 return Referenced->getType()->isRValueReferenceType();
2709}
2710
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002711static bool
2712BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002713 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002714 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002715 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002716 if (Field->isInvalidDecl())
2717 return true;
2718
Chandler Carruthf186b542010-06-29 23:50:44 +00002719 SourceLocation Loc = Constructor->getLocation();
2720
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002721 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2722 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002723 ParmVarDecl *Param = Constructor->getParamDecl(0);
2724 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002725
2726 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002727 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2728 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002729
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002730 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002731 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002732 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002733 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002734
Eli Friedman5f2987c2012-02-02 03:46:19 +00002735 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2736
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002737 if (Moving) {
2738 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2739 }
2740
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002741 // Build a reference to this field within the parameter.
2742 CXXScopeSpec SS;
2743 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2744 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002745 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2746 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002747 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002748 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002749 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002750 ParamType, Loc,
2751 /*IsArrow=*/false,
2752 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002753 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002754 /*FirstQualifierInScope=*/0,
2755 MemberLookup,
2756 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002757 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002758 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002759
2760 // C++11 [class.copy]p15:
2761 // - if a member m has rvalue reference type T&&, it is direct-initialized
2762 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002763 if (RefersToRValueRef(CtorArg.get())) {
2764 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002765 }
2766
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002767 // When the field we are copying is an array, create index variables for
2768 // each dimension of the array. We use these index variables to subscript
2769 // the source array, and other clients (e.g., CodeGen) will perform the
2770 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002771 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002772 QualType BaseType = Field->getType();
2773 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002774 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002775 while (const ConstantArrayType *Array
2776 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002777 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002778 // Create the iteration variable for this array index.
2779 IdentifierInfo *IterationVarName = 0;
2780 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002781 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002782 llvm::raw_svector_ostream OS(Str);
2783 OS << "__i" << IndexVariables.size();
2784 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2785 }
2786 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002787 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002788 IterationVarName, SizeType,
2789 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002790 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002791 IndexVariables.push_back(IterationVar);
2792
2793 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002794 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002795 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002796 assert(!IterationVarRef.isInvalid() &&
2797 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002798 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2799 assert(!IterationVarRef.isInvalid() &&
2800 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002801
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002802 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002803 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002804 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002805 Loc);
2806 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002807 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002808
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002809 BaseType = Array->getElementType();
2810 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002811
2812 // The array subscript expression is an lvalue, which is wrong for moving.
2813 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002814 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002815
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002816 // Construct the entity that we will be initializing. For an array, this
2817 // will be first element in the array, which may require several levels
2818 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002819 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002820 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002821 if (Indirect)
2822 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2823 else
2824 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002825 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2826 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2827 0,
2828 Entities.back()));
2829
2830 // Direct-initialize to use the copy constructor.
2831 InitializationKind InitKind =
2832 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2833
Sebastian Redl74e611a2011-09-04 18:14:28 +00002834 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002835 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002836 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002837
John McCall60d7b3a2010-08-24 06:29:42 +00002838 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002839 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002840 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002841 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002842 if (MemberInit.isInvalid())
2843 return true;
2844
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002845 if (Indirect) {
2846 assert(IndexVariables.size() == 0 &&
2847 "Indirect field improperly initialized");
2848 CXXMemberInit
2849 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2850 Loc, Loc,
2851 MemberInit.takeAs<Expr>(),
2852 Loc);
2853 } else
2854 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2855 Loc, MemberInit.takeAs<Expr>(),
2856 Loc,
2857 IndexVariables.data(),
2858 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002859 return false;
2860 }
2861
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002862 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2863
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002864 QualType FieldBaseElementType =
2865 SemaRef.Context.getBaseElementType(Field->getType());
2866
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002867 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002868 InitializedEntity InitEntity
2869 = Indirect? InitializedEntity::InitializeMember(Indirect)
2870 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002871 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002872 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002873
2874 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002875 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002876 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002877
Douglas Gregor53c374f2010-12-07 00:41:46 +00002878 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002879 if (MemberInit.isInvalid())
2880 return true;
2881
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002882 if (Indirect)
2883 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2884 Indirect, Loc,
2885 Loc,
2886 MemberInit.get(),
2887 Loc);
2888 else
2889 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2890 Field, Loc, Loc,
2891 MemberInit.get(),
2892 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002893 return false;
2894 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002895
Sean Hunt1f2f3842011-05-17 00:19:05 +00002896 if (!Field->getParent()->isUnion()) {
2897 if (FieldBaseElementType->isReferenceType()) {
2898 SemaRef.Diag(Constructor->getLocation(),
2899 diag::err_uninitialized_member_in_ctor)
2900 << (int)Constructor->isImplicit()
2901 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2902 << 0 << Field->getDeclName();
2903 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2904 return true;
2905 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002906
Sean Hunt1f2f3842011-05-17 00:19:05 +00002907 if (FieldBaseElementType.isConstQualified()) {
2908 SemaRef.Diag(Constructor->getLocation(),
2909 diag::err_uninitialized_member_in_ctor)
2910 << (int)Constructor->isImplicit()
2911 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2912 << 1 << Field->getDeclName();
2913 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2914 return true;
2915 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002916 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002917
David Blaikie4e4d0842012-03-11 07:00:24 +00002918 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002919 FieldBaseElementType->isObjCRetainableType() &&
2920 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2921 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002922 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002923 // Default-initialize Objective-C pointers to NULL.
2924 CXXMemberInit
2925 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2926 Loc, Loc,
2927 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2928 Loc);
2929 return false;
2930 }
2931
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002932 // Nothing to initialize.
2933 CXXMemberInit = 0;
2934 return false;
2935}
John McCallf1860e52010-05-20 23:23:51 +00002936
2937namespace {
2938struct BaseAndFieldInfo {
2939 Sema &S;
2940 CXXConstructorDecl *Ctor;
2941 bool AnyErrorsInInits;
2942 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002943 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002944 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002945
2946 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2947 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002948 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2949 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002950 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002951 else if (Generated && Ctor->isMoveConstructor())
2952 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002953 else
2954 IIK = IIK_Default;
2955 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002956
2957 bool isImplicitCopyOrMove() const {
2958 switch (IIK) {
2959 case IIK_Copy:
2960 case IIK_Move:
2961 return true;
2962
2963 case IIK_Default:
2964 return false;
2965 }
David Blaikie30263482012-01-20 21:50:17 +00002966
2967 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002968 }
Richard Smith0b8220a2012-08-07 21:30:42 +00002969
2970 bool addFieldInitializer(CXXCtorInitializer *Init) {
2971 AllToInit.push_back(Init);
2972
2973 // Check whether this initializer makes the field "used".
2974 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2975 S.UnusedPrivateFields.remove(Init->getAnyMember());
2976
2977 return false;
2978 }
John McCallf1860e52010-05-20 23:23:51 +00002979};
2980}
2981
Richard Smitha4950662011-09-19 13:34:43 +00002982/// \brief Determine whether the given indirect field declaration is somewhere
2983/// within an anonymous union.
2984static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2985 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2986 CEnd = F->chain_end();
2987 C != CEnd; ++C)
2988 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2989 if (Record->isUnion())
2990 return true;
2991
2992 return false;
2993}
2994
Douglas Gregorddb21472011-11-02 23:04:16 +00002995/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2996/// array type.
2997static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2998 if (T->isIncompleteArrayType())
2999 return true;
3000
3001 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3002 if (!ArrayT->getSize())
3003 return true;
3004
3005 T = ArrayT->getElementType();
3006 }
3007
3008 return false;
3009}
3010
Richard Smith7a614d82011-06-11 17:19:42 +00003011static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003012 FieldDecl *Field,
3013 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003014
Chandler Carruthe861c602010-06-30 02:59:29 +00003015 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003016 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3017 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003018
Richard Smith0b8220a2012-08-07 21:30:42 +00003019 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003020 // has a brace-or-equal-initializer, the entity is initialized as specified
3021 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003022 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003023 CXXCtorInitializer *Init;
3024 if (Indirect)
3025 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3026 SourceLocation(),
3027 SourceLocation(), 0,
3028 SourceLocation());
3029 else
3030 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3031 SourceLocation(),
3032 SourceLocation(), 0,
3033 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003034 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003035 }
3036
Richard Smithc115f632011-09-18 11:14:50 +00003037 // Don't build an implicit initializer for union members if none was
3038 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003039 if (Field->getParent()->isUnion() ||
3040 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003041 return false;
3042
Douglas Gregorddb21472011-11-02 23:04:16 +00003043 // Don't initialize incomplete or zero-length arrays.
3044 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3045 return false;
3046
John McCallf1860e52010-05-20 23:23:51 +00003047 // Don't try to build an implicit initializer if there were semantic
3048 // errors in any of the initializers (and therefore we might be
3049 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003050 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003051 return false;
3052
Sean Huntcbb67482011-01-08 20:30:50 +00003053 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003054 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3055 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003056 return true;
John McCallf1860e52010-05-20 23:23:51 +00003057
Richard Smith0b8220a2012-08-07 21:30:42 +00003058 if (!Init)
3059 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003060
Richard Smith0b8220a2012-08-07 21:30:42 +00003061 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003062}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003063
3064bool
3065Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3066 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003067 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003068 Constructor->setNumCtorInitializers(1);
3069 CXXCtorInitializer **initializer =
3070 new (Context) CXXCtorInitializer*[1];
3071 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3072 Constructor->setCtorInitializers(initializer);
3073
Sean Huntb76af9c2011-05-03 23:05:34 +00003074 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003075 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003076 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3077 }
3078
Sean Huntc1598702011-05-05 00:05:47 +00003079 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003080
Sean Hunt059ce0d2011-05-01 07:04:31 +00003081 return false;
3082}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003083
John McCallb77115d2011-06-17 00:18:42 +00003084bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
3085 CXXCtorInitializer **Initializers,
3086 unsigned NumInitializers,
3087 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003088 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003089 // Just store the initializers as written, they will be checked during
3090 // instantiation.
3091 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003092 Constructor->setNumCtorInitializers(NumInitializers);
3093 CXXCtorInitializer **baseOrMemberInitializers =
3094 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003095 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00003096 NumInitializers * sizeof(CXXCtorInitializer*));
3097 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003098 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003099
3100 // Let template instantiation know whether we had errors.
3101 if (AnyErrors)
3102 Constructor->setInvalidDecl();
3103
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003104 return false;
3105 }
3106
John McCallf1860e52010-05-20 23:23:51 +00003107 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003108
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003109 // We need to build the initializer AST according to order of construction
3110 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003111 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003112 if (!ClassDecl)
3113 return true;
3114
Eli Friedman80c30da2009-11-09 19:20:36 +00003115 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003116
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003117 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003118 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003119
3120 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003121 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003122 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003123 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003124 }
3125
Anders Carlsson711f34a2010-04-21 19:52:01 +00003126 // Keep track of the direct virtual bases.
3127 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3128 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3129 E = ClassDecl->bases_end(); I != E; ++I) {
3130 if (I->isVirtual())
3131 DirectVBases.insert(I);
3132 }
3133
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003134 // Push virtual bases before others.
3135 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3136 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3137
Sean Huntcbb67482011-01-08 20:30:50 +00003138 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003139 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3140 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003141 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003142 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003143 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003144 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003145 VBase, IsInheritedVirtualBase,
3146 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003147 HadError = true;
3148 continue;
3149 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003150
John McCallf1860e52010-05-20 23:23:51 +00003151 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003152 }
3153 }
Mike Stump1eb44332009-09-09 15:08:12 +00003154
John McCallf1860e52010-05-20 23:23:51 +00003155 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003156 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3157 E = ClassDecl->bases_end(); Base != E; ++Base) {
3158 // Virtuals are in the virtual base list and already constructed.
3159 if (Base->isVirtual())
3160 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003161
Sean Huntcbb67482011-01-08 20:30:50 +00003162 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003163 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3164 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003165 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003166 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003167 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003168 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003169 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003170 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003171 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003172 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003173
John McCallf1860e52010-05-20 23:23:51 +00003174 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003175 }
3176 }
Mike Stump1eb44332009-09-09 15:08:12 +00003177
John McCallf1860e52010-05-20 23:23:51 +00003178 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003179 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3180 MemEnd = ClassDecl->decls_end();
3181 Mem != MemEnd; ++Mem) {
3182 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003183 // C++ [class.bit]p2:
3184 // A declaration for a bit-field that omits the identifier declares an
3185 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3186 // initialized.
3187 if (F->isUnnamedBitfield())
3188 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003189
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003190 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003191 // handle anonymous struct/union fields based on their individual
3192 // indirect fields.
3193 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3194 continue;
3195
3196 if (CollectFieldInitializer(*this, Info, F))
3197 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003198 continue;
3199 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003200
3201 // Beyond this point, we only consider default initialization.
3202 if (Info.IIK != IIK_Default)
3203 continue;
3204
3205 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3206 if (F->getType()->isIncompleteArrayType()) {
3207 assert(ClassDecl->hasFlexibleArrayMember() &&
3208 "Incomplete array type is not valid");
3209 continue;
3210 }
3211
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003212 // Initialize each field of an anonymous struct individually.
3213 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3214 HadError = true;
3215
3216 continue;
3217 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003218 }
Mike Stump1eb44332009-09-09 15:08:12 +00003219
John McCallf1860e52010-05-20 23:23:51 +00003220 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003221 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003222 Constructor->setNumCtorInitializers(NumInitializers);
3223 CXXCtorInitializer **baseOrMemberInitializers =
3224 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003225 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003226 NumInitializers * sizeof(CXXCtorInitializer*));
3227 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003228
John McCallef027fe2010-03-16 21:39:52 +00003229 // Constructors implicitly reference the base and member
3230 // destructors.
3231 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3232 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003233 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003234
3235 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003236}
3237
Eli Friedman6347f422009-07-21 19:28:10 +00003238static void *GetKeyForTopLevelField(FieldDecl *Field) {
3239 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003240 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003241 if (RT->getDecl()->isAnonymousStructOrUnion())
3242 return static_cast<void *>(RT->getDecl());
3243 }
3244 return static_cast<void *>(Field);
3245}
3246
Anders Carlssonea356fb2010-04-02 05:42:15 +00003247static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003248 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003249}
3250
Anders Carlssonea356fb2010-04-02 05:42:15 +00003251static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003252 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003253 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003254 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003255
Eli Friedman6347f422009-07-21 19:28:10 +00003256 // For fields injected into the class via declaration of an anonymous union,
3257 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003258 FieldDecl *Field = Member->getAnyMember();
3259
John McCall3c3ccdb2010-04-10 09:28:51 +00003260 // If the field is a member of an anonymous struct or union, our key
3261 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003262 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003263 if (RD->isAnonymousStructOrUnion()) {
3264 while (true) {
3265 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3266 if (Parent->isAnonymousStructOrUnion())
3267 RD = Parent;
3268 else
3269 break;
3270 }
3271
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003272 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003273 }
Mike Stump1eb44332009-09-09 15:08:12 +00003274
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003275 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003276}
3277
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003278static void
3279DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003280 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003281 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003282 unsigned NumInits) {
3283 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003284 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003285
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003286 // Don't check initializers order unless the warning is enabled at the
3287 // location of at least one initializer.
3288 bool ShouldCheckOrder = false;
3289 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003290 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003291 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3292 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003293 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003294 ShouldCheckOrder = true;
3295 break;
3296 }
3297 }
3298 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003299 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003300
John McCalld6ca8da2010-04-10 07:37:23 +00003301 // Build the list of bases and members in the order that they'll
3302 // actually be initialized. The explicit initializers should be in
3303 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003304 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003305
Anders Carlsson071d6102010-04-02 03:38:04 +00003306 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3307
John McCalld6ca8da2010-04-10 07:37:23 +00003308 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003309 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003310 ClassDecl->vbases_begin(),
3311 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003312 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003313
John McCalld6ca8da2010-04-10 07:37:23 +00003314 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003315 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003316 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003317 if (Base->isVirtual())
3318 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003319 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003320 }
Mike Stump1eb44332009-09-09 15:08:12 +00003321
John McCalld6ca8da2010-04-10 07:37:23 +00003322 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003323 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003324 E = ClassDecl->field_end(); Field != E; ++Field) {
3325 if (Field->isUnnamedBitfield())
3326 continue;
3327
David Blaikie581deb32012-06-06 20:45:41 +00003328 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003329 }
3330
John McCalld6ca8da2010-04-10 07:37:23 +00003331 unsigned NumIdealInits = IdealInitKeys.size();
3332 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003333
Sean Huntcbb67482011-01-08 20:30:50 +00003334 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003335 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003336 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003337 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003338
3339 // Scan forward to try to find this initializer in the idealized
3340 // initializers list.
3341 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3342 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003343 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003344
3345 // If we didn't find this initializer, it must be because we
3346 // scanned past it on a previous iteration. That can only
3347 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003348 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003349 Sema::SemaDiagnosticBuilder D =
3350 SemaRef.Diag(PrevInit->getSourceLocation(),
3351 diag::warn_initializer_out_of_order);
3352
Francois Pichet00eb3f92010-12-04 09:14:42 +00003353 if (PrevInit->isAnyMemberInitializer())
3354 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003355 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003356 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003357
Francois Pichet00eb3f92010-12-04 09:14:42 +00003358 if (Init->isAnyMemberInitializer())
3359 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003360 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003361 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003362
3363 // Move back to the initializer's location in the ideal list.
3364 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3365 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003366 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003367
3368 assert(IdealIndex != NumIdealInits &&
3369 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003370 }
John McCalld6ca8da2010-04-10 07:37:23 +00003371
3372 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003373 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003374}
3375
John McCall3c3ccdb2010-04-10 09:28:51 +00003376namespace {
3377bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003378 CXXCtorInitializer *Init,
3379 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003380 if (!PrevInit) {
3381 PrevInit = Init;
3382 return false;
3383 }
3384
3385 if (FieldDecl *Field = Init->getMember())
3386 S.Diag(Init->getSourceLocation(),
3387 diag::err_multiple_mem_initialization)
3388 << Field->getDeclName()
3389 << Init->getSourceRange();
3390 else {
John McCallf4c73712011-01-19 06:33:43 +00003391 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003392 assert(BaseClass && "neither field nor base");
3393 S.Diag(Init->getSourceLocation(),
3394 diag::err_multiple_base_initialization)
3395 << QualType(BaseClass, 0)
3396 << Init->getSourceRange();
3397 }
3398 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3399 << 0 << PrevInit->getSourceRange();
3400
3401 return true;
3402}
3403
Sean Huntcbb67482011-01-08 20:30:50 +00003404typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003405typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3406
3407bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003408 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003409 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003410 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003411 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003412 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003413
3414 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003415 if (Parent->isUnion()) {
3416 UnionEntry &En = Unions[Parent];
3417 if (En.first && En.first != Child) {
3418 S.Diag(Init->getSourceLocation(),
3419 diag::err_multiple_mem_union_initialization)
3420 << Field->getDeclName()
3421 << Init->getSourceRange();
3422 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3423 << 0 << En.second->getSourceRange();
3424 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003425 }
3426 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003427 En.first = Child;
3428 En.second = Init;
3429 }
David Blaikie6fe29652011-11-17 06:01:57 +00003430 if (!Parent->isAnonymousStructOrUnion())
3431 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003432 }
3433
3434 Child = Parent;
3435 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003436 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003437
3438 return false;
3439}
3440}
3441
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003442/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003443void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003444 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003445 CXXCtorInitializer **meminits,
3446 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003447 bool AnyErrors) {
3448 if (!ConstructorDecl)
3449 return;
3450
3451 AdjustDeclIfTemplate(ConstructorDecl);
3452
3453 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003454 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003455
3456 if (!Constructor) {
3457 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3458 return;
3459 }
3460
Sean Huntcbb67482011-01-08 20:30:50 +00003461 CXXCtorInitializer **MemInits =
3462 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003463
3464 // Mapping for the duplicate initializers check.
3465 // For member initializers, this is keyed with a FieldDecl*.
3466 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003467 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003468
3469 // Mapping for the inconsistent anonymous-union initializers check.
3470 RedundantUnionMap MemberUnions;
3471
Anders Carlssonea356fb2010-04-02 05:42:15 +00003472 bool HadError = false;
3473 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003474 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003475
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003476 // Set the source order index.
3477 Init->setSourceOrder(i);
3478
Francois Pichet00eb3f92010-12-04 09:14:42 +00003479 if (Init->isAnyMemberInitializer()) {
3480 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003481 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3482 CheckRedundantUnionInit(*this, Init, MemberUnions))
3483 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003484 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003485 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3486 if (CheckRedundantInit(*this, Init, Members[Key]))
3487 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003488 } else {
3489 assert(Init->isDelegatingInitializer());
3490 // This must be the only initializer
Richard Smitha6ddea62012-09-14 18:21:10 +00003491 if (NumMemInits != 1) {
3492 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003493 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003494 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003495 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003496 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003497 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003498 // Return immediately as the initializer is set.
3499 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003500 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003501 }
3502
Anders Carlssonea356fb2010-04-02 05:42:15 +00003503 if (HadError)
3504 return;
3505
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003506 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003507
Sean Huntcbb67482011-01-08 20:30:50 +00003508 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003509}
3510
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003511void
John McCallef027fe2010-03-16 21:39:52 +00003512Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3513 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003514 // Ignore dependent contexts. Also ignore unions, since their members never
3515 // have destructors implicitly called.
3516 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003517 return;
John McCall58e6f342010-03-16 05:22:47 +00003518
3519 // FIXME: all the access-control diagnostics are positioned on the
3520 // field/base declaration. That's probably good; that said, the
3521 // user might reasonably want to know why the destructor is being
3522 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003523
Anders Carlsson9f853df2009-11-17 04:44:12 +00003524 // Non-static data members.
3525 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3526 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003527 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003528 if (Field->isInvalidDecl())
3529 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003530
3531 // Don't destroy incomplete or zero-length arrays.
3532 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3533 continue;
3534
Anders Carlsson9f853df2009-11-17 04:44:12 +00003535 QualType FieldType = Context.getBaseElementType(Field->getType());
3536
3537 const RecordType* RT = FieldType->getAs<RecordType>();
3538 if (!RT)
3539 continue;
3540
3541 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003542 if (FieldClassDecl->isInvalidDecl())
3543 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003544 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003545 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003546 // The destructor for an implicit anonymous union member is never invoked.
3547 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3548 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003549
Douglas Gregordb89f282010-07-01 22:47:18 +00003550 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003551 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003552 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003553 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003554 << Field->getDeclName()
3555 << FieldType);
3556
Eli Friedman5f2987c2012-02-02 03:46:19 +00003557 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003558 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003559 }
3560
John McCall58e6f342010-03-16 05:22:47 +00003561 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3562
Anders Carlsson9f853df2009-11-17 04:44:12 +00003563 // Bases.
3564 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3565 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003566 // Bases are always records in a well-formed non-dependent class.
3567 const RecordType *RT = Base->getType()->getAs<RecordType>();
3568
3569 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003570 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003571 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003572
John McCall58e6f342010-03-16 05:22:47 +00003573 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003574 // If our base class is invalid, we probably can't get its dtor anyway.
3575 if (BaseClassDecl->isInvalidDecl())
3576 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003577 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003578 continue;
John McCall58e6f342010-03-16 05:22:47 +00003579
Douglas Gregordb89f282010-07-01 22:47:18 +00003580 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003581 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003582
3583 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003584 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003585 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003586 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003587 << Base->getSourceRange(),
3588 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003589
Eli Friedman5f2987c2012-02-02 03:46:19 +00003590 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003591 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003592 }
3593
3594 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003595 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3596 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003597
3598 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003599 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003600
3601 // Ignore direct virtual bases.
3602 if (DirectVirtualBases.count(RT))
3603 continue;
3604
John McCall58e6f342010-03-16 05:22:47 +00003605 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003606 // If our base class is invalid, we probably can't get its dtor anyway.
3607 if (BaseClassDecl->isInvalidDecl())
3608 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003609 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003610 continue;
John McCall58e6f342010-03-16 05:22:47 +00003611
Douglas Gregordb89f282010-07-01 22:47:18 +00003612 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003613 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003614 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003615 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003616 << VBase->getType(),
3617 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003618
Eli Friedman5f2987c2012-02-02 03:46:19 +00003619 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003620 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003621 }
3622}
3623
John McCalld226f652010-08-21 09:40:31 +00003624void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003625 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003626 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003627
Mike Stump1eb44332009-09-09 15:08:12 +00003628 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003629 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003630 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003631}
3632
Mike Stump1eb44332009-09-09 15:08:12 +00003633bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003634 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003635 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3636 unsigned DiagID;
3637 AbstractDiagSelID SelID;
3638
3639 public:
3640 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3641 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3642
3643 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003644 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003645 if (SelID == -1)
3646 S.Diag(Loc, DiagID) << T;
3647 else
3648 S.Diag(Loc, DiagID) << SelID << T;
3649 }
3650 } Diagnoser(DiagID, SelID);
3651
3652 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003653}
3654
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003655bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003656 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003657 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003658 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003659
Anders Carlsson11f21a02009-03-23 19:10:31 +00003660 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003661 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003662
Ted Kremenek6217b802009-07-29 21:53:49 +00003663 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003664 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003665 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003666 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003667
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003668 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003669 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003670 }
Mike Stump1eb44332009-09-09 15:08:12 +00003671
Ted Kremenek6217b802009-07-29 21:53:49 +00003672 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003673 if (!RT)
3674 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003675
John McCall86ff3082010-02-04 22:26:26 +00003676 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003677
John McCall94c3b562010-08-18 09:41:07 +00003678 // We can't answer whether something is abstract until it has a
3679 // definition. If it's currently being defined, we'll walk back
3680 // over all the declarations when we have a full definition.
3681 const CXXRecordDecl *Def = RD->getDefinition();
3682 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003683 return false;
3684
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003685 if (!RD->isAbstract())
3686 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003687
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003688 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003689 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003690
John McCall94c3b562010-08-18 09:41:07 +00003691 return true;
3692}
3693
3694void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3695 // Check if we've already emitted the list of pure virtual functions
3696 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003697 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003698 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003699
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003700 CXXFinalOverriderMap FinalOverriders;
3701 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003702
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003703 // Keep a set of seen pure methods so we won't diagnose the same method
3704 // more than once.
3705 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3706
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003707 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3708 MEnd = FinalOverriders.end();
3709 M != MEnd;
3710 ++M) {
3711 for (OverridingMethods::iterator SO = M->second.begin(),
3712 SOEnd = M->second.end();
3713 SO != SOEnd; ++SO) {
3714 // C++ [class.abstract]p4:
3715 // A class is abstract if it contains or inherits at least one
3716 // pure virtual function for which the final overrider is pure
3717 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003718
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003719 //
3720 if (SO->second.size() != 1)
3721 continue;
3722
3723 if (!SO->second.front().Method->isPure())
3724 continue;
3725
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003726 if (!SeenPureMethods.insert(SO->second.front().Method))
3727 continue;
3728
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003729 Diag(SO->second.front().Method->getLocation(),
3730 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003731 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003732 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003733 }
3734
3735 if (!PureVirtualClassDiagSet)
3736 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3737 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003738}
3739
Anders Carlsson8211eff2009-03-24 01:19:16 +00003740namespace {
John McCall94c3b562010-08-18 09:41:07 +00003741struct AbstractUsageInfo {
3742 Sema &S;
3743 CXXRecordDecl *Record;
3744 CanQualType AbstractType;
3745 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003746
John McCall94c3b562010-08-18 09:41:07 +00003747 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3748 : S(S), Record(Record),
3749 AbstractType(S.Context.getCanonicalType(
3750 S.Context.getTypeDeclType(Record))),
3751 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003752
John McCall94c3b562010-08-18 09:41:07 +00003753 void DiagnoseAbstractType() {
3754 if (Invalid) return;
3755 S.DiagnoseAbstractType(Record);
3756 Invalid = true;
3757 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003758
John McCall94c3b562010-08-18 09:41:07 +00003759 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3760};
3761
3762struct CheckAbstractUsage {
3763 AbstractUsageInfo &Info;
3764 const NamedDecl *Ctx;
3765
3766 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3767 : Info(Info), Ctx(Ctx) {}
3768
3769 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3770 switch (TL.getTypeLocClass()) {
3771#define ABSTRACT_TYPELOC(CLASS, PARENT)
3772#define TYPELOC(CLASS, PARENT) \
3773 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3774#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003775 }
John McCall94c3b562010-08-18 09:41:07 +00003776 }
Mike Stump1eb44332009-09-09 15:08:12 +00003777
John McCall94c3b562010-08-18 09:41:07 +00003778 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3779 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3780 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003781 if (!TL.getArg(I))
3782 continue;
3783
John McCall94c3b562010-08-18 09:41:07 +00003784 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3785 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003786 }
John McCall94c3b562010-08-18 09:41:07 +00003787 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003788
John McCall94c3b562010-08-18 09:41:07 +00003789 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3790 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3791 }
Mike Stump1eb44332009-09-09 15:08:12 +00003792
John McCall94c3b562010-08-18 09:41:07 +00003793 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3794 // Visit the type parameters from a permissive context.
3795 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3796 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3797 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3798 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3799 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3800 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003801 }
John McCall94c3b562010-08-18 09:41:07 +00003802 }
Mike Stump1eb44332009-09-09 15:08:12 +00003803
John McCall94c3b562010-08-18 09:41:07 +00003804 // Visit pointee types from a permissive context.
3805#define CheckPolymorphic(Type) \
3806 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3807 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3808 }
3809 CheckPolymorphic(PointerTypeLoc)
3810 CheckPolymorphic(ReferenceTypeLoc)
3811 CheckPolymorphic(MemberPointerTypeLoc)
3812 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003813 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003814
John McCall94c3b562010-08-18 09:41:07 +00003815 /// Handle all the types we haven't given a more specific
3816 /// implementation for above.
3817 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3818 // Every other kind of type that we haven't called out already
3819 // that has an inner type is either (1) sugar or (2) contains that
3820 // inner type in some way as a subobject.
3821 if (TypeLoc Next = TL.getNextTypeLoc())
3822 return Visit(Next, Sel);
3823
3824 // If there's no inner type and we're in a permissive context,
3825 // don't diagnose.
3826 if (Sel == Sema::AbstractNone) return;
3827
3828 // Check whether the type matches the abstract type.
3829 QualType T = TL.getType();
3830 if (T->isArrayType()) {
3831 Sel = Sema::AbstractArrayType;
3832 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003833 }
John McCall94c3b562010-08-18 09:41:07 +00003834 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3835 if (CT != Info.AbstractType) return;
3836
3837 // It matched; do some magic.
3838 if (Sel == Sema::AbstractArrayType) {
3839 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3840 << T << TL.getSourceRange();
3841 } else {
3842 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3843 << Sel << T << TL.getSourceRange();
3844 }
3845 Info.DiagnoseAbstractType();
3846 }
3847};
3848
3849void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3850 Sema::AbstractDiagSelID Sel) {
3851 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3852}
3853
3854}
3855
3856/// Check for invalid uses of an abstract type in a method declaration.
3857static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3858 CXXMethodDecl *MD) {
3859 // No need to do the check on definitions, which require that
3860 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003861 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003862 return;
3863
3864 // For safety's sake, just ignore it if we don't have type source
3865 // information. This should never happen for non-implicit methods,
3866 // but...
3867 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3868 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3869}
3870
3871/// Check for invalid uses of an abstract type within a class definition.
3872static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3873 CXXRecordDecl *RD) {
3874 for (CXXRecordDecl::decl_iterator
3875 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3876 Decl *D = *I;
3877 if (D->isImplicit()) continue;
3878
3879 // Methods and method templates.
3880 if (isa<CXXMethodDecl>(D)) {
3881 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3882 } else if (isa<FunctionTemplateDecl>(D)) {
3883 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3884 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3885
3886 // Fields and static variables.
3887 } else if (isa<FieldDecl>(D)) {
3888 FieldDecl *FD = cast<FieldDecl>(D);
3889 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3890 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3891 } else if (isa<VarDecl>(D)) {
3892 VarDecl *VD = cast<VarDecl>(D);
3893 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3894 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3895
3896 // Nested classes and class templates.
3897 } else if (isa<CXXRecordDecl>(D)) {
3898 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3899 } else if (isa<ClassTemplateDecl>(D)) {
3900 CheckAbstractClassUsage(Info,
3901 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3902 }
3903 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003904}
3905
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003906/// \brief Perform semantic checks on a class definition that has been
3907/// completing, introducing implicitly-declared members, checking for
3908/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003909void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003910 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003911 return;
3912
John McCall94c3b562010-08-18 09:41:07 +00003913 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3914 AbstractUsageInfo Info(*this, Record);
3915 CheckAbstractClassUsage(Info, Record);
3916 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003917
3918 // If this is not an aggregate type and has no user-declared constructor,
3919 // complain about any non-static data members of reference or const scalar
3920 // type, since they will never get initializers.
3921 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003922 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3923 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003924 bool Complained = false;
3925 for (RecordDecl::field_iterator F = Record->field_begin(),
3926 FEnd = Record->field_end();
3927 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003928 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003929 continue;
3930
Douglas Gregor325e5932010-04-15 00:00:53 +00003931 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003932 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003933 if (!Complained) {
3934 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3935 << Record->getTagKind() << Record;
3936 Complained = true;
3937 }
3938
3939 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3940 << F->getType()->isReferenceType()
3941 << F->getDeclName();
3942 }
3943 }
3944 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003945
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003946 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003947 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003948
3949 if (Record->getIdentifier()) {
3950 // C++ [class.mem]p13:
3951 // If T is the name of a class, then each of the following shall have a
3952 // name different from T:
3953 // - every member of every anonymous union that is a member of class T.
3954 //
3955 // C++ [class.mem]p14:
3956 // In addition, if class T has a user-declared constructor (12.1), every
3957 // non-static data member of class T shall have a name different from T.
3958 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003959 R.first != R.second; ++R.first) {
3960 NamedDecl *D = *R.first;
3961 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3962 isa<IndirectFieldDecl>(D)) {
3963 Diag(D->getLocation(), diag::err_member_name_of_class)
3964 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003965 break;
3966 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003967 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003968 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003969
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003970 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003971 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003972 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003973 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003974 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3975 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3976 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003977
David Blaikieb6b5b972012-09-21 03:21:07 +00003978 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
3979 Diag(Record->getLocation(), diag::warn_abstract_final_class);
3980 DiagnoseAbstractType(Record);
3981 }
3982
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003983 // See if a method overloads virtual methods in a base
3984 /// class without overriding any.
3985 if (!Record->isDependentType()) {
3986 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3987 MEnd = Record->method_end();
3988 M != MEnd; ++M) {
David Blaikie262bc182012-04-30 02:36:29 +00003989 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003990 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003991 }
3992 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003993
3994 // Declare inherited constructors. We do this eagerly here because:
3995 // - The standard requires an eager diagnostic for conflicting inherited
3996 // constructors from different classes.
3997 // - The lazy declaration of the other implicit constructors is so as to not
3998 // waste space and performance on classes that are not meant to be
3999 // instantiated (e.g. meta-functions). This doesn't apply to classes that
4000 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004001 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004002}
4003
Richard Smithac713512012-12-08 02:53:02 +00004004void Sema::CheckExplicitlyDefaultedAndDeletedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004005 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
4006 ME = Record->method_end();
Richard Smithac713512012-12-08 02:53:02 +00004007 MI != ME; ++MI) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004008 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
David Blaikie581deb32012-06-06 20:45:41 +00004009 CheckExplicitlyDefaultedSpecialMember(*MI);
Richard Smithac713512012-12-08 02:53:02 +00004010
4011 if (!MI->isImplicit() && !MI->isUserProvided()) {
4012 // For an explicitly defaulted or deleted special member, we defer
4013 // determining triviality until the class is complete. That time is now!
4014 CXXSpecialMember CSM = getSpecialMember(*MI);
4015 if (CSM != CXXInvalid) {
4016 MI->setTrivial(SpecialMemberIsTrivial(*MI, CSM));
4017
4018 // Inform the class that we've finished declaring this member.
4019 Record->finishedDefaultedOrDeletedMember(*MI);
4020 }
4021 }
4022 }
Sean Hunt001cad92011-05-10 00:49:42 +00004023}
4024
Richard Smith7756afa2012-06-10 05:43:50 +00004025/// Is the special member function which would be selected to perform the
4026/// specified operation on the specified class type a constexpr constructor?
4027static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4028 Sema::CXXSpecialMember CSM,
4029 bool ConstArg) {
4030 Sema::SpecialMemberOverloadResult *SMOR =
4031 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4032 false, false, false, false);
4033 if (!SMOR || !SMOR->getMethod())
4034 // A constructor we wouldn't select can't be "involved in initializing"
4035 // anything.
4036 return true;
4037 return SMOR->getMethod()->isConstexpr();
4038}
4039
4040/// Determine whether the specified special member function would be constexpr
4041/// if it were implicitly defined.
4042static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4043 Sema::CXXSpecialMember CSM,
4044 bool ConstArg) {
4045 if (!S.getLangOpts().CPlusPlus0x)
4046 return false;
4047
4048 // C++11 [dcl.constexpr]p4:
4049 // In the definition of a constexpr constructor [...]
4050 switch (CSM) {
4051 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004052 // Since default constructor lookup is essentially trivial (and cannot
4053 // involve, for instance, template instantiation), we compute whether a
4054 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4055 //
4056 // This is important for performance; we need to know whether the default
4057 // constructor is constexpr to determine whether the type is a literal type.
4058 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4059
Richard Smith7756afa2012-06-10 05:43:50 +00004060 case Sema::CXXCopyConstructor:
4061 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004062 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004063 break;
4064
4065 case Sema::CXXCopyAssignment:
4066 case Sema::CXXMoveAssignment:
4067 case Sema::CXXDestructor:
4068 case Sema::CXXInvalid:
4069 return false;
4070 }
4071
4072 // -- if the class is a non-empty union, or for each non-empty anonymous
4073 // union member of a non-union class, exactly one non-static data member
4074 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004075 //
4076 // If we squint, this is guaranteed, since exactly one non-static data member
4077 // will be initialized (if the constructor isn't deleted), we just don't know
4078 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004079 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004080 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004081
4082 // -- the class shall not have any virtual base classes;
4083 if (ClassDecl->getNumVBases())
4084 return false;
4085
4086 // -- every constructor involved in initializing [...] base class
4087 // sub-objects shall be a constexpr constructor;
4088 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4089 BEnd = ClassDecl->bases_end();
4090 B != BEnd; ++B) {
4091 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4092 if (!BaseType) continue;
4093
4094 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4095 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4096 return false;
4097 }
4098
4099 // -- every constructor involved in initializing non-static data members
4100 // [...] shall be a constexpr constructor;
4101 // -- every non-static data member and base class sub-object shall be
4102 // initialized
4103 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4104 FEnd = ClassDecl->field_end();
4105 F != FEnd; ++F) {
4106 if (F->isInvalidDecl())
4107 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004108 if (const RecordType *RecordTy =
4109 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004110 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4111 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4112 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004113 }
4114 }
4115
4116 // All OK, it's constexpr!
4117 return true;
4118}
4119
Richard Smithb9d0b762012-07-27 04:22:15 +00004120static Sema::ImplicitExceptionSpecification
4121computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4122 switch (S.getSpecialMember(MD)) {
4123 case Sema::CXXDefaultConstructor:
4124 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4125 case Sema::CXXCopyConstructor:
4126 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4127 case Sema::CXXCopyAssignment:
4128 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4129 case Sema::CXXMoveConstructor:
4130 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4131 case Sema::CXXMoveAssignment:
4132 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4133 case Sema::CXXDestructor:
4134 return S.ComputeDefaultedDtorExceptionSpec(MD);
4135 case Sema::CXXInvalid:
4136 break;
4137 }
4138 llvm_unreachable("only special members have implicit exception specs");
4139}
4140
Richard Smithdd25e802012-07-30 23:48:14 +00004141static void
4142updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4143 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4144 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4145 ExceptSpec.getEPI(EPI);
4146 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4147 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4148 FPT->getNumArgs(), EPI));
4149 FD->setType(QualType(NewFPT, 0));
4150}
4151
Richard Smithb9d0b762012-07-27 04:22:15 +00004152void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4153 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4154 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4155 return;
4156
Richard Smithdd25e802012-07-30 23:48:14 +00004157 // Evaluate the exception specification.
4158 ImplicitExceptionSpecification ExceptSpec =
4159 computeImplicitExceptionSpec(*this, Loc, MD);
4160
4161 // Update the type of the special member to use it.
4162 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4163
4164 // A user-provided destructor can be defined outside the class. When that
4165 // happens, be sure to update the exception specification on both
4166 // declarations.
4167 const FunctionProtoType *CanonicalFPT =
4168 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4169 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4170 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4171 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004172}
4173
Richard Smith3003e1d2012-05-15 04:39:51 +00004174void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4175 CXXRecordDecl *RD = MD->getParent();
4176 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004177
Richard Smith3003e1d2012-05-15 04:39:51 +00004178 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4179 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004180
4181 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004182 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004183 bool First = MD == MD->getCanonicalDecl();
4184
4185 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004186
4187 // C++11 [dcl.fct.def.default]p1:
4188 // A function that is explicitly defaulted shall
4189 // -- be a special member function (checked elsewhere),
4190 // -- have the same type (except for ref-qualifiers, and except that a
4191 // copy operation can take a non-const reference) as an implicit
4192 // declaration, and
4193 // -- not have default arguments.
4194 unsigned ExpectedParams = 1;
4195 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4196 ExpectedParams = 0;
4197 if (MD->getNumParams() != ExpectedParams) {
4198 // This also checks for default arguments: a copy or move constructor with a
4199 // default argument is classified as a default constructor, and assignment
4200 // operations and destructors can't have default arguments.
4201 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4202 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004203 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004204 } else if (MD->isVariadic()) {
4205 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4206 << CSM << MD->getSourceRange();
4207 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004208 }
4209
Richard Smith3003e1d2012-05-15 04:39:51 +00004210 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004211
Richard Smith7756afa2012-06-10 05:43:50 +00004212 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004213 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004214 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004215 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004216 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004217
Richard Smith3003e1d2012-05-15 04:39:51 +00004218 QualType ReturnType = Context.VoidTy;
4219 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4220 // Check for return type matching.
4221 ReturnType = Type->getResultType();
4222 QualType ExpectedReturnType =
4223 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4224 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4225 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4226 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4227 HadError = true;
4228 }
4229
4230 // A defaulted special member cannot have cv-qualifiers.
4231 if (Type->getTypeQuals()) {
4232 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4233 << (CSM == CXXMoveAssignment);
4234 HadError = true;
4235 }
4236 }
4237
4238 // Check for parameter type matching.
4239 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004240 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004241 if (ExpectedParams && ArgType->isReferenceType()) {
4242 // Argument must be reference to possibly-const T.
4243 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004244 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004245
4246 if (ReferentType.isVolatileQualified()) {
4247 Diag(MD->getLocation(),
4248 diag::err_defaulted_special_member_volatile_param) << CSM;
4249 HadError = true;
4250 }
4251
Richard Smith7756afa2012-06-10 05:43:50 +00004252 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004253 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4254 Diag(MD->getLocation(),
4255 diag::err_defaulted_special_member_copy_const_param)
4256 << (CSM == CXXCopyAssignment);
4257 // FIXME: Explain why this special member can't be const.
4258 } else {
4259 Diag(MD->getLocation(),
4260 diag::err_defaulted_special_member_move_const_param)
4261 << (CSM == CXXMoveAssignment);
4262 }
4263 HadError = true;
4264 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004265 } else if (ExpectedParams) {
4266 // A copy assignment operator can take its argument by value, but a
4267 // defaulted one cannot.
4268 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004269 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004270 HadError = true;
4271 }
Sean Huntbe631222011-05-17 20:44:43 +00004272
Richard Smithb9d0b762012-07-27 04:22:15 +00004273 // Rebuild the type with the implicit exception specification added, if we
4274 // are going to need it.
4275 const FunctionProtoType *ImplicitType = 0;
4276 if (First || Type->hasExceptionSpec()) {
4277 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4278 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4279 ImplicitType = cast<FunctionProtoType>(
4280 Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
4281 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004282
Richard Smith61802452011-12-22 02:22:31 +00004283 // C++11 [dcl.fct.def.default]p2:
4284 // An explicitly-defaulted function may be declared constexpr only if it
4285 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004286 // Do not apply this rule to members of class templates, since core issue 1358
4287 // makes such functions always instantiate to constexpr functions. For
4288 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004289 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4290 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004291 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4292 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4293 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004294 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004295 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004296 }
4297 // and may have an explicit exception-specification only if it is compatible
4298 // with the exception-specification on the implicit declaration.
Richard Smith3003e1d2012-05-15 04:39:51 +00004299 if (Type->hasExceptionSpec() &&
4300 CheckEquivalentExceptionSpec(
4301 PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
4302 PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
4303 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004304
4305 // If a function is explicitly defaulted on its first declaration,
4306 if (First) {
4307 // -- it is implicitly considered to be constexpr if the implicit
4308 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004309 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004310
Richard Smith3003e1d2012-05-15 04:39:51 +00004311 // -- it is implicitly considered to have the same exception-specification
4312 // as if it had been implicitly declared,
4313 MD->setType(QualType(ImplicitType, 0));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004314 }
4315
Richard Smith3003e1d2012-05-15 04:39:51 +00004316 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004317 if (First) {
4318 MD->setDeletedAsWritten();
4319 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004320 // C++11 [dcl.fct.def.default]p4:
4321 // [For a] user-provided explicitly-defaulted function [...] if such a
4322 // function is implicitly defined as deleted, the program is ill-formed.
4323 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4324 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004325 }
4326 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004327
Richard Smith3003e1d2012-05-15 04:39:51 +00004328 if (HadError)
4329 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004330}
4331
Richard Smith7d5088a2012-02-18 02:02:13 +00004332namespace {
4333struct SpecialMemberDeletionInfo {
4334 Sema &S;
4335 CXXMethodDecl *MD;
4336 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004337 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004338
4339 // Properties of the special member, computed for convenience.
4340 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4341 SourceLocation Loc;
4342
4343 bool AllFieldsAreConst;
4344
4345 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004346 Sema::CXXSpecialMember CSM, bool Diagnose)
4347 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004348 IsConstructor(false), IsAssignment(false), IsMove(false),
4349 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4350 AllFieldsAreConst(true) {
4351 switch (CSM) {
4352 case Sema::CXXDefaultConstructor:
4353 case Sema::CXXCopyConstructor:
4354 IsConstructor = true;
4355 break;
4356 case Sema::CXXMoveConstructor:
4357 IsConstructor = true;
4358 IsMove = true;
4359 break;
4360 case Sema::CXXCopyAssignment:
4361 IsAssignment = true;
4362 break;
4363 case Sema::CXXMoveAssignment:
4364 IsAssignment = true;
4365 IsMove = true;
4366 break;
4367 case Sema::CXXDestructor:
4368 break;
4369 case Sema::CXXInvalid:
4370 llvm_unreachable("invalid special member kind");
4371 }
4372
4373 if (MD->getNumParams()) {
4374 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4375 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4376 }
4377 }
4378
4379 bool inUnion() const { return MD->getParent()->isUnion(); }
4380
4381 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004382 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4383 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004384 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004385 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4386 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4387 Quals = 0;
4388 return S.LookupSpecialMember(Class, CSM,
4389 ConstArg || (Quals & Qualifiers::Const),
4390 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004391 MD->getRefQualifier() == RQ_RValue,
4392 TQ & Qualifiers::Const,
4393 TQ & Qualifiers::Volatile);
4394 }
4395
Richard Smith6c4c36c2012-03-30 20:53:28 +00004396 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004397
Richard Smith6c4c36c2012-03-30 20:53:28 +00004398 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004399 bool shouldDeleteForField(FieldDecl *FD);
4400 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004401
Richard Smith517bb842012-07-18 03:51:16 +00004402 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4403 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004404 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4405 Sema::SpecialMemberOverloadResult *SMOR,
4406 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004407
4408 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004409};
4410}
4411
John McCall12d8d802012-04-09 20:53:23 +00004412/// Is the given special member inaccessible when used on the given
4413/// sub-object.
4414bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4415 CXXMethodDecl *target) {
4416 /// If we're operating on a base class, the object type is the
4417 /// type of this special member.
4418 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004419 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004420 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4421 objectTy = S.Context.getTypeDeclType(MD->getParent());
4422 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4423
4424 // If we're operating on a field, the object type is the type of the field.
4425 } else {
4426 objectTy = S.Context.getTypeDeclType(target->getParent());
4427 }
4428
4429 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4430}
4431
Richard Smith6c4c36c2012-03-30 20:53:28 +00004432/// Check whether we should delete a special member due to the implicit
4433/// definition containing a call to a special member of a subobject.
4434bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4435 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4436 bool IsDtorCallInCtor) {
4437 CXXMethodDecl *Decl = SMOR->getMethod();
4438 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4439
4440 int DiagKind = -1;
4441
4442 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4443 DiagKind = !Decl ? 0 : 1;
4444 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4445 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004446 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004447 DiagKind = 3;
4448 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4449 !Decl->isTrivial()) {
4450 // A member of a union must have a trivial corresponding special member.
4451 // As a weird special case, a destructor call from a union's constructor
4452 // must be accessible and non-deleted, but need not be trivial. Such a
4453 // destructor is never actually called, but is semantically checked as
4454 // if it were.
4455 DiagKind = 4;
4456 }
4457
4458 if (DiagKind == -1)
4459 return false;
4460
4461 if (Diagnose) {
4462 if (Field) {
4463 S.Diag(Field->getLocation(),
4464 diag::note_deleted_special_member_class_subobject)
4465 << CSM << MD->getParent() << /*IsField*/true
4466 << Field << DiagKind << IsDtorCallInCtor;
4467 } else {
4468 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4469 S.Diag(Base->getLocStart(),
4470 diag::note_deleted_special_member_class_subobject)
4471 << CSM << MD->getParent() << /*IsField*/false
4472 << Base->getType() << DiagKind << IsDtorCallInCtor;
4473 }
4474
4475 if (DiagKind == 1)
4476 S.NoteDeletedFunction(Decl);
4477 // FIXME: Explain inaccessibility if DiagKind == 3.
4478 }
4479
4480 return true;
4481}
4482
Richard Smith9a561d52012-02-26 09:11:52 +00004483/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004484/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004485bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004486 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004487 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004488
4489 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004490 // -- any direct or virtual base class, or non-static data member with no
4491 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004492 // either M has no default constructor or overload resolution as applied
4493 // to M's default constructor results in an ambiguity or in a function
4494 // that is deleted or inaccessible
4495 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4496 // -- a direct or virtual base class B that cannot be copied/moved because
4497 // overload resolution, as applied to B's corresponding special member,
4498 // results in an ambiguity or a function that is deleted or inaccessible
4499 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004500 // C++11 [class.dtor]p5:
4501 // -- any direct or virtual base class [...] has a type with a destructor
4502 // that is deleted or inaccessible
4503 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004504 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004505 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004506 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004507
Richard Smith6c4c36c2012-03-30 20:53:28 +00004508 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4509 // -- any direct or virtual base class or non-static data member has a
4510 // type with a destructor that is deleted or inaccessible
4511 if (IsConstructor) {
4512 Sema::SpecialMemberOverloadResult *SMOR =
4513 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4514 false, false, false, false, false);
4515 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4516 return true;
4517 }
4518
Richard Smith9a561d52012-02-26 09:11:52 +00004519 return false;
4520}
4521
4522/// Check whether we should delete a special member function due to the class
4523/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004524bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004525 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004526 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004527}
4528
4529/// Check whether we should delete a special member function due to the class
4530/// having a particular non-static data member.
4531bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4532 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4533 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4534
4535 if (CSM == Sema::CXXDefaultConstructor) {
4536 // For a default constructor, all references must be initialized in-class
4537 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004538 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4539 if (Diagnose)
4540 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4541 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004542 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004543 }
Richard Smith79363f52012-02-27 06:07:25 +00004544 // C++11 [class.ctor]p5: any non-variant non-static data member of
4545 // const-qualified type (or array thereof) with no
4546 // brace-or-equal-initializer does not have a user-provided default
4547 // constructor.
4548 if (!inUnion() && FieldType.isConstQualified() &&
4549 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004550 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4551 if (Diagnose)
4552 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004553 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004554 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004555 }
4556
4557 if (inUnion() && !FieldType.isConstQualified())
4558 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004559 } else if (CSM == Sema::CXXCopyConstructor) {
4560 // For a copy constructor, data members must not be of rvalue reference
4561 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004562 if (FieldType->isRValueReferenceType()) {
4563 if (Diagnose)
4564 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4565 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004566 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004567 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004568 } else if (IsAssignment) {
4569 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004570 if (FieldType->isReferenceType()) {
4571 if (Diagnose)
4572 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4573 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004574 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004575 }
4576 if (!FieldRecord && FieldType.isConstQualified()) {
4577 // C++11 [class.copy]p23:
4578 // -- a non-static data member of const non-class type (or array thereof)
4579 if (Diagnose)
4580 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004581 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004582 return true;
4583 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004584 }
4585
4586 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004587 // Some additional restrictions exist on the variant members.
4588 if (!inUnion() && FieldRecord->isUnion() &&
4589 FieldRecord->isAnonymousStructOrUnion()) {
4590 bool AllVariantFieldsAreConst = true;
4591
Richard Smithdf8dc862012-03-29 19:00:10 +00004592 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004593 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4594 UE = FieldRecord->field_end();
4595 UI != UE; ++UI) {
4596 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004597
4598 if (!UnionFieldType.isConstQualified())
4599 AllVariantFieldsAreConst = false;
4600
Richard Smith9a561d52012-02-26 09:11:52 +00004601 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4602 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004603 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4604 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004605 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004606 }
4607
4608 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004609 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004610 FieldRecord->field_begin() != FieldRecord->field_end()) {
4611 if (Diagnose)
4612 S.Diag(FieldRecord->getLocation(),
4613 diag::note_deleted_default_ctor_all_const)
4614 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004615 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004616 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004617
Richard Smithdf8dc862012-03-29 19:00:10 +00004618 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004619 // This is technically non-conformant, but sanity demands it.
4620 return false;
4621 }
4622
Richard Smith517bb842012-07-18 03:51:16 +00004623 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4624 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004625 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004626 }
4627
4628 return false;
4629}
4630
4631/// C++11 [class.ctor] p5:
4632/// A defaulted default constructor for a class X is defined as deleted if
4633/// X is a union and all of its variant members are of const-qualified type.
4634bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004635 // This is a silly definition, because it gives an empty union a deleted
4636 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004637 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4638 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4639 if (Diagnose)
4640 S.Diag(MD->getParent()->getLocation(),
4641 diag::note_deleted_default_ctor_all_const)
4642 << MD->getParent() << /*not anonymous union*/0;
4643 return true;
4644 }
4645 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004646}
4647
4648/// Determine whether a defaulted special member function should be defined as
4649/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4650/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004651bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4652 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004653 if (MD->isInvalidDecl())
4654 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004655 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004656 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004657 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004658 return false;
4659
Richard Smith7d5088a2012-02-18 02:02:13 +00004660 // C++11 [expr.lambda.prim]p19:
4661 // The closure type associated with a lambda-expression has a
4662 // deleted (8.4.3) default constructor and a deleted copy
4663 // assignment operator.
4664 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004665 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4666 if (Diagnose)
4667 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004668 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004669 }
4670
Richard Smith5bdaac52012-04-02 20:59:25 +00004671 // For an anonymous struct or union, the copy and assignment special members
4672 // will never be used, so skip the check. For an anonymous union declared at
4673 // namespace scope, the constructor and destructor are used.
4674 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4675 RD->isAnonymousStructOrUnion())
4676 return false;
4677
Richard Smith6c4c36c2012-03-30 20:53:28 +00004678 // C++11 [class.copy]p7, p18:
4679 // If the class definition declares a move constructor or move assignment
4680 // operator, an implicitly declared copy constructor or copy assignment
4681 // operator is defined as deleted.
4682 if (MD->isImplicit() &&
4683 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4684 CXXMethodDecl *UserDeclaredMove = 0;
4685
4686 // In Microsoft mode, a user-declared move only causes the deletion of the
4687 // corresponding copy operation, not both copy operations.
4688 if (RD->hasUserDeclaredMoveConstructor() &&
4689 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4690 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004691
4692 // Find any user-declared move constructor.
4693 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4694 E = RD->ctor_end(); I != E; ++I) {
4695 if (I->isMoveConstructor()) {
4696 UserDeclaredMove = *I;
4697 break;
4698 }
4699 }
Richard Smith1c931be2012-04-02 18:40:40 +00004700 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004701 } else if (RD->hasUserDeclaredMoveAssignment() &&
4702 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4703 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004704
4705 // Find any user-declared move assignment operator.
4706 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4707 E = RD->method_end(); I != E; ++I) {
4708 if (I->isMoveAssignmentOperator()) {
4709 UserDeclaredMove = *I;
4710 break;
4711 }
4712 }
Richard Smith1c931be2012-04-02 18:40:40 +00004713 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004714 }
4715
4716 if (UserDeclaredMove) {
4717 Diag(UserDeclaredMove->getLocation(),
4718 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004719 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004720 << UserDeclaredMove->isMoveAssignmentOperator();
4721 return true;
4722 }
4723 }
Sean Hunte16da072011-10-10 06:18:57 +00004724
Richard Smith5bdaac52012-04-02 20:59:25 +00004725 // Do access control from the special member function
4726 ContextRAII MethodContext(*this, MD);
4727
Richard Smith9a561d52012-02-26 09:11:52 +00004728 // C++11 [class.dtor]p5:
4729 // -- for a virtual destructor, lookup of the non-array deallocation function
4730 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004731 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004732 FunctionDecl *OperatorDelete = 0;
4733 DeclarationName Name =
4734 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4735 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004736 OperatorDelete, false)) {
4737 if (Diagnose)
4738 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004739 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004740 }
Richard Smith9a561d52012-02-26 09:11:52 +00004741 }
4742
Richard Smith6c4c36c2012-03-30 20:53:28 +00004743 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004744
Sean Huntcdee3fe2011-05-11 22:34:38 +00004745 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004746 BE = RD->bases_end(); BI != BE; ++BI)
4747 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004748 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004749 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004750
4751 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004752 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004753 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004754 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004755
4756 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004757 FE = RD->field_end(); FI != FE; ++FI)
4758 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004759 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004760 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004761
Richard Smith7d5088a2012-02-18 02:02:13 +00004762 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004763 return true;
4764
4765 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004766}
4767
Richard Smithac713512012-12-08 02:53:02 +00004768/// Perform lookup for a special member of the specified kind, and determine
4769/// whether it is trivial. If the triviality can be determined without the
4770/// lookup, skip it. This is intended for use when determining whether a
4771/// special member of a containing object is trivial, and thus does not ever
4772/// perform overload resolution for default constructors.
4773///
4774/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4775/// member that was most likely to be intended to be trivial, if any.
4776static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4777 Sema::CXXSpecialMember CSM, unsigned Quals,
4778 CXXMethodDecl **Selected) {
4779 if (Selected)
4780 *Selected = 0;
4781
4782 switch (CSM) {
4783 case Sema::CXXInvalid:
4784 llvm_unreachable("not a special member");
4785
4786 case Sema::CXXDefaultConstructor:
4787 // C++11 [class.ctor]p5:
4788 // A default constructor is trivial if:
4789 // - all the [direct subobjects] have trivial default constructors
4790 //
4791 // Note, no overload resolution is performed in this case.
4792 if (RD->hasTrivialDefaultConstructor())
4793 return true;
4794
4795 if (Selected) {
4796 // If there's a default constructor which could have been trivial, dig it
4797 // out. Otherwise, if there's any user-provided default constructor, point
4798 // to that as an example of why there's not a trivial one.
4799 CXXConstructorDecl *DefCtor = 0;
4800 if (RD->needsImplicitDefaultConstructor())
4801 S.DeclareImplicitDefaultConstructor(RD);
4802 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4803 CE = RD->ctor_end(); CI != CE; ++CI) {
4804 if (!CI->isDefaultConstructor())
4805 continue;
4806 DefCtor = *CI;
4807 if (!DefCtor->isUserProvided())
4808 break;
4809 }
4810
4811 *Selected = DefCtor;
4812 }
4813
4814 return false;
4815
4816 case Sema::CXXDestructor:
4817 // C++11 [class.dtor]p5:
4818 // A destructor is trivial if:
4819 // - all the direct [subobjects] have trivial destructors
4820 if (RD->hasTrivialDestructor())
4821 return true;
4822
4823 if (Selected) {
4824 if (RD->needsImplicitDestructor())
4825 S.DeclareImplicitDestructor(RD);
4826 *Selected = RD->getDestructor();
4827 }
4828
4829 return false;
4830
4831 case Sema::CXXCopyConstructor:
4832 // C++11 [class.copy]p12:
4833 // A copy constructor is trivial if:
4834 // - the constructor selected to copy each direct [subobject] is trivial
4835 if (RD->hasTrivialCopyConstructor()) {
4836 if (Quals == Qualifiers::Const)
4837 // We must either select the trivial copy constructor or reach an
4838 // ambiguity; no need to actually perform overload resolution.
4839 return true;
4840 } else if (!Selected) {
4841 return false;
4842 }
4843 // In C++98, we are not supposed to perform overload resolution here, but we
4844 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4845 // cases like B as having a non-trivial copy constructor:
4846 // struct A { template<typename T> A(T&); };
4847 // struct B { mutable A a; };
4848 goto NeedOverloadResolution;
4849
4850 case Sema::CXXCopyAssignment:
4851 // C++11 [class.copy]p25:
4852 // A copy assignment operator is trivial if:
4853 // - the assignment operator selected to copy each direct [subobject] is
4854 // trivial
4855 if (RD->hasTrivialCopyAssignment()) {
4856 if (Quals == Qualifiers::Const)
4857 return true;
4858 } else if (!Selected) {
4859 return false;
4860 }
4861 // In C++98, we are not supposed to perform overload resolution here, but we
4862 // treat that as a language defect.
4863 goto NeedOverloadResolution;
4864
4865 case Sema::CXXMoveConstructor:
4866 case Sema::CXXMoveAssignment:
4867 NeedOverloadResolution:
4868 Sema::SpecialMemberOverloadResult *SMOR =
4869 S.LookupSpecialMember(RD, CSM,
4870 Quals & Qualifiers::Const,
4871 Quals & Qualifiers::Volatile,
4872 /*RValueThis*/false, /*ConstThis*/false,
4873 /*VolatileThis*/false);
4874
4875 // The standard doesn't describe how to behave if the lookup is ambiguous.
4876 // We treat it as not making the member non-trivial, just like the standard
4877 // mandates for the default constructor. This should rarely matter, because
4878 // the member will also be deleted.
4879 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4880 return true;
4881
4882 if (!SMOR->getMethod()) {
4883 assert(SMOR->getKind() ==
4884 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
4885 return false;
4886 }
4887
4888 // We deliberately don't check if we found a deleted special member. We're
4889 // not supposed to!
4890 if (Selected)
4891 *Selected = SMOR->getMethod();
4892 return SMOR->getMethod()->isTrivial();
4893 }
4894
4895 llvm_unreachable("unknown special method kind");
4896}
4897
4898CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
4899 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
4900 CI != CE; ++CI)
4901 if (!CI->isImplicit())
4902 return *CI;
4903
4904 // Look for constructor templates.
4905 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
4906 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
4907 if (CXXConstructorDecl *CD =
4908 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
4909 return CD;
4910 }
4911
4912 return 0;
4913}
4914
4915/// The kind of subobject we are checking for triviality. The values of this
4916/// enumeration are used in diagnostics.
4917enum TrivialSubobjectKind {
4918 /// The subobject is a base class.
4919 TSK_BaseClass,
4920 /// The subobject is a non-static data member.
4921 TSK_Field,
4922 /// The object is actually the complete object.
4923 TSK_CompleteObject
4924};
4925
4926/// Check whether the special member selected for a given type would be trivial.
4927static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
4928 QualType SubType,
4929 Sema::CXXSpecialMember CSM,
4930 TrivialSubobjectKind Kind,
4931 bool Diagnose) {
4932 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
4933 if (!SubRD)
4934 return true;
4935
4936 CXXMethodDecl *Selected;
4937 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
4938 Diagnose ? &Selected : 0))
4939 return true;
4940
4941 if (Diagnose) {
4942 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
4943 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
4944 << Kind << SubType.getUnqualifiedType();
4945 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
4946 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
4947 } else if (!Selected)
4948 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
4949 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
4950 else if (Selected->isUserProvided()) {
4951 if (Kind == TSK_CompleteObject)
4952 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
4953 << Kind << SubType.getUnqualifiedType() << CSM;
4954 else {
4955 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
4956 << Kind << SubType.getUnqualifiedType() << CSM;
4957 S.Diag(Selected->getLocation(), diag::note_declared_at);
4958 }
4959 } else {
4960 if (Kind != TSK_CompleteObject)
4961 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
4962 << Kind << SubType.getUnqualifiedType() << CSM;
4963
4964 // Explain why the defaulted or deleted special member isn't trivial.
4965 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
4966 }
4967 }
4968
4969 return false;
4970}
4971
4972/// Check whether the members of a class type allow a special member to be
4973/// trivial.
4974static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
4975 Sema::CXXSpecialMember CSM,
4976 bool ConstArg, bool Diagnose) {
4977 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4978 FE = RD->field_end(); FI != FE; ++FI) {
4979 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
4980 continue;
4981
4982 QualType FieldType = S.Context.getBaseElementType(FI->getType());
4983
4984 // Pretend anonymous struct or union members are members of this class.
4985 if (FI->isAnonymousStructOrUnion()) {
4986 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
4987 CSM, ConstArg, Diagnose))
4988 return false;
4989 continue;
4990 }
4991
4992 // C++11 [class.ctor]p5:
4993 // A default constructor is trivial if [...]
4994 // -- no non-static data member of its class has a
4995 // brace-or-equal-initializer
4996 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
4997 if (Diagnose)
4998 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
4999 return false;
5000 }
5001
5002 // Objective C ARC 4.3.5:
5003 // [...] nontrivally ownership-qualified types are [...] not trivially
5004 // default constructible, copy constructible, move constructible, copy
5005 // assignable, move assignable, or destructible [...]
5006 if (S.getLangOpts().ObjCAutoRefCount &&
5007 FieldType.hasNonTrivialObjCLifetime()) {
5008 if (Diagnose)
5009 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5010 << RD << FieldType.getObjCLifetime();
5011 return false;
5012 }
5013
5014 if (ConstArg && !FI->isMutable())
5015 FieldType.addConst();
5016 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5017 TSK_Field, Diagnose))
5018 return false;
5019 }
5020
5021 return true;
5022}
5023
5024/// Diagnose why the specified class does not have a trivial special member of
5025/// the given kind.
5026void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5027 QualType Ty = Context.getRecordType(RD);
5028 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5029 Ty.addConst();
5030
5031 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5032 TSK_CompleteObject, /*Diagnose*/true);
5033}
5034
5035/// Determine whether a defaulted or deleted special member function is trivial,
5036/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5037/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5038bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5039 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005040 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5041
5042 CXXRecordDecl *RD = MD->getParent();
5043
5044 bool ConstArg = false;
5045 ParmVarDecl *Param0 = MD->getNumParams() ? MD->getParamDecl(0) : 0;
5046
5047 // C++11 [class.copy]p12, p25:
5048 // A [special member] is trivial if its declared parameter type is the same
5049 // as if it had been implicitly declared [...]
5050 switch (CSM) {
5051 case CXXDefaultConstructor:
5052 case CXXDestructor:
5053 // Trivial default constructors and destructors cannot have parameters.
5054 break;
5055
5056 case CXXCopyConstructor:
5057 case CXXCopyAssignment: {
5058 // Trivial copy operations always have const, non-volatile parameter types.
5059 ConstArg = true;
5060 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5061 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5062 if (Diagnose)
5063 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5064 << Param0->getSourceRange() << Param0->getType()
5065 << Context.getLValueReferenceType(
5066 Context.getRecordType(RD).withConst());
5067 return false;
5068 }
5069 break;
5070 }
5071
5072 case CXXMoveConstructor:
5073 case CXXMoveAssignment: {
5074 // Trivial move operations always have non-cv-qualified parameters.
5075 const RValueReferenceType *RT =
5076 Param0->getType()->getAs<RValueReferenceType>();
5077 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5078 if (Diagnose)
5079 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5080 << Param0->getSourceRange() << Param0->getType()
5081 << Context.getRValueReferenceType(Context.getRecordType(RD));
5082 return false;
5083 }
5084 break;
5085 }
5086
5087 case CXXInvalid:
5088 llvm_unreachable("not a special member");
5089 }
5090
5091 // FIXME: We require that the parameter-declaration-clause is equivalent to
5092 // that of an implicit declaration, not just that the declared parameter type
5093 // matches, in order to prevent absuridities like a function simultaneously
5094 // being a trivial copy constructor and a non-trivial default constructor.
5095 // This issue has not yet been assigned a core issue number.
5096 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5097 if (Diagnose)
5098 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5099 diag::note_nontrivial_default_arg)
5100 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5101 return false;
5102 }
5103 if (MD->isVariadic()) {
5104 if (Diagnose)
5105 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5106 return false;
5107 }
5108
5109 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5110 // A copy/move [constructor or assignment operator] is trivial if
5111 // -- the [member] selected to copy/move each direct base class subobject
5112 // is trivial
5113 //
5114 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5115 // A [default constructor or destructor] is trivial if
5116 // -- all the direct base classes have trivial [default constructors or
5117 // destructors]
5118 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5119 BE = RD->bases_end(); BI != BE; ++BI)
5120 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5121 ConstArg ? BI->getType().withConst()
5122 : BI->getType(),
5123 CSM, TSK_BaseClass, Diagnose))
5124 return false;
5125
5126 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5127 // A copy/move [constructor or assignment operator] for a class X is
5128 // trivial if
5129 // -- for each non-static data member of X that is of class type (or array
5130 // thereof), the constructor selected to copy/move that member is
5131 // trivial
5132 //
5133 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5134 // A [default constructor or destructor] is trivial if
5135 // -- for all of the non-static data members of its class that are of class
5136 // type (or array thereof), each such class has a trivial [default
5137 // constructor or destructor]
5138 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5139 return false;
5140
5141 // C++11 [class.dtor]p5:
5142 // A destructor is trivial if [...]
5143 // -- the destructor is not virtual
5144 if (CSM == CXXDestructor && MD->isVirtual()) {
5145 if (Diagnose)
5146 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5147 return false;
5148 }
5149
5150 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5151 // A [special member] for class X is trivial if [...]
5152 // -- class X has no virtual functions and no virtual base classes
5153 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5154 if (!Diagnose)
5155 return false;
5156
5157 if (RD->getNumVBases()) {
5158 // Check for virtual bases. We already know that the corresponding
5159 // member in all bases is trivial, so vbases must all be direct.
5160 CXXBaseSpecifier &BS = *RD->vbases_begin();
5161 assert(BS.isVirtual());
5162 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5163 return false;
5164 }
5165
5166 // Must have a virtual method.
5167 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5168 ME = RD->method_end(); MI != ME; ++MI) {
5169 if (MI->isVirtual()) {
5170 SourceLocation MLoc = MI->getLocStart();
5171 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5172 return false;
5173 }
5174 }
5175
5176 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5177 }
5178
5179 // Looks like it's trivial!
5180 return true;
5181}
5182
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005183/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005184namespace {
5185 struct FindHiddenVirtualMethodData {
5186 Sema *S;
5187 CXXMethodDecl *Method;
5188 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005189 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005190 };
5191}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005192
David Blaikie5f750682012-10-19 00:53:08 +00005193/// \brief Check whether any most overriden method from MD in Methods
5194static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5195 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5196 if (MD->size_overridden_methods() == 0)
5197 return Methods.count(MD->getCanonicalDecl());
5198 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5199 E = MD->end_overridden_methods();
5200 I != E; ++I)
5201 if (CheckMostOverridenMethods(*I, Methods))
5202 return true;
5203 return false;
5204}
5205
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005206/// \brief Member lookup function that determines whether a given C++
5207/// method overloads virtual methods in a base class without overriding any,
5208/// to be used with CXXRecordDecl::lookupInBases().
5209static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5210 CXXBasePath &Path,
5211 void *UserData) {
5212 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5213
5214 FindHiddenVirtualMethodData &Data
5215 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5216
5217 DeclarationName Name = Data.Method->getDeclName();
5218 assert(Name.getNameKind() == DeclarationName::Identifier);
5219
5220 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005221 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005222 for (Path.Decls = BaseRecord->lookup(Name);
5223 Path.Decls.first != Path.Decls.second;
5224 ++Path.Decls.first) {
5225 NamedDecl *D = *Path.Decls.first;
5226 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005227 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005228 foundSameNameMethod = true;
5229 // Interested only in hidden virtual methods.
5230 if (!MD->isVirtual())
5231 continue;
5232 // If the method we are checking overrides a method from its base
5233 // don't warn about the other overloaded methods.
5234 if (!Data.S->IsOverload(Data.Method, MD, false))
5235 return true;
5236 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005237 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005238 overloadedMethods.push_back(MD);
5239 }
5240 }
5241
5242 if (foundSameNameMethod)
5243 Data.OverloadedMethods.append(overloadedMethods.begin(),
5244 overloadedMethods.end());
5245 return foundSameNameMethod;
5246}
5247
David Blaikie5f750682012-10-19 00:53:08 +00005248/// \brief Add the most overriden methods from MD to Methods
5249static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5250 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5251 if (MD->size_overridden_methods() == 0)
5252 Methods.insert(MD->getCanonicalDecl());
5253 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5254 E = MD->end_overridden_methods();
5255 I != E; ++I)
5256 AddMostOverridenMethods(*I, Methods);
5257}
5258
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005259/// \brief See if a method overloads virtual methods in a base class without
5260/// overriding any.
5261void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5262 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005263 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005264 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005265 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005266 return;
5267
5268 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5269 /*bool RecordPaths=*/false,
5270 /*bool DetectVirtual=*/false);
5271 FindHiddenVirtualMethodData Data;
5272 Data.Method = MD;
5273 Data.S = this;
5274
5275 // Keep the base methods that were overriden or introduced in the subclass
5276 // by 'using' in a set. A base method not in this set is hidden.
5277 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
5278 res.first != res.second; ++res.first) {
David Blaikie5f750682012-10-19 00:53:08 +00005279 NamedDecl *ND = *res.first;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005280 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
David Blaikie5f750682012-10-19 00:53:08 +00005281 ND = shad->getTargetDecl();
5282 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5283 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005284 }
5285
5286 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5287 !Data.OverloadedMethods.empty()) {
5288 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5289 << MD << (Data.OverloadedMethods.size() > 1);
5290
5291 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5292 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5293 Diag(overloadedMD->getLocation(),
5294 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5295 }
5296 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005297}
5298
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005299void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005300 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005301 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005302 SourceLocation RBrac,
5303 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005304 if (!TagDecl)
5305 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005306
Douglas Gregor42af25f2009-05-11 19:58:34 +00005307 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005308
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005309 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5310 if (l->getKind() != AttributeList::AT_Visibility)
5311 continue;
5312 l->setInvalid();
5313 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5314 l->getName();
5315 }
5316
David Blaikie77b6de02011-09-22 02:58:26 +00005317 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005318 // strict aliasing violation!
5319 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005320 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005321
Douglas Gregor23c94db2010-07-02 17:43:08 +00005322 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005323 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005324}
5325
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005326/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5327/// special functions, such as the default constructor, copy
5328/// constructor, or destructor, to the given C++ class (C++
5329/// [special]p1). This routine can only be executed just before the
5330/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005331void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005332 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005333 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005334
Richard Smithbc2a35d2012-12-08 08:32:28 +00005335 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005336 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005337
Richard Smithbc2a35d2012-12-08 08:32:28 +00005338 // If the properties or semantics of the copy constructor couldn't be
5339 // determined while the class was being declared, force a declaration
5340 // of it now.
5341 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5342 DeclareImplicitCopyConstructor(ClassDecl);
5343 }
5344
5345 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005346 ++ASTContext::NumImplicitMoveConstructors;
5347
Richard Smithbc2a35d2012-12-08 08:32:28 +00005348 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5349 DeclareImplicitMoveConstructor(ClassDecl);
5350 }
5351
Douglas Gregora376d102010-07-02 21:50:04 +00005352 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5353 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005354
5355 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005356 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005357 // it shows up in the right place in the vtable and that we diagnose
5358 // problems with the implicit exception specification.
5359 if (ClassDecl->isDynamicClass() ||
5360 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005361 DeclareImplicitCopyAssignment(ClassDecl);
5362 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005363
Richard Smith1c931be2012-04-02 18:40:40 +00005364 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005365 ++ASTContext::NumImplicitMoveAssignmentOperators;
5366
5367 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005368 if (ClassDecl->isDynamicClass() ||
5369 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005370 DeclareImplicitMoveAssignment(ClassDecl);
5371 }
5372
Douglas Gregor4923aa22010-07-02 20:37:36 +00005373 if (!ClassDecl->hasUserDeclaredDestructor()) {
5374 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005375
5376 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005377 // have to declare the destructor immediately. This ensures that, e.g., it
5378 // shows up in the right place in the vtable and that we diagnose problems
5379 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005380 if (ClassDecl->isDynamicClass() ||
5381 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005382 DeclareImplicitDestructor(ClassDecl);
5383 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005384}
5385
Francois Pichet8387e2a2011-04-22 22:18:13 +00005386void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5387 if (!D)
5388 return;
5389
5390 int NumParamList = D->getNumTemplateParameterLists();
5391 for (int i = 0; i < NumParamList; i++) {
5392 TemplateParameterList* Params = D->getTemplateParameterList(i);
5393 for (TemplateParameterList::iterator Param = Params->begin(),
5394 ParamEnd = Params->end();
5395 Param != ParamEnd; ++Param) {
5396 NamedDecl *Named = cast<NamedDecl>(*Param);
5397 if (Named->getDeclName()) {
5398 S->AddDecl(Named);
5399 IdResolver.AddDecl(Named);
5400 }
5401 }
5402 }
5403}
5404
John McCalld226f652010-08-21 09:40:31 +00005405void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005406 if (!D)
5407 return;
5408
5409 TemplateParameterList *Params = 0;
5410 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5411 Params = Template->getTemplateParameters();
5412 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5413 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5414 Params = PartialSpec->getTemplateParameters();
5415 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005416 return;
5417
Douglas Gregor6569d682009-05-27 23:11:45 +00005418 for (TemplateParameterList::iterator Param = Params->begin(),
5419 ParamEnd = Params->end();
5420 Param != ParamEnd; ++Param) {
5421 NamedDecl *Named = cast<NamedDecl>(*Param);
5422 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005423 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005424 IdResolver.AddDecl(Named);
5425 }
5426 }
5427}
5428
John McCalld226f652010-08-21 09:40:31 +00005429void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005430 if (!RecordD) return;
5431 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005432 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005433 PushDeclContext(S, Record);
5434}
5435
John McCalld226f652010-08-21 09:40:31 +00005436void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005437 if (!RecordD) return;
5438 PopDeclContext();
5439}
5440
Douglas Gregor72b505b2008-12-16 21:30:33 +00005441/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5442/// parsing a top-level (non-nested) C++ class, and we are now
5443/// parsing those parts of the given Method declaration that could
5444/// not be parsed earlier (C++ [class.mem]p2), such as default
5445/// arguments. This action should enter the scope of the given
5446/// Method declaration as if we had just parsed the qualified method
5447/// name. However, it should not bring the parameters into scope;
5448/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005449void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005450}
5451
5452/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5453/// C++ method declaration. We're (re-)introducing the given
5454/// function parameter into scope for use in parsing later parts of
5455/// the method declaration. For example, we could see an
5456/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005457void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005458 if (!ParamD)
5459 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005460
John McCalld226f652010-08-21 09:40:31 +00005461 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005462
5463 // If this parameter has an unparsed default argument, clear it out
5464 // to make way for the parsed default argument.
5465 if (Param->hasUnparsedDefaultArg())
5466 Param->setDefaultArg(0);
5467
John McCalld226f652010-08-21 09:40:31 +00005468 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005469 if (Param->getDeclName())
5470 IdResolver.AddDecl(Param);
5471}
5472
5473/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5474/// processing the delayed method declaration for Method. The method
5475/// declaration is now considered finished. There may be a separate
5476/// ActOnStartOfFunctionDef action later (not necessarily
5477/// immediately!) for this method, if it was also defined inside the
5478/// class body.
John McCalld226f652010-08-21 09:40:31 +00005479void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005480 if (!MethodD)
5481 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005482
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005483 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005484
John McCalld226f652010-08-21 09:40:31 +00005485 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005486
5487 // Now that we have our default arguments, check the constructor
5488 // again. It could produce additional diagnostics or affect whether
5489 // the class has implicitly-declared destructors, among other
5490 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005491 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5492 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005493
5494 // Check the default arguments, which we may have added.
5495 if (!Method->isInvalidDecl())
5496 CheckCXXDefaultArguments(Method);
5497}
5498
Douglas Gregor42a552f2008-11-05 20:51:48 +00005499/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005500/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005501/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005502/// emit diagnostics and set the invalid bit to true. In any case, the type
5503/// will be updated to reflect a well-formed type for the constructor and
5504/// returned.
5505QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005506 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005507 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005508
5509 // C++ [class.ctor]p3:
5510 // A constructor shall not be virtual (10.3) or static (9.4). A
5511 // constructor can be invoked for a const, volatile or const
5512 // volatile object. A constructor shall not be declared const,
5513 // volatile, or const volatile (9.3.2).
5514 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005515 if (!D.isInvalidType())
5516 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5517 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5518 << SourceRange(D.getIdentifierLoc());
5519 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005520 }
John McCalld931b082010-08-26 03:08:43 +00005521 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005522 if (!D.isInvalidType())
5523 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5524 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5525 << SourceRange(D.getIdentifierLoc());
5526 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005527 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005528 }
Mike Stump1eb44332009-09-09 15:08:12 +00005529
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005530 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005531 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005532 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005533 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5534 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005535 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005536 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5537 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005538 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005539 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5540 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005541 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005542 }
Mike Stump1eb44332009-09-09 15:08:12 +00005543
Douglas Gregorc938c162011-01-26 05:01:58 +00005544 // C++0x [class.ctor]p4:
5545 // A constructor shall not be declared with a ref-qualifier.
5546 if (FTI.hasRefQualifier()) {
5547 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5548 << FTI.RefQualifierIsLValueRef
5549 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5550 D.setInvalidType();
5551 }
5552
Douglas Gregor42a552f2008-11-05 20:51:48 +00005553 // Rebuild the function type "R" without any type qualifiers (in
5554 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005555 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005556 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005557 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5558 return R;
5559
5560 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5561 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005562 EPI.RefQualifier = RQ_None;
5563
Chris Lattner65401802009-04-25 08:28:21 +00005564 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005565 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005566}
5567
Douglas Gregor72b505b2008-12-16 21:30:33 +00005568/// CheckConstructor - Checks a fully-formed constructor for
5569/// well-formedness, issuing any diagnostics required. Returns true if
5570/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005571void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005572 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005573 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5574 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005575 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005576
5577 // C++ [class.copy]p3:
5578 // A declaration of a constructor for a class X is ill-formed if
5579 // its first parameter is of type (optionally cv-qualified) X and
5580 // either there are no other parameters or else all other
5581 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005582 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005583 ((Constructor->getNumParams() == 1) ||
5584 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005585 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5586 Constructor->getTemplateSpecializationKind()
5587 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005588 QualType ParamType = Constructor->getParamDecl(0)->getType();
5589 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5590 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005591 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005592 const char *ConstRef
5593 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5594 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005595 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005596 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005597
5598 // FIXME: Rather that making the constructor invalid, we should endeavor
5599 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005600 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005601 }
5602 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005603}
5604
John McCall15442822010-08-04 01:04:25 +00005605/// CheckDestructor - Checks a fully-formed destructor definition for
5606/// well-formedness, issuing any diagnostics required. Returns true
5607/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005608bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005609 CXXRecordDecl *RD = Destructor->getParent();
5610
5611 if (Destructor->isVirtual()) {
5612 SourceLocation Loc;
5613
5614 if (!Destructor->isImplicit())
5615 Loc = Destructor->getLocation();
5616 else
5617 Loc = RD->getLocation();
5618
5619 // If we have a virtual destructor, look up the deallocation function
5620 FunctionDecl *OperatorDelete = 0;
5621 DeclarationName Name =
5622 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005623 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005624 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005625
Eli Friedman5f2987c2012-02-02 03:46:19 +00005626 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005627
5628 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005629 }
Anders Carlsson37909802009-11-30 21:24:50 +00005630
5631 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005632}
5633
Mike Stump1eb44332009-09-09 15:08:12 +00005634static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005635FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5636 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5637 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005638 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005639}
5640
Douglas Gregor42a552f2008-11-05 20:51:48 +00005641/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5642/// the well-formednes of the destructor declarator @p D with type @p
5643/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005644/// emit diagnostics and set the declarator to invalid. Even if this happens,
5645/// will be updated to reflect a well-formed type for the destructor and
5646/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005647QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005648 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005649 // C++ [class.dtor]p1:
5650 // [...] A typedef-name that names a class is a class-name
5651 // (7.1.3); however, a typedef-name that names a class shall not
5652 // be used as the identifier in the declarator for a destructor
5653 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005654 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005655 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005656 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005657 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005658 else if (const TemplateSpecializationType *TST =
5659 DeclaratorType->getAs<TemplateSpecializationType>())
5660 if (TST->isTypeAlias())
5661 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5662 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005663
5664 // C++ [class.dtor]p2:
5665 // A destructor is used to destroy objects of its class type. A
5666 // destructor takes no parameters, and no return type can be
5667 // specified for it (not even void). The address of a destructor
5668 // shall not be taken. A destructor shall not be static. A
5669 // destructor can be invoked for a const, volatile or const
5670 // volatile object. A destructor shall not be declared const,
5671 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005672 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005673 if (!D.isInvalidType())
5674 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5675 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005676 << SourceRange(D.getIdentifierLoc())
5677 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5678
John McCalld931b082010-08-26 03:08:43 +00005679 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005680 }
Chris Lattner65401802009-04-25 08:28:21 +00005681 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005682 // Destructors don't have return types, but the parser will
5683 // happily parse something like:
5684 //
5685 // class X {
5686 // float ~X();
5687 // };
5688 //
5689 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005690 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5691 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5692 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005693 }
Mike Stump1eb44332009-09-09 15:08:12 +00005694
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005695 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005696 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005697 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005698 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5699 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005700 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005701 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5702 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005703 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005704 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5705 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005706 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005707 }
5708
Douglas Gregorc938c162011-01-26 05:01:58 +00005709 // C++0x [class.dtor]p2:
5710 // A destructor shall not be declared with a ref-qualifier.
5711 if (FTI.hasRefQualifier()) {
5712 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5713 << FTI.RefQualifierIsLValueRef
5714 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5715 D.setInvalidType();
5716 }
5717
Douglas Gregor42a552f2008-11-05 20:51:48 +00005718 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005719 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005720 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5721
5722 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005723 FTI.freeArgs();
5724 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005725 }
5726
Mike Stump1eb44332009-09-09 15:08:12 +00005727 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005728 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005729 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005730 D.setInvalidType();
5731 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005732
5733 // Rebuild the function type "R" without any type qualifiers or
5734 // parameters (in case any of the errors above fired) and with
5735 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005736 // types.
John McCalle23cf432010-12-14 08:05:40 +00005737 if (!D.isInvalidType())
5738 return R;
5739
Douglas Gregord92ec472010-07-01 05:10:53 +00005740 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005741 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5742 EPI.Variadic = false;
5743 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005744 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005745 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005746}
5747
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005748/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5749/// well-formednes of the conversion function declarator @p D with
5750/// type @p R. If there are any errors in the declarator, this routine
5751/// will emit diagnostics and return true. Otherwise, it will return
5752/// false. Either way, the type @p R will be updated to reflect a
5753/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005754void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005755 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005756 // C++ [class.conv.fct]p1:
5757 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005758 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005759 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005760 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005761 if (!D.isInvalidType())
5762 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5763 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5764 << SourceRange(D.getIdentifierLoc());
5765 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005766 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005767 }
John McCalla3f81372010-04-13 00:04:31 +00005768
5769 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5770
Chris Lattner6e475012009-04-25 08:35:12 +00005771 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005772 // Conversion functions don't have return types, but the parser will
5773 // happily parse something like:
5774 //
5775 // class X {
5776 // float operator bool();
5777 // };
5778 //
5779 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005780 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5781 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5782 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005783 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005784 }
5785
John McCalla3f81372010-04-13 00:04:31 +00005786 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5787
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005788 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005789 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005790 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5791
5792 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005793 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005794 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005795 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005796 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005797 D.setInvalidType();
5798 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005799
John McCalla3f81372010-04-13 00:04:31 +00005800 // Diagnose "&operator bool()" and other such nonsense. This
5801 // is actually a gcc extension which we don't support.
5802 if (Proto->getResultType() != ConvType) {
5803 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5804 << Proto->getResultType();
5805 D.setInvalidType();
5806 ConvType = Proto->getResultType();
5807 }
5808
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005809 // C++ [class.conv.fct]p4:
5810 // The conversion-type-id shall not represent a function type nor
5811 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005812 if (ConvType->isArrayType()) {
5813 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5814 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005815 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005816 } else if (ConvType->isFunctionType()) {
5817 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5818 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005819 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005820 }
5821
5822 // Rebuild the function type "R" without any parameters (in case any
5823 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005824 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005825 if (D.isInvalidType())
5826 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005827
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005828 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005829 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005830 Diag(D.getDeclSpec().getExplicitSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005831 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005832 diag::warn_cxx98_compat_explicit_conversion_functions :
5833 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005834 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005835}
5836
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005837/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5838/// the declaration of the given C++ conversion function. This routine
5839/// is responsible for recording the conversion function in the C++
5840/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005841Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005842 assert(Conversion && "Expected to receive a conversion function declaration");
5843
Douglas Gregor9d350972008-12-12 08:25:50 +00005844 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005845
5846 // Make sure we aren't redeclaring the conversion function.
5847 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005848
5849 // C++ [class.conv.fct]p1:
5850 // [...] A conversion function is never used to convert a
5851 // (possibly cv-qualified) object to the (possibly cv-qualified)
5852 // same object type (or a reference to it), to a (possibly
5853 // cv-qualified) base class of that type (or a reference to it),
5854 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005855 // FIXME: Suppress this warning if the conversion function ends up being a
5856 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005857 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005858 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005859 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005860 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005861 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5862 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005863 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005864 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005865 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5866 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005867 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005868 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005869 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005870 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005871 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005872 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005873 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005874 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005875 }
5876
Douglas Gregore80622f2010-09-29 04:25:11 +00005877 if (FunctionTemplateDecl *ConversionTemplate
5878 = Conversion->getDescribedFunctionTemplate())
5879 return ConversionTemplate;
5880
John McCalld226f652010-08-21 09:40:31 +00005881 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005882}
5883
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005884//===----------------------------------------------------------------------===//
5885// Namespace Handling
5886//===----------------------------------------------------------------------===//
5887
Richard Smithd1a55a62012-10-04 22:13:39 +00005888/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
5889/// reopened.
5890static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
5891 SourceLocation Loc,
5892 IdentifierInfo *II, bool *IsInline,
5893 NamespaceDecl *PrevNS) {
5894 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00005895
Richard Smithc969e6a2012-10-05 01:46:25 +00005896 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
5897 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
5898 // inline namespaces, with the intention of bringing names into namespace std.
5899 //
5900 // We support this just well enough to get that case working; this is not
5901 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00005902 if (*IsInline && II && II->getName().startswith("__atomic") &&
5903 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00005904 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00005905 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
5906 NS = NS->getPreviousDecl())
5907 NS->setInline(*IsInline);
5908 // Patch up the lookup table for the containing namespace. This isn't really
5909 // correct, but it's good enough for this particular case.
5910 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
5911 E = PrevNS->decls_end(); I != E; ++I)
5912 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
5913 PrevNS->getParent()->makeDeclVisibleInContext(ND);
5914 return;
5915 }
5916
5917 if (PrevNS->isInline())
5918 // The user probably just forgot the 'inline', so suggest that it
5919 // be added back.
5920 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5921 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
5922 else
5923 S.Diag(Loc, diag::err_inline_namespace_mismatch)
5924 << IsInline;
5925
5926 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
5927 *IsInline = PrevNS->isInline();
5928}
John McCallea318642010-08-26 09:15:37 +00005929
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005930/// ActOnStartNamespaceDef - This is called at the start of a namespace
5931/// definition.
John McCalld226f652010-08-21 09:40:31 +00005932Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005933 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005934 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005935 SourceLocation IdentLoc,
5936 IdentifierInfo *II,
5937 SourceLocation LBrace,
5938 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005939 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5940 // For anonymous namespace, take the location of the left brace.
5941 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005942 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005943 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005944 bool IsStd = false;
5945 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005946 Scope *DeclRegionScope = NamespcScope->getParent();
5947
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005948 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005949 if (II) {
5950 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005951 // The identifier in an original-namespace-definition shall not
5952 // have been previously defined in the declarative region in
5953 // which the original-namespace-definition appears. The
5954 // identifier in an original-namespace-definition is the name of
5955 // the namespace. Subsequently in that declarative region, it is
5956 // treated as an original-namespace-name.
5957 //
5958 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005959 // look through using directives, just look for any ordinary names.
5960
5961 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005962 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5963 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005964 NamedDecl *PrevDecl = 0;
5965 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005966 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005967 R.first != R.second; ++R.first) {
5968 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5969 PrevDecl = *R.first;
5970 break;
5971 }
5972 }
5973
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005974 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5975
5976 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005977 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00005978 if (IsInline != PrevNS->isInline())
5979 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
5980 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00005981 } else if (PrevDecl) {
5982 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005983 Diag(Loc, diag::err_redefinition_different_kind)
5984 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005985 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005986 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005987 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005988 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005989 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005990 // This is the first "real" definition of the namespace "std", so update
5991 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005992 PrevNS = getStdNamespace();
5993 IsStd = true;
5994 AddToKnown = !IsInline;
5995 } else {
5996 // We've seen this namespace for the first time.
5997 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005998 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005999 } else {
John McCall9aeed322009-10-01 00:25:31 +00006000 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006001
6002 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006003 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006004 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006005 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006006 } else {
6007 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006008 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006009 }
6010
Richard Smithd1a55a62012-10-04 22:13:39 +00006011 if (PrevNS && IsInline != PrevNS->isInline())
6012 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6013 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006014 }
6015
6016 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6017 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006018 if (IsInvalid)
6019 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006020
6021 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006022
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006023 // FIXME: Should we be merging attributes?
6024 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006025 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006026
6027 if (IsStd)
6028 StdNamespace = Namespc;
6029 if (AddToKnown)
6030 KnownNamespaces[Namespc] = false;
6031
6032 if (II) {
6033 PushOnScopeChains(Namespc, DeclRegionScope);
6034 } else {
6035 // Link the anonymous namespace into its parent.
6036 DeclContext *Parent = CurContext->getRedeclContext();
6037 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6038 TU->setAnonymousNamespace(Namespc);
6039 } else {
6040 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006041 }
John McCall9aeed322009-10-01 00:25:31 +00006042
Douglas Gregora4181472010-03-24 00:46:35 +00006043 CurContext->addDecl(Namespc);
6044
John McCall9aeed322009-10-01 00:25:31 +00006045 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6046 // behaves as if it were replaced by
6047 // namespace unique { /* empty body */ }
6048 // using namespace unique;
6049 // namespace unique { namespace-body }
6050 // where all occurrences of 'unique' in a translation unit are
6051 // replaced by the same identifier and this identifier differs
6052 // from all other identifiers in the entire program.
6053
6054 // We just create the namespace with an empty name and then add an
6055 // implicit using declaration, just like the standard suggests.
6056 //
6057 // CodeGen enforces the "universally unique" aspect by giving all
6058 // declarations semantically contained within an anonymous
6059 // namespace internal linkage.
6060
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006061 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006062 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006063 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006064 /* 'using' */ LBrace,
6065 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006066 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006067 /* identifier */ SourceLocation(),
6068 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006069 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006070 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006071 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006072 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006073 }
6074
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006075 ActOnDocumentableDecl(Namespc);
6076
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006077 // Although we could have an invalid decl (i.e. the namespace name is a
6078 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006079 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6080 // for the namespace has the declarations that showed up in that particular
6081 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006082 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006083 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006084}
6085
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006086/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6087/// is a namespace alias, returns the namespace it points to.
6088static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6089 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6090 return AD->getNamespace();
6091 return dyn_cast_or_null<NamespaceDecl>(D);
6092}
6093
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006094/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6095/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006096void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006097 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6098 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006099 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006100 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006101 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006102 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006103}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006104
John McCall384aff82010-08-25 07:42:41 +00006105CXXRecordDecl *Sema::getStdBadAlloc() const {
6106 return cast_or_null<CXXRecordDecl>(
6107 StdBadAlloc.get(Context.getExternalSource()));
6108}
6109
6110NamespaceDecl *Sema::getStdNamespace() const {
6111 return cast_or_null<NamespaceDecl>(
6112 StdNamespace.get(Context.getExternalSource()));
6113}
6114
Douglas Gregor66992202010-06-29 17:53:46 +00006115/// \brief Retrieve the special "std" namespace, which may require us to
6116/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006117NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006118 if (!StdNamespace) {
6119 // The "std" namespace has not yet been defined, so build one implicitly.
6120 StdNamespace = NamespaceDecl::Create(Context,
6121 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006122 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006123 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006124 &PP.getIdentifierTable().get("std"),
6125 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006126 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006127 }
6128
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006129 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006130}
6131
Sebastian Redl395e04d2012-01-17 22:49:33 +00006132bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006133 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006134 "Looking for std::initializer_list outside of C++.");
6135
6136 // We're looking for implicit instantiations of
6137 // template <typename E> class std::initializer_list.
6138
6139 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6140 return false;
6141
Sebastian Redl84760e32012-01-17 22:49:58 +00006142 ClassTemplateDecl *Template = 0;
6143 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006144
Sebastian Redl84760e32012-01-17 22:49:58 +00006145 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006146
Sebastian Redl84760e32012-01-17 22:49:58 +00006147 ClassTemplateSpecializationDecl *Specialization =
6148 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6149 if (!Specialization)
6150 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006151
Sebastian Redl84760e32012-01-17 22:49:58 +00006152 Template = Specialization->getSpecializedTemplate();
6153 Arguments = Specialization->getTemplateArgs().data();
6154 } else if (const TemplateSpecializationType *TST =
6155 Ty->getAs<TemplateSpecializationType>()) {
6156 Template = dyn_cast_or_null<ClassTemplateDecl>(
6157 TST->getTemplateName().getAsTemplateDecl());
6158 Arguments = TST->getArgs();
6159 }
6160 if (!Template)
6161 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006162
6163 if (!StdInitializerList) {
6164 // Haven't recognized std::initializer_list yet, maybe this is it.
6165 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6166 if (TemplateClass->getIdentifier() !=
6167 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006168 !getStdNamespace()->InEnclosingNamespaceSetOf(
6169 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006170 return false;
6171 // This is a template called std::initializer_list, but is it the right
6172 // template?
6173 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006174 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006175 return false;
6176 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6177 return false;
6178
6179 // It's the right template.
6180 StdInitializerList = Template;
6181 }
6182
6183 if (Template != StdInitializerList)
6184 return false;
6185
6186 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006187 if (Element)
6188 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006189 return true;
6190}
6191
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006192static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6193 NamespaceDecl *Std = S.getStdNamespace();
6194 if (!Std) {
6195 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6196 return 0;
6197 }
6198
6199 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6200 Loc, Sema::LookupOrdinaryName);
6201 if (!S.LookupQualifiedName(Result, Std)) {
6202 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6203 return 0;
6204 }
6205 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6206 if (!Template) {
6207 Result.suppressDiagnostics();
6208 // We found something weird. Complain about the first thing we found.
6209 NamedDecl *Found = *Result.begin();
6210 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6211 return 0;
6212 }
6213
6214 // We found some template called std::initializer_list. Now verify that it's
6215 // correct.
6216 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006217 if (Params->getMinRequiredArguments() != 1 ||
6218 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006219 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6220 return 0;
6221 }
6222
6223 return Template;
6224}
6225
6226QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6227 if (!StdInitializerList) {
6228 StdInitializerList = LookupStdInitializerList(*this, Loc);
6229 if (!StdInitializerList)
6230 return QualType();
6231 }
6232
6233 TemplateArgumentListInfo Args(Loc, Loc);
6234 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6235 Context.getTrivialTypeSourceInfo(Element,
6236 Loc)));
6237 return Context.getCanonicalType(
6238 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6239}
6240
Sebastian Redl98d36062012-01-17 22:50:14 +00006241bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6242 // C++ [dcl.init.list]p2:
6243 // A constructor is an initializer-list constructor if its first parameter
6244 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6245 // std::initializer_list<E> for some type E, and either there are no other
6246 // parameters or else all other parameters have default arguments.
6247 if (Ctor->getNumParams() < 1 ||
6248 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6249 return false;
6250
6251 QualType ArgType = Ctor->getParamDecl(0)->getType();
6252 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6253 ArgType = RT->getPointeeType().getUnqualifiedType();
6254
6255 return isStdInitializerList(ArgType, 0);
6256}
6257
Douglas Gregor9172aa62011-03-26 22:25:30 +00006258/// \brief Determine whether a using statement is in a context where it will be
6259/// apply in all contexts.
6260static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6261 switch (CurContext->getDeclKind()) {
6262 case Decl::TranslationUnit:
6263 return true;
6264 case Decl::LinkageSpec:
6265 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6266 default:
6267 return false;
6268 }
6269}
6270
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006271namespace {
6272
6273// Callback to only accept typo corrections that are namespaces.
6274class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6275 public:
6276 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6277 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6278 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6279 }
6280 return false;
6281 }
6282};
6283
6284}
6285
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006286static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6287 CXXScopeSpec &SS,
6288 SourceLocation IdentLoc,
6289 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006290 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006291 R.clear();
6292 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006293 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006294 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006295 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6296 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006297 if (DeclContext *DC = S.computeDeclContext(SS, false))
6298 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6299 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006300 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6301 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006302 else
6303 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6304 << Ident << CorrectedQuotedStr
6305 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006306
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006307 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6308 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006309
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006310 R.addDecl(Corrected.getCorrectionDecl());
6311 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006312 }
6313 return false;
6314}
6315
John McCalld226f652010-08-21 09:40:31 +00006316Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006317 SourceLocation UsingLoc,
6318 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006319 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006320 SourceLocation IdentLoc,
6321 IdentifierInfo *NamespcName,
6322 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006323 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6324 assert(NamespcName && "Invalid NamespcName.");
6325 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006326
6327 // This can only happen along a recovery path.
6328 while (S->getFlags() & Scope::TemplateParamScope)
6329 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006330 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006331
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006332 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006333 NestedNameSpecifier *Qualifier = 0;
6334 if (SS.isSet())
6335 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6336
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006337 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006338 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6339 LookupParsedName(R, S, &SS);
6340 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006341 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006342
Douglas Gregor66992202010-06-29 17:53:46 +00006343 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006344 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006345 // Allow "using namespace std;" or "using namespace ::std;" even if
6346 // "std" hasn't been defined yet, for GCC compatibility.
6347 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6348 NamespcName->isStr("std")) {
6349 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006350 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006351 R.resolveKind();
6352 }
6353 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006354 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006355 }
6356
John McCallf36e02d2009-10-09 21:13:30 +00006357 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006358 NamedDecl *Named = R.getFoundDecl();
6359 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6360 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006361 // C++ [namespace.udir]p1:
6362 // A using-directive specifies that the names in the nominated
6363 // namespace can be used in the scope in which the
6364 // using-directive appears after the using-directive. During
6365 // unqualified name lookup (3.4.1), the names appear as if they
6366 // were declared in the nearest enclosing namespace which
6367 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006368 // namespace. [Note: in this context, "contains" means "contains
6369 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006370
6371 // Find enclosing context containing both using-directive and
6372 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006373 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006374 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6375 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6376 CommonAncestor = CommonAncestor->getParent();
6377
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006378 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006379 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006380 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006381
Douglas Gregor9172aa62011-03-26 22:25:30 +00006382 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006383 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006384 Diag(IdentLoc, diag::warn_using_directive_in_header);
6385 }
6386
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006387 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006388 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006389 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006390 }
6391
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006392 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006393 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006394}
6395
6396void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006397 // If the scope has an associated entity and the using directive is at
6398 // namespace or translation unit scope, add the UsingDirectiveDecl into
6399 // its lookup structure so qualified name lookup can find it.
6400 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6401 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006402 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006403 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006404 // Otherwise, it is at block sope. The using-directives will affect lookup
6405 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006406 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006407}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006408
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006409
John McCalld226f652010-08-21 09:40:31 +00006410Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006411 AccessSpecifier AS,
6412 bool HasUsingKeyword,
6413 SourceLocation UsingLoc,
6414 CXXScopeSpec &SS,
6415 UnqualifiedId &Name,
6416 AttributeList *AttrList,
6417 bool IsTypeName,
6418 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006419 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006420
Douglas Gregor12c118a2009-11-04 16:30:06 +00006421 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006422 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006423 case UnqualifiedId::IK_Identifier:
6424 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006425 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006426 case UnqualifiedId::IK_ConversionFunctionId:
6427 break;
6428
6429 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006430 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006431 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006432 Diag(Name.getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00006433 getLangOpts().CPlusPlus0x ?
Richard Smitha1366cb2012-04-27 19:33:05 +00006434 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
6435 // instead once inheriting constructors work.
6436 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00006437 diag::err_using_decl_constructor)
6438 << SS.getRange();
6439
David Blaikie4e4d0842012-03-11 07:00:24 +00006440 if (getLangOpts().CPlusPlus0x) break;
John McCall604e7f12009-12-08 07:46:18 +00006441
John McCalld226f652010-08-21 09:40:31 +00006442 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006443
6444 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006445 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006446 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006447 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006448
6449 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006450 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006451 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006452 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006453 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006454
6455 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6456 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006457 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006458 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006459
John McCall60fa3cf2009-12-11 02:10:03 +00006460 // Warn about using declarations.
6461 // TODO: store that the declaration was written without 'using' and
6462 // talk about access decls instead of using decls in the
6463 // diagnostics.
6464 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006465 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006466
6467 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006468 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006469 }
6470
Douglas Gregor56c04582010-12-16 00:46:58 +00006471 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6472 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6473 return 0;
6474
John McCall9488ea12009-11-17 05:59:44 +00006475 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006476 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006477 /* IsInstantiation */ false,
6478 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006479 if (UD)
6480 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006481
John McCalld226f652010-08-21 09:40:31 +00006482 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006483}
6484
Douglas Gregor09acc982010-07-07 23:08:52 +00006485/// \brief Determine whether a using declaration considers the given
6486/// declarations as "equivalent", e.g., if they are redeclarations of
6487/// the same entity or are both typedefs of the same type.
6488static bool
6489IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6490 bool &SuppressRedeclaration) {
6491 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6492 SuppressRedeclaration = false;
6493 return true;
6494 }
6495
Richard Smith162e1c12011-04-15 14:24:37 +00006496 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6497 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006498 SuppressRedeclaration = true;
6499 return Context.hasSameType(TD1->getUnderlyingType(),
6500 TD2->getUnderlyingType());
6501 }
6502
6503 return false;
6504}
6505
6506
John McCall9f54ad42009-12-10 09:41:52 +00006507/// Determines whether to create a using shadow decl for a particular
6508/// decl, given the set of decls existing prior to this using lookup.
6509bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6510 const LookupResult &Previous) {
6511 // Diagnose finding a decl which is not from a base class of the
6512 // current class. We do this now because there are cases where this
6513 // function will silently decide not to build a shadow decl, which
6514 // will pre-empt further diagnostics.
6515 //
6516 // We don't need to do this in C++0x because we do the check once on
6517 // the qualifier.
6518 //
6519 // FIXME: diagnose the following if we care enough:
6520 // struct A { int foo; };
6521 // struct B : A { using A::foo; };
6522 // template <class T> struct C : A {};
6523 // template <class T> struct D : C<T> { using B::foo; } // <---
6524 // This is invalid (during instantiation) in C++03 because B::foo
6525 // resolves to the using decl in B, which is not a base class of D<T>.
6526 // We can't diagnose it immediately because C<T> is an unknown
6527 // specialization. The UsingShadowDecl in D<T> then points directly
6528 // to A::foo, which will look well-formed when we instantiate.
6529 // The right solution is to not collapse the shadow-decl chain.
David Blaikie4e4d0842012-03-11 07:00:24 +00006530 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006531 DeclContext *OrigDC = Orig->getDeclContext();
6532
6533 // Handle enums and anonymous structs.
6534 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6535 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6536 while (OrigRec->isAnonymousStructOrUnion())
6537 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6538
6539 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6540 if (OrigDC == CurContext) {
6541 Diag(Using->getLocation(),
6542 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006543 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006544 Diag(Orig->getLocation(), diag::note_using_decl_target);
6545 return true;
6546 }
6547
Douglas Gregordc355712011-02-25 00:36:19 +00006548 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006549 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006550 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006551 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006552 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006553 Diag(Orig->getLocation(), diag::note_using_decl_target);
6554 return true;
6555 }
6556 }
6557
6558 if (Previous.empty()) return false;
6559
6560 NamedDecl *Target = Orig;
6561 if (isa<UsingShadowDecl>(Target))
6562 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6563
John McCalld7533ec2009-12-11 02:33:26 +00006564 // If the target happens to be one of the previous declarations, we
6565 // don't have a conflict.
6566 //
6567 // FIXME: but we might be increasing its access, in which case we
6568 // should redeclare it.
6569 NamedDecl *NonTag = 0, *Tag = 0;
6570 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6571 I != E; ++I) {
6572 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006573 bool Result;
6574 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6575 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006576
6577 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6578 }
6579
John McCall9f54ad42009-12-10 09:41:52 +00006580 if (Target->isFunctionOrFunctionTemplate()) {
6581 FunctionDecl *FD;
6582 if (isa<FunctionTemplateDecl>(Target))
6583 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6584 else
6585 FD = cast<FunctionDecl>(Target);
6586
6587 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006588 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006589 case Ovl_Overload:
6590 return false;
6591
6592 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006593 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006594 break;
6595
6596 // We found a decl with the exact signature.
6597 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006598 // If we're in a record, we want to hide the target, so we
6599 // return true (without a diagnostic) to tell the caller not to
6600 // build a shadow decl.
6601 if (CurContext->isRecord())
6602 return true;
6603
6604 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006605 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006606 break;
6607 }
6608
6609 Diag(Target->getLocation(), diag::note_using_decl_target);
6610 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6611 return true;
6612 }
6613
6614 // Target is not a function.
6615
John McCall9f54ad42009-12-10 09:41:52 +00006616 if (isa<TagDecl>(Target)) {
6617 // No conflict between a tag and a non-tag.
6618 if (!Tag) return false;
6619
John McCall41ce66f2009-12-10 19:51:03 +00006620 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006621 Diag(Target->getLocation(), diag::note_using_decl_target);
6622 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6623 return true;
6624 }
6625
6626 // No conflict between a tag and a non-tag.
6627 if (!NonTag) return false;
6628
John McCall41ce66f2009-12-10 19:51:03 +00006629 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006630 Diag(Target->getLocation(), diag::note_using_decl_target);
6631 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6632 return true;
6633}
6634
John McCall9488ea12009-11-17 05:59:44 +00006635/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006636UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006637 UsingDecl *UD,
6638 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006639
6640 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006641 NamedDecl *Target = Orig;
6642 if (isa<UsingShadowDecl>(Target)) {
6643 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6644 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006645 }
6646
6647 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006648 = UsingShadowDecl::Create(Context, CurContext,
6649 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006650 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006651
6652 Shadow->setAccess(UD->getAccess());
6653 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6654 Shadow->setInvalidDecl();
6655
John McCall9488ea12009-11-17 05:59:44 +00006656 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006657 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006658 else
John McCall604e7f12009-12-08 07:46:18 +00006659 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006660
John McCall604e7f12009-12-08 07:46:18 +00006661
John McCall9f54ad42009-12-10 09:41:52 +00006662 return Shadow;
6663}
John McCall604e7f12009-12-08 07:46:18 +00006664
John McCall9f54ad42009-12-10 09:41:52 +00006665/// Hides a using shadow declaration. This is required by the current
6666/// using-decl implementation when a resolvable using declaration in a
6667/// class is followed by a declaration which would hide or override
6668/// one or more of the using decl's targets; for example:
6669///
6670/// struct Base { void foo(int); };
6671/// struct Derived : Base {
6672/// using Base::foo;
6673/// void foo(int);
6674/// };
6675///
6676/// The governing language is C++03 [namespace.udecl]p12:
6677///
6678/// When a using-declaration brings names from a base class into a
6679/// derived class scope, member functions in the derived class
6680/// override and/or hide member functions with the same name and
6681/// parameter types in a base class (rather than conflicting).
6682///
6683/// There are two ways to implement this:
6684/// (1) optimistically create shadow decls when they're not hidden
6685/// by existing declarations, or
6686/// (2) don't create any shadow decls (or at least don't make them
6687/// visible) until we've fully parsed/instantiated the class.
6688/// The problem with (1) is that we might have to retroactively remove
6689/// a shadow decl, which requires several O(n) operations because the
6690/// decl structures are (very reasonably) not designed for removal.
6691/// (2) avoids this but is very fiddly and phase-dependent.
6692void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006693 if (Shadow->getDeclName().getNameKind() ==
6694 DeclarationName::CXXConversionFunctionName)
6695 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6696
John McCall9f54ad42009-12-10 09:41:52 +00006697 // Remove it from the DeclContext...
6698 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006699
John McCall9f54ad42009-12-10 09:41:52 +00006700 // ...and the scope, if applicable...
6701 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006702 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006703 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006704 }
6705
John McCall9f54ad42009-12-10 09:41:52 +00006706 // ...and the using decl.
6707 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6708
6709 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006710 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006711}
6712
John McCall7ba107a2009-11-18 02:36:19 +00006713/// Builds a using declaration.
6714///
6715/// \param IsInstantiation - Whether this call arises from an
6716/// instantiation of an unresolved using declaration. We treat
6717/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006718NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6719 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006720 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006721 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006722 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006723 bool IsInstantiation,
6724 bool IsTypeName,
6725 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006726 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006727 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006728 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006729
Anders Carlsson550b14b2009-08-28 05:49:21 +00006730 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006731
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006732 if (SS.isEmpty()) {
6733 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006734 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006735 }
Mike Stump1eb44332009-09-09 15:08:12 +00006736
John McCall9f54ad42009-12-10 09:41:52 +00006737 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006738 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006739 ForRedeclaration);
6740 Previous.setHideTags(false);
6741 if (S) {
6742 LookupName(Previous, S);
6743
6744 // It is really dumb that we have to do this.
6745 LookupResult::Filter F = Previous.makeFilter();
6746 while (F.hasNext()) {
6747 NamedDecl *D = F.next();
6748 if (!isDeclInScope(D, CurContext, S))
6749 F.erase();
6750 }
6751 F.done();
6752 } else {
6753 assert(IsInstantiation && "no scope in non-instantiation");
6754 assert(CurContext->isRecord() && "scope not record in instantiation");
6755 LookupQualifiedName(Previous, CurContext);
6756 }
6757
John McCall9f54ad42009-12-10 09:41:52 +00006758 // Check for invalid redeclarations.
6759 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6760 return 0;
6761
6762 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006763 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6764 return 0;
6765
John McCallaf8e6ed2009-11-12 03:15:40 +00006766 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006767 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006768 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006769 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006770 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006771 // FIXME: not all declaration name kinds are legal here
6772 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6773 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006774 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006775 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006776 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006777 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6778 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006779 }
John McCalled976492009-12-04 22:46:56 +00006780 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006781 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6782 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006783 }
John McCalled976492009-12-04 22:46:56 +00006784 D->setAccess(AS);
6785 CurContext->addDecl(D);
6786
6787 if (!LookupContext) return D;
6788 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006789
John McCall77bb1aa2010-05-01 00:40:08 +00006790 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006791 UD->setInvalidDecl();
6792 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006793 }
6794
Richard Smithc5a89a12012-04-02 01:30:27 +00006795 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006796 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006797 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006798 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006799 return UD;
6800 }
6801
6802 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006803
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006804 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006805
John McCall604e7f12009-12-08 07:46:18 +00006806 // Unlike most lookups, we don't always want to hide tag
6807 // declarations: tag names are visible through the using declaration
6808 // even if hidden by ordinary names, *except* in a dependent context
6809 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006810 if (!IsInstantiation)
6811 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006812
John McCallb9abd8722012-04-07 03:04:20 +00006813 // For the purposes of this lookup, we have a base object type
6814 // equal to that of the current context.
6815 if (CurContext->isRecord()) {
6816 R.setBaseObjectType(
6817 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6818 }
6819
John McCalla24dc2e2009-11-17 02:14:36 +00006820 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006821
John McCallf36e02d2009-10-09 21:13:30 +00006822 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006823 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006824 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006825 UD->setInvalidDecl();
6826 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006827 }
6828
John McCalled976492009-12-04 22:46:56 +00006829 if (R.isAmbiguous()) {
6830 UD->setInvalidDecl();
6831 return UD;
6832 }
Mike Stump1eb44332009-09-09 15:08:12 +00006833
John McCall7ba107a2009-11-18 02:36:19 +00006834 if (IsTypeName) {
6835 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006836 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006837 Diag(IdentLoc, diag::err_using_typename_non_type);
6838 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6839 Diag((*I)->getUnderlyingDecl()->getLocation(),
6840 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006841 UD->setInvalidDecl();
6842 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006843 }
6844 } else {
6845 // If we asked for a non-typename and we got a type, error out,
6846 // but only if this is an instantiation of an unresolved using
6847 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006848 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006849 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6850 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006851 UD->setInvalidDecl();
6852 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006853 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006854 }
6855
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006856 // C++0x N2914 [namespace.udecl]p6:
6857 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006858 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006859 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6860 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006861 UD->setInvalidDecl();
6862 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006863 }
Mike Stump1eb44332009-09-09 15:08:12 +00006864
John McCall9f54ad42009-12-10 09:41:52 +00006865 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6866 if (!CheckUsingShadowDecl(UD, *I, Previous))
6867 BuildUsingShadowDecl(S, UD, *I);
6868 }
John McCall9488ea12009-11-17 05:59:44 +00006869
6870 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006871}
6872
Sebastian Redlf677ea32011-02-05 19:23:19 +00006873/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006874bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6875 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006876
Douglas Gregordc355712011-02-25 00:36:19 +00006877 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006878 assert(SourceType &&
6879 "Using decl naming constructor doesn't have type in scope spec.");
6880 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6881
6882 // Check whether the named type is a direct base class.
6883 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6884 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6885 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6886 BaseIt != BaseE; ++BaseIt) {
6887 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6888 if (CanonicalSourceType == BaseType)
6889 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006890 if (BaseIt->getType()->isDependentType())
6891 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006892 }
6893
6894 if (BaseIt == BaseE) {
6895 // Did not find SourceType in the bases.
6896 Diag(UD->getUsingLocation(),
6897 diag::err_using_decl_constructor_not_in_direct_base)
6898 << UD->getNameInfo().getSourceRange()
6899 << QualType(SourceType, 0) << TargetClass;
6900 return true;
6901 }
6902
Richard Smithc5a89a12012-04-02 01:30:27 +00006903 if (!CurContext->isDependentContext())
6904 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006905
6906 return false;
6907}
6908
John McCall9f54ad42009-12-10 09:41:52 +00006909/// Checks that the given using declaration is not an invalid
6910/// redeclaration. Note that this is checking only for the using decl
6911/// itself, not for any ill-formedness among the UsingShadowDecls.
6912bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6913 bool isTypeName,
6914 const CXXScopeSpec &SS,
6915 SourceLocation NameLoc,
6916 const LookupResult &Prev) {
6917 // C++03 [namespace.udecl]p8:
6918 // C++0x [namespace.udecl]p10:
6919 // A using-declaration is a declaration and can therefore be used
6920 // repeatedly where (and only where) multiple declarations are
6921 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006922 //
John McCall8a726212010-11-29 18:01:58 +00006923 // That's in non-member contexts.
6924 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006925 return false;
6926
6927 NestedNameSpecifier *Qual
6928 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6929
6930 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6931 NamedDecl *D = *I;
6932
6933 bool DTypename;
6934 NestedNameSpecifier *DQual;
6935 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6936 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006937 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006938 } else if (UnresolvedUsingValueDecl *UD
6939 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6940 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006941 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006942 } else if (UnresolvedUsingTypenameDecl *UD
6943 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6944 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006945 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006946 } else continue;
6947
6948 // using decls differ if one says 'typename' and the other doesn't.
6949 // FIXME: non-dependent using decls?
6950 if (isTypeName != DTypename) continue;
6951
6952 // using decls differ if they name different scopes (but note that
6953 // template instantiation can cause this check to trigger when it
6954 // didn't before instantiation).
6955 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6956 Context.getCanonicalNestedNameSpecifier(DQual))
6957 continue;
6958
6959 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006960 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006961 return true;
6962 }
6963
6964 return false;
6965}
6966
John McCall604e7f12009-12-08 07:46:18 +00006967
John McCalled976492009-12-04 22:46:56 +00006968/// Checks that the given nested-name qualifier used in a using decl
6969/// in the current context is appropriately related to the current
6970/// scope. If an error is found, diagnoses it and returns true.
6971bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6972 const CXXScopeSpec &SS,
6973 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006974 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006975
John McCall604e7f12009-12-08 07:46:18 +00006976 if (!CurContext->isRecord()) {
6977 // C++03 [namespace.udecl]p3:
6978 // C++0x [namespace.udecl]p8:
6979 // A using-declaration for a class member shall be a member-declaration.
6980
6981 // If we weren't able to compute a valid scope, it must be a
6982 // dependent class scope.
6983 if (!NamedContext || NamedContext->isRecord()) {
6984 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6985 << SS.getRange();
6986 return true;
6987 }
6988
6989 // Otherwise, everything is known to be fine.
6990 return false;
6991 }
6992
6993 // The current scope is a record.
6994
6995 // If the named context is dependent, we can't decide much.
6996 if (!NamedContext) {
6997 // FIXME: in C++0x, we can diagnose if we can prove that the
6998 // nested-name-specifier does not refer to a base class, which is
6999 // still possible in some cases.
7000
7001 // Otherwise we have to conservatively report that things might be
7002 // okay.
7003 return false;
7004 }
7005
7006 if (!NamedContext->isRecord()) {
7007 // Ideally this would point at the last name in the specifier,
7008 // but we don't have that level of source info.
7009 Diag(SS.getRange().getBegin(),
7010 diag::err_using_decl_nested_name_specifier_is_not_class)
7011 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7012 return true;
7013 }
7014
Douglas Gregor6fb07292010-12-21 07:41:49 +00007015 if (!NamedContext->isDependentContext() &&
7016 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7017 return true;
7018
David Blaikie4e4d0842012-03-11 07:00:24 +00007019 if (getLangOpts().CPlusPlus0x) {
John McCall604e7f12009-12-08 07:46:18 +00007020 // C++0x [namespace.udecl]p3:
7021 // In a using-declaration used as a member-declaration, the
7022 // nested-name-specifier shall name a base class of the class
7023 // being defined.
7024
7025 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7026 cast<CXXRecordDecl>(NamedContext))) {
7027 if (CurContext == NamedContext) {
7028 Diag(NameLoc,
7029 diag::err_using_decl_nested_name_specifier_is_current_class)
7030 << SS.getRange();
7031 return true;
7032 }
7033
7034 Diag(SS.getRange().getBegin(),
7035 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7036 << (NestedNameSpecifier*) SS.getScopeRep()
7037 << cast<CXXRecordDecl>(CurContext)
7038 << SS.getRange();
7039 return true;
7040 }
7041
7042 return false;
7043 }
7044
7045 // C++03 [namespace.udecl]p4:
7046 // A using-declaration used as a member-declaration shall refer
7047 // to a member of a base class of the class being defined [etc.].
7048
7049 // Salient point: SS doesn't have to name a base class as long as
7050 // lookup only finds members from base classes. Therefore we can
7051 // diagnose here only if we can prove that that can't happen,
7052 // i.e. if the class hierarchies provably don't intersect.
7053
7054 // TODO: it would be nice if "definitely valid" results were cached
7055 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7056 // need to be repeated.
7057
7058 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007059 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007060
7061 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7062 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7063 Data->Bases.insert(Base);
7064 return true;
7065 }
7066
7067 bool hasDependentBases(const CXXRecordDecl *Class) {
7068 return !Class->forallBases(collect, this);
7069 }
7070
7071 /// Returns true if the base is dependent or is one of the
7072 /// accumulated base classes.
7073 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7074 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7075 return !Data->Bases.count(Base);
7076 }
7077
7078 bool mightShareBases(const CXXRecordDecl *Class) {
7079 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7080 }
7081 };
7082
7083 UserData Data;
7084
7085 // Returns false if we find a dependent base.
7086 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7087 return false;
7088
7089 // Returns false if the class has a dependent base or if it or one
7090 // of its bases is present in the base set of the current context.
7091 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7092 return false;
7093
7094 Diag(SS.getRange().getBegin(),
7095 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7096 << (NestedNameSpecifier*) SS.getScopeRep()
7097 << cast<CXXRecordDecl>(CurContext)
7098 << SS.getRange();
7099
7100 return true;
John McCalled976492009-12-04 22:46:56 +00007101}
7102
Richard Smith162e1c12011-04-15 14:24:37 +00007103Decl *Sema::ActOnAliasDeclaration(Scope *S,
7104 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007105 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007106 SourceLocation UsingLoc,
7107 UnqualifiedId &Name,
7108 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007109 // Skip up to the relevant declaration scope.
7110 while (S->getFlags() & Scope::TemplateParamScope)
7111 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007112 assert((S->getFlags() & Scope::DeclScope) &&
7113 "got alias-declaration outside of declaration scope");
7114
7115 if (Type.isInvalid())
7116 return 0;
7117
7118 bool Invalid = false;
7119 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7120 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007121 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007122
7123 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7124 return 0;
7125
7126 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007127 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007128 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007129 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7130 TInfo->getTypeLoc().getBeginLoc());
7131 }
Richard Smith162e1c12011-04-15 14:24:37 +00007132
7133 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7134 LookupName(Previous, S);
7135
7136 // Warn about shadowing the name of a template parameter.
7137 if (Previous.isSingleResult() &&
7138 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007139 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007140 Previous.clear();
7141 }
7142
7143 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7144 "name in alias declaration must be an identifier");
7145 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7146 Name.StartLocation,
7147 Name.Identifier, TInfo);
7148
7149 NewTD->setAccess(AS);
7150
7151 if (Invalid)
7152 NewTD->setInvalidDecl();
7153
Richard Smith3e4c6c42011-05-05 21:57:07 +00007154 CheckTypedefForVariablyModifiedType(S, NewTD);
7155 Invalid |= NewTD->isInvalidDecl();
7156
Richard Smith162e1c12011-04-15 14:24:37 +00007157 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007158
7159 NamedDecl *NewND;
7160 if (TemplateParamLists.size()) {
7161 TypeAliasTemplateDecl *OldDecl = 0;
7162 TemplateParameterList *OldTemplateParams = 0;
7163
7164 if (TemplateParamLists.size() != 1) {
7165 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007166 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7167 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007168 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007169 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007170
7171 // Only consider previous declarations in the same scope.
7172 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7173 /*ExplicitInstantiationOrSpecialization*/false);
7174 if (!Previous.empty()) {
7175 Redeclaration = true;
7176
7177 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7178 if (!OldDecl && !Invalid) {
7179 Diag(UsingLoc, diag::err_redefinition_different_kind)
7180 << Name.Identifier;
7181
7182 NamedDecl *OldD = Previous.getRepresentativeDecl();
7183 if (OldD->getLocation().isValid())
7184 Diag(OldD->getLocation(), diag::note_previous_definition);
7185
7186 Invalid = true;
7187 }
7188
7189 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7190 if (TemplateParameterListsAreEqual(TemplateParams,
7191 OldDecl->getTemplateParameters(),
7192 /*Complain=*/true,
7193 TPL_TemplateMatch))
7194 OldTemplateParams = OldDecl->getTemplateParameters();
7195 else
7196 Invalid = true;
7197
7198 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7199 if (!Invalid &&
7200 !Context.hasSameType(OldTD->getUnderlyingType(),
7201 NewTD->getUnderlyingType())) {
7202 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7203 // but we can't reasonably accept it.
7204 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7205 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7206 if (OldTD->getLocation().isValid())
7207 Diag(OldTD->getLocation(), diag::note_previous_definition);
7208 Invalid = true;
7209 }
7210 }
7211 }
7212
7213 // Merge any previous default template arguments into our parameters,
7214 // and check the parameter list.
7215 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7216 TPC_TypeAliasTemplate))
7217 return 0;
7218
7219 TypeAliasTemplateDecl *NewDecl =
7220 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7221 Name.Identifier, TemplateParams,
7222 NewTD);
7223
7224 NewDecl->setAccess(AS);
7225
7226 if (Invalid)
7227 NewDecl->setInvalidDecl();
7228 else if (OldDecl)
7229 NewDecl->setPreviousDeclaration(OldDecl);
7230
7231 NewND = NewDecl;
7232 } else {
7233 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7234 NewND = NewTD;
7235 }
Richard Smith162e1c12011-04-15 14:24:37 +00007236
7237 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007238 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007239
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007240 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007241 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007242}
7243
John McCalld226f652010-08-21 09:40:31 +00007244Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007245 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007246 SourceLocation AliasLoc,
7247 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007248 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007249 SourceLocation IdentLoc,
7250 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007251
Anders Carlsson81c85c42009-03-28 23:53:49 +00007252 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007253 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7254 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007255
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007256 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007257 NamedDecl *PrevDecl
7258 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7259 ForRedeclaration);
7260 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7261 PrevDecl = 0;
7262
7263 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007264 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007265 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007266 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007267 // FIXME: At some point, we'll want to create the (redundant)
7268 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007269 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007270 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007271 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007272 }
Mike Stump1eb44332009-09-09 15:08:12 +00007273
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007274 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7275 diag::err_redefinition_different_kind;
7276 Diag(AliasLoc, DiagID) << Alias;
7277 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007278 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007279 }
7280
John McCalla24dc2e2009-11-17 02:14:36 +00007281 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007282 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007283
John McCallf36e02d2009-10-09 21:13:30 +00007284 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007285 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007286 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007287 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007288 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007289 }
Mike Stump1eb44332009-09-09 15:08:12 +00007290
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007291 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007292 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007293 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007294 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007295
John McCall3dbd3d52010-02-16 06:53:13 +00007296 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007297 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007298}
7299
Sean Hunt001cad92011-05-10 00:49:42 +00007300Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007301Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7302 CXXMethodDecl *MD) {
7303 CXXRecordDecl *ClassDecl = MD->getParent();
7304
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007305 // C++ [except.spec]p14:
7306 // An implicitly declared special member function (Clause 12) shall have an
7307 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007308 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007309 if (ClassDecl->isInvalidDecl())
7310 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007311
Sebastian Redl60618fa2011-03-12 11:50:43 +00007312 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007313 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7314 BEnd = ClassDecl->bases_end();
7315 B != BEnd; ++B) {
7316 if (B->isVirtual()) // Handled below.
7317 continue;
7318
Douglas Gregor18274032010-07-03 00:47:00 +00007319 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7320 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007321 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7322 // If this is a deleted function, add it anyway. This might be conformant
7323 // with the standard. This might not. I'm not sure. It might not matter.
7324 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007325 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007326 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007327 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007328
7329 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007330 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7331 BEnd = ClassDecl->vbases_end();
7332 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007333 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7334 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007335 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7336 // If this is a deleted function, add it anyway. This might be conformant
7337 // with the standard. This might not. I'm not sure. It might not matter.
7338 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007339 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007340 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007341 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007342
7343 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007344 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7345 FEnd = ClassDecl->field_end();
7346 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007347 if (F->hasInClassInitializer()) {
7348 if (Expr *E = F->getInClassInitializer())
7349 ExceptSpec.CalledExpr(E);
7350 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007351 // DR1351:
7352 // If the brace-or-equal-initializer of a non-static data member
7353 // invokes a defaulted default constructor of its class or of an
7354 // enclosing class in a potentially evaluated subexpression, the
7355 // program is ill-formed.
7356 //
7357 // This resolution is unworkable: the exception specification of the
7358 // default constructor can be needed in an unevaluated context, in
7359 // particular, in the operand of a noexcept-expression, and we can be
7360 // unable to compute an exception specification for an enclosed class.
7361 //
7362 // We do not allow an in-class initializer to require the evaluation
7363 // of the exception specification for any in-class initializer whose
7364 // definition is not lexically complete.
7365 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007366 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007367 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007368 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7369 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7370 // If this is a deleted function, add it anyway. This might be conformant
7371 // with the standard. This might not. I'm not sure. It might not matter.
7372 // In particular, the problem is that this function never gets called. It
7373 // might just be ill-formed because this function attempts to refer to
7374 // a deleted function here.
7375 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007376 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007377 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007378 }
John McCalle23cf432010-12-14 08:05:40 +00007379
Sean Hunt001cad92011-05-10 00:49:42 +00007380 return ExceptSpec;
7381}
7382
Richard Smithafb49182012-11-29 01:34:07 +00007383namespace {
7384/// RAII object to register a special member as being currently declared.
7385struct DeclaringSpecialMember {
7386 Sema &S;
7387 Sema::SpecialMemberDecl D;
7388 bool WasAlreadyBeingDeclared;
7389
7390 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7391 : S(S), D(RD, CSM) {
7392 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7393 if (WasAlreadyBeingDeclared)
7394 // This almost never happens, but if it does, ensure that our cache
7395 // doesn't contain a stale result.
7396 S.SpecialMemberCache.clear();
7397
7398 // FIXME: Register a note to be produced if we encounter an error while
7399 // declaring the special member.
7400 }
7401 ~DeclaringSpecialMember() {
7402 if (!WasAlreadyBeingDeclared)
7403 S.SpecialMembersBeingDeclared.erase(D);
7404 }
7405
7406 /// \brief Are we already trying to declare this special member?
7407 bool isAlreadyBeingDeclared() const {
7408 return WasAlreadyBeingDeclared;
7409 }
7410};
7411}
7412
Sean Hunt001cad92011-05-10 00:49:42 +00007413CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7414 CXXRecordDecl *ClassDecl) {
7415 // C++ [class.ctor]p5:
7416 // A default constructor for a class X is a constructor of class X
7417 // that can be called without an argument. If there is no
7418 // user-declared constructor for class X, a default constructor is
7419 // implicitly declared. An implicitly-declared default constructor
7420 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007421 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007422 "Should not build implicit default constructor!");
7423
Richard Smithafb49182012-11-29 01:34:07 +00007424 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7425 if (DSM.isAlreadyBeingDeclared())
7426 return 0;
7427
Richard Smith7756afa2012-06-10 05:43:50 +00007428 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7429 CXXDefaultConstructor,
7430 false);
7431
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007432 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007433 CanQualType ClassType
7434 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007435 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007436 DeclarationName Name
7437 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007438 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007439 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007440 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007441 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007442 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007443 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007444 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007445 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007446
7447 // Build an exception specification pointing back at this constructor.
7448 FunctionProtoType::ExtProtoInfo EPI;
7449 EPI.ExceptionSpecType = EST_Unevaluated;
7450 EPI.ExceptionSpecDecl = DefaultCon;
7451 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7452
Richard Smithbc2a35d2012-12-08 08:32:28 +00007453 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7454 // constructors is easy to compute.
7455 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7456
7457 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7458 DefaultCon->setDeletedAsWritten();
7459
Douglas Gregor18274032010-07-03 00:47:00 +00007460 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007461 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007462
Douglas Gregor23c94db2010-07-02 17:43:08 +00007463 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007464 PushOnScopeChains(DefaultCon, S, false);
7465 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007466
Douglas Gregor32df23e2010-07-01 22:02:46 +00007467 return DefaultCon;
7468}
7469
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007470void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7471 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007472 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007473 !Constructor->doesThisDeclarationHaveABody() &&
7474 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007475 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007476
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007477 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007478 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007479
Eli Friedman9a14db32012-10-18 20:14:08 +00007480 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007481 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00007482 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007483 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007484 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007485 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007486 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007487 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007488 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007489
7490 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007491 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007492
7493 Constructor->setUsed();
7494 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007495
7496 if (ASTMutationListener *L = getASTMutationListener()) {
7497 L->CompletedImplicitDefinition(Constructor);
7498 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007499}
7500
Richard Smith7a614d82011-06-11 17:19:42 +00007501void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7502 if (!D) return;
7503 AdjustDeclIfTemplate(D);
7504
7505 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
Richard Smith7a614d82011-06-11 17:19:42 +00007506
Richard Smithb9d0b762012-07-27 04:22:15 +00007507 if (!ClassDecl->isDependentType())
Richard Smithac713512012-12-08 02:53:02 +00007508 CheckExplicitlyDefaultedAndDeletedMethods(ClassDecl);
7509
7510 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
7511 // function that is not a constructor declares that member function to be
7512 // const. [...] The class of which that function is a member shall be
7513 // a literal type.
7514 //
7515 // If the class has virtual bases, any constexpr members will already have
7516 // been diagnosed by the checks performed on the member declaration, so
7517 // suppress this (less useful) diagnostic.
7518 //
7519 // We delay this until we know whether an explicitly-defaulted (or deleted)
7520 // destructor for the class is trivial.
7521 if (LangOpts.CPlusPlus0x && !ClassDecl->isDependentType() &&
7522 !ClassDecl->isLiteral() && !ClassDecl->getNumVBases()) {
7523 for (CXXRecordDecl::method_iterator M = ClassDecl->method_begin(),
7524 MEnd = ClassDecl->method_end();
7525 M != MEnd; ++M) {
7526 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
7527 switch (ClassDecl->getTemplateSpecializationKind()) {
7528 case TSK_ImplicitInstantiation:
7529 case TSK_ExplicitInstantiationDeclaration:
7530 case TSK_ExplicitInstantiationDefinition:
7531 // If a template instantiates to a non-literal type, but its members
7532 // instantiate to constexpr functions, the template is technically
7533 // ill-formed, but we allow it for sanity.
7534 continue;
7535
7536 case TSK_Undeclared:
7537 case TSK_ExplicitSpecialization:
7538 RequireLiteralType(M->getLocation(), Context.getRecordType(ClassDecl),
7539 diag::err_constexpr_method_non_literal);
7540 break;
7541 }
7542
7543 // Only produce one error per class.
7544 break;
7545 }
7546 }
7547 }
Richard Smith7a614d82011-06-11 17:19:42 +00007548}
7549
Sebastian Redlf677ea32011-02-05 19:23:19 +00007550void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7551 // We start with an initial pass over the base classes to collect those that
7552 // inherit constructors from. If there are none, we can forgo all further
7553 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007554 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007555 BasesVector BasesToInheritFrom;
7556 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7557 BaseE = ClassDecl->bases_end();
7558 BaseIt != BaseE; ++BaseIt) {
7559 if (BaseIt->getInheritConstructors()) {
7560 QualType Base = BaseIt->getType();
7561 if (Base->isDependentType()) {
7562 // If we inherit constructors from anything that is dependent, just
7563 // abort processing altogether. We'll get another chance for the
7564 // instantiations.
7565 return;
7566 }
7567 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7568 }
7569 }
7570 if (BasesToInheritFrom.empty())
7571 return;
7572
7573 // Now collect the constructors that we already have in the current class.
7574 // Those take precedence over inherited constructors.
7575 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7576 // unless there is a user-declared constructor with the same signature in
7577 // the class where the using-declaration appears.
7578 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7579 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7580 CtorE = ClassDecl->ctor_end();
7581 CtorIt != CtorE; ++CtorIt) {
7582 ExistingConstructors.insert(
7583 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7584 }
7585
Sebastian Redlf677ea32011-02-05 19:23:19 +00007586 DeclarationName CreatedCtorName =
7587 Context.DeclarationNames.getCXXConstructorName(
7588 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7589
7590 // Now comes the true work.
7591 // First, we keep a map from constructor types to the base that introduced
7592 // them. Needed for finding conflicting constructors. We also keep the
7593 // actually inserted declarations in there, for pretty diagnostics.
7594 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7595 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7596 ConstructorToSourceMap InheritedConstructors;
7597 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7598 BaseE = BasesToInheritFrom.end();
7599 BaseIt != BaseE; ++BaseIt) {
7600 const RecordType *Base = *BaseIt;
7601 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7602 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7603 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7604 CtorE = BaseDecl->ctor_end();
7605 CtorIt != CtorE; ++CtorIt) {
7606 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00007607 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00007608 DeclarationName Name =
7609 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00007610 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7611 LookupQualifiedName(Result, CurContext);
7612 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007613 SourceLocation UsingLoc = UD ? UD->getLocation() :
7614 ClassDecl->getLocation();
7615
7616 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7617 // from the class X named in the using-declaration consists of actual
7618 // constructors and notional constructors that result from the
7619 // transformation of defaulted parameters as follows:
7620 // - all non-template default constructors of X, and
7621 // - for each non-template constructor of X that has at least one
7622 // parameter with a default argument, the set of constructors that
7623 // results from omitting any ellipsis parameter specification and
7624 // successively omitting parameters with a default argument from the
7625 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00007626 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007627 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7628 const FunctionProtoType *BaseCtorType =
7629 BaseCtor->getType()->getAs<FunctionProtoType>();
7630
7631 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7632 maxParams = BaseCtor->getNumParams();
7633 params <= maxParams; ++params) {
7634 // Skip default constructors. They're never inherited.
7635 if (params == 0)
7636 continue;
7637 // Skip copy and move constructors for the same reason.
7638 if (CanBeCopyOrMove && params == 1)
7639 continue;
7640
7641 // Build up a function type for this particular constructor.
7642 // FIXME: The working paper does not consider that the exception spec
7643 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007644 // source. This code doesn't yet, either. When it does, this code will
7645 // need to be delayed until after exception specifications and in-class
7646 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007647 const Type *NewCtorType;
7648 if (params == maxParams)
7649 NewCtorType = BaseCtorType;
7650 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007651 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007652 for (unsigned i = 0; i < params; ++i) {
7653 Args.push_back(BaseCtorType->getArgType(i));
7654 }
7655 FunctionProtoType::ExtProtoInfo ExtInfo =
7656 BaseCtorType->getExtProtoInfo();
7657 ExtInfo.Variadic = false;
7658 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7659 Args.data(), params, ExtInfo)
7660 .getTypePtr();
7661 }
7662 const Type *CanonicalNewCtorType =
7663 Context.getCanonicalType(NewCtorType);
7664
7665 // Now that we have the type, first check if the class already has a
7666 // constructor with this signature.
7667 if (ExistingConstructors.count(CanonicalNewCtorType))
7668 continue;
7669
7670 // Then we check if we have already declared an inherited constructor
7671 // with this signature.
7672 std::pair<ConstructorToSourceMap::iterator, bool> result =
7673 InheritedConstructors.insert(std::make_pair(
7674 CanonicalNewCtorType,
7675 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7676 if (!result.second) {
7677 // Already in the map. If it came from a different class, that's an
7678 // error. Not if it's from the same.
7679 CanQualType PreviousBase = result.first->second.first;
7680 if (CanonicalBase != PreviousBase) {
7681 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7682 const CXXConstructorDecl *PrevBaseCtor =
7683 PrevCtor->getInheritedConstructor();
7684 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7685
7686 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7687 Diag(BaseCtor->getLocation(),
7688 diag::note_using_decl_constructor_conflict_current_ctor);
7689 Diag(PrevBaseCtor->getLocation(),
7690 diag::note_using_decl_constructor_conflict_previous_ctor);
7691 Diag(PrevCtor->getLocation(),
7692 diag::note_using_decl_constructor_conflict_previous_using);
7693 }
7694 continue;
7695 }
7696
7697 // OK, we're there, now add the constructor.
7698 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007699 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007700 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7701 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007702 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7703 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007704 /*ImplicitlyDeclared=*/true,
7705 // FIXME: Due to a defect in the standard, we treat inherited
7706 // constructors as constexpr even if that makes them ill-formed.
7707 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007708 NewCtor->setAccess(BaseCtor->getAccess());
7709
7710 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007711 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007712 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007713 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7714 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007715 /*IdentifierInfo=*/0,
7716 BaseCtorType->getArgType(i),
7717 /*TInfo=*/0, SC_None,
7718 SC_None, /*DefaultArg=*/0));
7719 }
David Blaikie4278c652011-09-21 18:16:56 +00007720 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007721 NewCtor->setInheritedConstructor(BaseCtor);
7722
Sebastian Redlf677ea32011-02-05 19:23:19 +00007723 ClassDecl->addDecl(NewCtor);
7724 result.first->second.second = NewCtor;
7725 }
7726 }
7727 }
7728}
7729
Sean Huntcb45a0f2011-05-12 22:46:25 +00007730Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007731Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7732 CXXRecordDecl *ClassDecl = MD->getParent();
7733
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007734 // C++ [except.spec]p14:
7735 // An implicitly declared special member function (Clause 12) shall have
7736 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007737 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007738 if (ClassDecl->isInvalidDecl())
7739 return ExceptSpec;
7740
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007741 // Direct base-class destructors.
7742 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7743 BEnd = ClassDecl->bases_end();
7744 B != BEnd; ++B) {
7745 if (B->isVirtual()) // Handled below.
7746 continue;
7747
7748 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007749 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007750 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007751 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007752
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007753 // Virtual base-class destructors.
7754 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7755 BEnd = ClassDecl->vbases_end();
7756 B != BEnd; ++B) {
7757 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007758 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007759 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007760 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007761
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007762 // Field destructors.
7763 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7764 FEnd = ClassDecl->field_end();
7765 F != FEnd; ++F) {
7766 if (const RecordType *RecordTy
7767 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007768 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007769 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007770 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007771
Sean Huntcb45a0f2011-05-12 22:46:25 +00007772 return ExceptSpec;
7773}
7774
7775CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7776 // C++ [class.dtor]p2:
7777 // If a class has no user-declared destructor, a destructor is
7778 // declared implicitly. An implicitly-declared destructor is an
7779 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00007780 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00007781
Richard Smithafb49182012-11-29 01:34:07 +00007782 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7783 if (DSM.isAlreadyBeingDeclared())
7784 return 0;
7785
Douglas Gregor4923aa22010-07-02 20:37:36 +00007786 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007787 CanQualType ClassType
7788 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007789 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007790 DeclarationName Name
7791 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007792 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007793 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007794 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7795 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007796 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007797 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007798 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007799 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007800
7801 // Build an exception specification pointing back at this destructor.
7802 FunctionProtoType::ExtProtoInfo EPI;
7803 EPI.ExceptionSpecType = EST_Unevaluated;
7804 EPI.ExceptionSpecDecl = Destructor;
7805 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7806
Richard Smithbc2a35d2012-12-08 08:32:28 +00007807 AddOverriddenMethods(ClassDecl, Destructor);
7808
7809 // We don't need to use SpecialMemberIsTrivial here; triviality for
7810 // destructors is easy to compute.
7811 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7812
7813 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7814 Destructor->setDeletedAsWritten();
7815
Douglas Gregor4923aa22010-07-02 20:37:36 +00007816 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007817 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007818
Douglas Gregor4923aa22010-07-02 20:37:36 +00007819 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007820 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007821 PushOnScopeChains(Destructor, S, false);
7822 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007823
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007824 return Destructor;
7825}
7826
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007827void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007828 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007829 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007830 !Destructor->doesThisDeclarationHaveABody() &&
7831 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007832 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007833 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007834 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007835
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007836 if (Destructor->isInvalidDecl())
7837 return;
7838
Eli Friedman9a14db32012-10-18 20:14:08 +00007839 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007840
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007841 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007842 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7843 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007844
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007845 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007846 Diag(CurrentLocation, diag::note_member_synthesized_at)
7847 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7848
7849 Destructor->setInvalidDecl();
7850 return;
7851 }
7852
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007853 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007854 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007855 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007856 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007857 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007858
7859 if (ASTMutationListener *L = getASTMutationListener()) {
7860 L->CompletedImplicitDefinition(Destructor);
7861 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007862}
7863
Richard Smitha4156b82012-04-21 18:42:51 +00007864/// \brief Perform any semantic analysis which needs to be delayed until all
7865/// pending class member declarations have been parsed.
7866void Sema::ActOnFinishCXXMemberDecls() {
Richard Smitha4156b82012-04-21 18:42:51 +00007867 // Perform any deferred checking of exception specifications for virtual
7868 // destructors.
7869 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7870 i != e; ++i) {
7871 const CXXDestructorDecl *Dtor =
7872 DelayedDestructorExceptionSpecChecks[i].first;
7873 assert(!Dtor->getParent()->isDependentType() &&
7874 "Should not ever add destructors of templates into the list.");
7875 CheckOverridingFunctionExceptionSpec(Dtor,
7876 DelayedDestructorExceptionSpecChecks[i].second);
7877 }
7878 DelayedDestructorExceptionSpecChecks.clear();
7879}
7880
Richard Smithb9d0b762012-07-27 04:22:15 +00007881void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7882 CXXDestructorDecl *Destructor) {
7883 assert(getLangOpts().CPlusPlus0x &&
7884 "adjusting dtor exception specs was introduced in c++11");
7885
Sebastian Redl0ee33912011-05-19 05:13:44 +00007886 // C++11 [class.dtor]p3:
7887 // A declaration of a destructor that does not have an exception-
7888 // specification is implicitly considered to have the same exception-
7889 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007890 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007891 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007892 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007893 return;
7894
Chandler Carruth3f224b22011-09-20 04:55:26 +00007895 // Replace the destructor's type, building off the existing one. Fortunately,
7896 // the only thing of interest in the destructor type is its extended info.
7897 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007898 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7899 EPI.ExceptionSpecType = EST_Unevaluated;
7900 EPI.ExceptionSpecDecl = Destructor;
7901 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007902
Sebastian Redl0ee33912011-05-19 05:13:44 +00007903 // FIXME: If the destructor has a body that could throw, and the newly created
7904 // spec doesn't allow exceptions, we should emit a warning, because this
7905 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007906 // However, we don't have a body or an exception specification yet, so it
7907 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007908}
7909
Richard Smith8c889532012-11-14 00:50:40 +00007910/// When generating a defaulted copy or move assignment operator, if a field
7911/// should be copied with __builtin_memcpy rather than via explicit assignments,
7912/// do so. This optimization only applies for arrays of scalars, and for arrays
7913/// of class type where the selected copy/move-assignment operator is trivial.
7914static StmtResult
7915buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
7916 Expr *To, Expr *From) {
7917 // Compute the size of the memory buffer to be copied.
7918 QualType SizeType = S.Context.getSizeType();
7919 llvm::APInt Size(S.Context.getTypeSize(SizeType),
7920 S.Context.getTypeSizeInChars(T).getQuantity());
7921
7922 // Take the address of the field references for "from" and "to". We
7923 // directly construct UnaryOperators here because semantic analysis
7924 // does not permit us to take the address of an xvalue.
7925 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
7926 S.Context.getPointerType(From->getType()),
7927 VK_RValue, OK_Ordinary, Loc);
7928 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
7929 S.Context.getPointerType(To->getType()),
7930 VK_RValue, OK_Ordinary, Loc);
7931
7932 const Type *E = T->getBaseElementTypeUnsafe();
7933 bool NeedsCollectableMemCpy =
7934 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
7935
7936 // Create a reference to the __builtin_objc_memmove_collectable function
7937 StringRef MemCpyName = NeedsCollectableMemCpy ?
7938 "__builtin_objc_memmove_collectable" :
7939 "__builtin_memcpy";
7940 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
7941 Sema::LookupOrdinaryName);
7942 S.LookupName(R, S.TUScope, true);
7943
7944 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
7945 if (!MemCpy)
7946 // Something went horribly wrong earlier, and we will have complained
7947 // about it.
7948 return StmtError();
7949
7950 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
7951 VK_RValue, Loc, 0);
7952 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
7953
7954 Expr *CallArgs[] = {
7955 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
7956 };
7957 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
7958 Loc, CallArgs, Loc);
7959
7960 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7961 return S.Owned(Call.takeAs<Stmt>());
7962}
7963
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007964/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007965/// \c To.
7966///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007967/// This routine is used to copy/move the members of a class with an
7968/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007969/// copied are arrays, this routine builds for loops to copy them.
7970///
7971/// \param S The Sema object used for type-checking.
7972///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007973/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007974///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007975/// \param T The type of the expressions being copied/moved. Both expressions
7976/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007977///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007978/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007979///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007980/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007981///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007982/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007983/// Otherwise, it's a non-static member subobject.
7984///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007985/// \param Copying Whether we're copying or moving.
7986///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007987/// \param Depth Internal parameter recording the depth of the recursion.
7988///
Richard Smith8c889532012-11-14 00:50:40 +00007989/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
7990/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00007991static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00007992buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
7993 Expr *To, Expr *From,
7994 bool CopyingBaseSubobject, bool Copying,
7995 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00007996 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007997 // Each subobject is assigned in the manner appropriate to its type:
7998 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007999 // - if the subobject is of class type, as if by a call to operator= with
8000 // the subobject as the object expression and the corresponding
8001 // subobject of x as a single function argument (as if by explicit
8002 // qualification; that is, ignoring any possible virtual overriding
8003 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008004 //
8005 // C++03 [class.copy]p13:
8006 // - if the subobject is of class type, the copy assignment operator for
8007 // the class is used (as if by explicit qualification; that is,
8008 // ignoring any possible virtual overriding functions in more derived
8009 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008010 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8011 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008012
Douglas Gregor06a9f362010-05-01 20:49:11 +00008013 // Look for operator=.
8014 DeclarationName Name
8015 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8016 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8017 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008018
Richard Smith044c8aa2012-11-13 00:54:12 +00008019 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8020 // operator.
8021 if (!S.getLangOpts().CPlusPlus0x) {
8022 LookupResult::Filter F = OpLookup.makeFilter();
8023 while (F.hasNext()) {
8024 NamedDecl *D = F.next();
8025 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8026 if (Method->isCopyAssignmentOperator() ||
8027 (!Copying && Method->isMoveAssignmentOperator()))
8028 continue;
8029
8030 F.erase();
8031 }
8032 F.done();
John McCallb0207482010-03-16 06:11:48 +00008033 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008034
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008035 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008036 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008037 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008038 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008039 // ambiguities), we need to cast "this" to that subobject type; to
8040 // ensure that we don't go through the virtual call mechanism, we need
8041 // to qualify the operator= name with the base class (see below). However,
8042 // this means that if the base class has a protected copy assignment
8043 // operator, the protected member access check will fail. So, we
8044 // rewrite "protected" access to "public" access in this case, since we
8045 // know by construction that we're calling from a derived class.
8046 if (CopyingBaseSubobject) {
8047 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8048 L != LEnd; ++L) {
8049 if (L.getAccess() == AS_protected)
8050 L.setAccess(AS_public);
8051 }
8052 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008053
Douglas Gregor06a9f362010-05-01 20:49:11 +00008054 // Create the nested-name-specifier that will be used to qualify the
8055 // reference to operator=; this is required to suppress the virtual
8056 // call mechanism.
8057 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008058 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008059 SS.MakeTrivial(S.Context,
8060 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008061 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008062 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008063
Douglas Gregor06a9f362010-05-01 20:49:11 +00008064 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008065 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008066 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008067 /*TemplateKWLoc=*/SourceLocation(),
8068 /*FirstQualifierInScope=*/0,
8069 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008070 /*TemplateArgs=*/0,
8071 /*SuppressQualifierCheck=*/true);
8072 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008073 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008074
Douglas Gregor06a9f362010-05-01 20:49:11 +00008075 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008076
Richard Smith044c8aa2012-11-13 00:54:12 +00008077 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008078 OpEqualRef.takeAs<Expr>(),
8079 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008080 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008081 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008082
Richard Smith8c889532012-11-14 00:50:40 +00008083 // If we built a call to a trivial 'operator=' while copying an array,
8084 // bail out. We'll replace the whole shebang with a memcpy.
8085 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8086 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8087 return StmtResult((Stmt*)0);
8088
Richard Smith044c8aa2012-11-13 00:54:12 +00008089 // Convert to an expression-statement, and clean up any produced
8090 // temporaries.
8091 return S.ActOnExprStmt(S.MakeFullExpr(Call.take(), Loc));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008092 }
John McCallb0207482010-03-16 06:11:48 +00008093
Richard Smith044c8aa2012-11-13 00:54:12 +00008094 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008095 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008096 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008097 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008098 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008099 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008100 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008101 return S.ActOnExprStmt(S.MakeFullExpr(Assignment.take(), Loc));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008102 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008103
8104 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008105 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008106
Douglas Gregor06a9f362010-05-01 20:49:11 +00008107 // Construct a loop over the array bounds, e.g.,
8108 //
8109 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8110 //
8111 // that will copy each of the array elements.
8112 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008113
Douglas Gregor06a9f362010-05-01 20:49:11 +00008114 // Create the iteration variable.
8115 IdentifierInfo *IterationVarName = 0;
8116 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008117 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008118 llvm::raw_svector_ostream OS(Str);
8119 OS << "__i" << Depth;
8120 IterationVarName = &S.Context.Idents.get(OS.str());
8121 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008122 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008123 IterationVarName, SizeType,
8124 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00008125 SC_None, SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008126
Douglas Gregor06a9f362010-05-01 20:49:11 +00008127 // Initialize the iteration variable to zero.
8128 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008129 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008130
8131 // Create a reference to the iteration variable; we'll use this several
8132 // times throughout.
8133 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008134 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008135 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008136 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8137 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8138
Douglas Gregor06a9f362010-05-01 20:49:11 +00008139 // Create the DeclStmt that holds the iteration variable.
8140 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008141
Douglas Gregor06a9f362010-05-01 20:49:11 +00008142 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008143 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008144 IterationVarRefRVal,
8145 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008146 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008147 IterationVarRefRVal,
8148 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008149 if (!Copying) // Cast to rvalue
8150 From = CastForMoving(S, From);
8151
8152 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008153 StmtResult Copy =
8154 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8155 To, From, CopyingBaseSubobject,
8156 Copying, Depth + 1);
8157 // Bail out if copying fails or if we determined that we should use memcpy.
8158 if (Copy.isInvalid() || !Copy.get())
8159 return Copy;
8160
8161 // Create the comparison against the array bound.
8162 llvm::APInt Upper
8163 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8164 Expr *Comparison
8165 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8166 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8167 BO_NE, S.Context.BoolTy,
8168 VK_RValue, OK_Ordinary, Loc, false);
8169
8170 // Create the pre-increment of the iteration variable.
8171 Expr *Increment
8172 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8173 VK_LValue, OK_Ordinary, Loc);
8174
Douglas Gregor06a9f362010-05-01 20:49:11 +00008175 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008176 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008177 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00008178 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008179 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008180}
8181
Richard Smith8c889532012-11-14 00:50:40 +00008182static StmtResult
8183buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8184 Expr *To, Expr *From,
8185 bool CopyingBaseSubobject, bool Copying) {
8186 // Maybe we should use a memcpy?
8187 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8188 T.isTriviallyCopyableType(S.Context))
8189 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8190
8191 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8192 CopyingBaseSubobject,
8193 Copying, 0));
8194
8195 // If we ended up picking a trivial assignment operator for an array of a
8196 // non-trivially-copyable class type, just emit a memcpy.
8197 if (!Result.isInvalid() && !Result.get())
8198 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8199
8200 return Result;
8201}
8202
Richard Smithb9d0b762012-07-27 04:22:15 +00008203Sema::ImplicitExceptionSpecification
8204Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8205 CXXRecordDecl *ClassDecl = MD->getParent();
8206
8207 ImplicitExceptionSpecification ExceptSpec(*this);
8208 if (ClassDecl->isInvalidDecl())
8209 return ExceptSpec;
8210
8211 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8212 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8213 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8214
Douglas Gregorb87786f2010-07-01 17:48:08 +00008215 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008216 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008217 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008218
8219 // It is unspecified whether or not an implicit copy assignment operator
8220 // attempts to deduplicate calls to assignment operators of virtual bases are
8221 // made. As such, this exception specification is effectively unspecified.
8222 // Based on a similar decision made for constness in C++0x, we're erring on
8223 // the side of assuming such calls to be made regardless of whether they
8224 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008225 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8226 BaseEnd = ClassDecl->bases_end();
8227 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008228 if (Base->isVirtual())
8229 continue;
8230
Douglas Gregora376d102010-07-02 21:50:04 +00008231 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008232 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008233 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8234 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008235 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008236 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008237
8238 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8239 BaseEnd = ClassDecl->vbases_end();
8240 Base != BaseEnd; ++Base) {
8241 CXXRecordDecl *BaseClassDecl
8242 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8243 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8244 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008245 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008246 }
8247
Douglas Gregorb87786f2010-07-01 17:48:08 +00008248 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8249 FieldEnd = ClassDecl->field_end();
8250 Field != FieldEnd;
8251 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008252 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008253 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8254 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008255 LookupCopyingAssignment(FieldClassDecl,
8256 ArgQuals | FieldType.getCVRQualifiers(),
8257 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008258 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008259 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008260 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008261
Richard Smithb9d0b762012-07-27 04:22:15 +00008262 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008263}
8264
8265CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8266 // Note: The following rules are largely analoguous to the copy
8267 // constructor rules. Note that virtual bases are not taken into account
8268 // for determining the argument type of the operator. Note also that
8269 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008270 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008271
Richard Smithafb49182012-11-29 01:34:07 +00008272 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8273 if (DSM.isAlreadyBeingDeclared())
8274 return 0;
8275
Sean Hunt30de05c2011-05-14 05:23:20 +00008276 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8277 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008278 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008279 ArgType = ArgType.withConst();
8280 ArgType = Context.getLValueReferenceType(ArgType);
8281
Douglas Gregord3c35902010-07-01 16:36:15 +00008282 // An implicitly-declared copy assignment operator is an inline public
8283 // member of its class.
8284 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008285 SourceLocation ClassLoc = ClassDecl->getLocation();
8286 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008287 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008288 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00008289 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00008290 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008291 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008292 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008293 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008294 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008295 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008296
8297 // Build an exception specification pointing back at this member.
8298 FunctionProtoType::ExtProtoInfo EPI;
8299 EPI.ExceptionSpecType = EST_Unevaluated;
8300 EPI.ExceptionSpecDecl = CopyAssignment;
8301 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8302
Douglas Gregord3c35902010-07-01 16:36:15 +00008303 // Add the parameter to the operator.
8304 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008305 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008306 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008307 SC_None,
8308 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008309 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008310
Richard Smithbc2a35d2012-12-08 08:32:28 +00008311 AddOverriddenMethods(ClassDecl, CopyAssignment);
8312
8313 CopyAssignment->setTrivial(
8314 ClassDecl->needsOverloadResolutionForCopyAssignment()
8315 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8316 : ClassDecl->hasTrivialCopyAssignment());
8317
Nico Weberafcc96a2012-01-23 03:19:29 +00008318 // C++0x [class.copy]p19:
8319 // .... If the class definition does not explicitly declare a copy
8320 // assignment operator, there is no user-declared move constructor, and
8321 // there is no user-declared move assignment operator, a copy assignment
8322 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008323 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00008324 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008325
Richard Smithbc2a35d2012-12-08 08:32:28 +00008326 // Note that we have added this copy-assignment operator.
8327 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8328
8329 if (Scope *S = getScopeForContext(ClassDecl))
8330 PushOnScopeChains(CopyAssignment, S, false);
8331 ClassDecl->addDecl(CopyAssignment);
8332
Douglas Gregord3c35902010-07-01 16:36:15 +00008333 return CopyAssignment;
8334}
8335
Douglas Gregor06a9f362010-05-01 20:49:11 +00008336void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8337 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008338 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008339 CopyAssignOperator->isOverloadedOperator() &&
8340 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008341 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8342 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008343 "DefineImplicitCopyAssignment called for wrong function");
8344
8345 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8346
8347 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8348 CopyAssignOperator->setInvalidDecl();
8349 return;
8350 }
8351
8352 CopyAssignOperator->setUsed();
8353
Eli Friedman9a14db32012-10-18 20:14:08 +00008354 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008355 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008356
8357 // C++0x [class.copy]p30:
8358 // The implicitly-defined or explicitly-defaulted copy assignment operator
8359 // for a non-union class X performs memberwise copy assignment of its
8360 // subobjects. The direct base classes of X are assigned first, in the
8361 // order of their declaration in the base-specifier-list, and then the
8362 // immediate non-static data members of X are assigned, in the order in
8363 // which they were declared in the class definition.
8364
8365 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008366 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008367
8368 // The parameter for the "other" object, which we are copying from.
8369 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8370 Qualifiers OtherQuals = Other->getType().getQualifiers();
8371 QualType OtherRefType = Other->getType();
8372 if (const LValueReferenceType *OtherRef
8373 = OtherRefType->getAs<LValueReferenceType>()) {
8374 OtherRefType = OtherRef->getPointeeType();
8375 OtherQuals = OtherRefType.getQualifiers();
8376 }
8377
8378 // Our location for everything implicitly-generated.
8379 SourceLocation Loc = CopyAssignOperator->getLocation();
8380
8381 // Construct a reference to the "other" object. We'll be using this
8382 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008383 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008384 assert(OtherRef && "Reference to parameter cannot fail!");
8385
8386 // Construct the "this" pointer. We'll be using this throughout the generated
8387 // ASTs.
8388 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8389 assert(This && "Reference to this cannot fail!");
8390
8391 // Assign base classes.
8392 bool Invalid = false;
8393 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8394 E = ClassDecl->bases_end(); Base != E; ++Base) {
8395 // Form the assignment:
8396 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8397 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008398 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008399 Invalid = true;
8400 continue;
8401 }
8402
John McCallf871d0c2010-08-07 06:22:56 +00008403 CXXCastPath BasePath;
8404 BasePath.push_back(Base);
8405
Douglas Gregor06a9f362010-05-01 20:49:11 +00008406 // Construct the "from" expression, which is an implicit cast to the
8407 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008408 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008409 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8410 CK_UncheckedDerivedToBase,
8411 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008412
8413 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008414 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008415
8416 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008417 To = ImpCastExprToType(To.take(),
8418 Context.getCVRQualifiedType(BaseType,
8419 CopyAssignOperator->getTypeQualifiers()),
8420 CK_UncheckedDerivedToBase,
8421 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008422
8423 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008424 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008425 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008426 /*CopyingBaseSubobject=*/true,
8427 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008428 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008429 Diag(CurrentLocation, diag::note_member_synthesized_at)
8430 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8431 CopyAssignOperator->setInvalidDecl();
8432 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008433 }
8434
8435 // Success! Record the copy.
8436 Statements.push_back(Copy.takeAs<Expr>());
8437 }
8438
Douglas Gregor06a9f362010-05-01 20:49:11 +00008439 // Assign non-static members.
8440 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8441 FieldEnd = ClassDecl->field_end();
8442 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008443 if (Field->isUnnamedBitfield())
8444 continue;
8445
Douglas Gregor06a9f362010-05-01 20:49:11 +00008446 // Check for members of reference type; we can't copy those.
8447 if (Field->getType()->isReferenceType()) {
8448 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8449 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8450 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008451 Diag(CurrentLocation, diag::note_member_synthesized_at)
8452 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008453 Invalid = true;
8454 continue;
8455 }
8456
8457 // Check for members of const-qualified, non-class type.
8458 QualType BaseType = Context.getBaseElementType(Field->getType());
8459 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8460 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8461 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8462 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008463 Diag(CurrentLocation, diag::note_member_synthesized_at)
8464 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008465 Invalid = true;
8466 continue;
8467 }
John McCallb77115d2011-06-17 00:18:42 +00008468
8469 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008470 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8471 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008472
8473 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008474 if (FieldType->isIncompleteArrayType()) {
8475 assert(ClassDecl->hasFlexibleArrayMember() &&
8476 "Incomplete array type is not valid");
8477 continue;
8478 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008479
8480 // Build references to the field in the object we're copying from and to.
8481 CXXScopeSpec SS; // Intentionally empty
8482 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8483 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008484 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008485 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008486 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008487 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008488 SS, SourceLocation(), 0,
8489 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008490 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008491 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008492 SS, SourceLocation(), 0,
8493 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008494 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8495 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008496
Douglas Gregor06a9f362010-05-01 20:49:11 +00008497 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008498 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008499 To.get(), From.get(),
8500 /*CopyingBaseSubobject=*/false,
8501 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008502 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008503 Diag(CurrentLocation, diag::note_member_synthesized_at)
8504 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8505 CopyAssignOperator->setInvalidDecl();
8506 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008507 }
8508
8509 // Success! Record the copy.
8510 Statements.push_back(Copy.takeAs<Stmt>());
8511 }
8512
8513 if (!Invalid) {
8514 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008515 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008516
John McCall60d7b3a2010-08-24 06:29:42 +00008517 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008518 if (Return.isInvalid())
8519 Invalid = true;
8520 else {
8521 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008522
8523 if (Trap.hasErrorOccurred()) {
8524 Diag(CurrentLocation, diag::note_member_synthesized_at)
8525 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8526 Invalid = true;
8527 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008528 }
8529 }
8530
8531 if (Invalid) {
8532 CopyAssignOperator->setInvalidDecl();
8533 return;
8534 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008535
8536 StmtResult Body;
8537 {
8538 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008539 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008540 /*isStmtExpr=*/false);
8541 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8542 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008543 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008544
8545 if (ASTMutationListener *L = getASTMutationListener()) {
8546 L->CompletedImplicitDefinition(CopyAssignOperator);
8547 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008548}
8549
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008550Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008551Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8552 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008553
Richard Smithb9d0b762012-07-27 04:22:15 +00008554 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008555 if (ClassDecl->isInvalidDecl())
8556 return ExceptSpec;
8557
8558 // C++0x [except.spec]p14:
8559 // An implicitly declared special member function (Clause 12) shall have an
8560 // exception-specification. [...]
8561
8562 // It is unspecified whether or not an implicit move assignment operator
8563 // attempts to deduplicate calls to assignment operators of virtual bases are
8564 // made. As such, this exception specification is effectively unspecified.
8565 // Based on a similar decision made for constness in C++0x, we're erring on
8566 // the side of assuming such calls to be made regardless of whether they
8567 // actually happen.
8568 // Note that a move constructor is not implicitly declared when there are
8569 // virtual bases, but it can still be user-declared and explicitly defaulted.
8570 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8571 BaseEnd = ClassDecl->bases_end();
8572 Base != BaseEnd; ++Base) {
8573 if (Base->isVirtual())
8574 continue;
8575
8576 CXXRecordDecl *BaseClassDecl
8577 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8578 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008579 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008580 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008581 }
8582
8583 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8584 BaseEnd = ClassDecl->vbases_end();
8585 Base != BaseEnd; ++Base) {
8586 CXXRecordDecl *BaseClassDecl
8587 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8588 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008589 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008590 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008591 }
8592
8593 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8594 FieldEnd = ClassDecl->field_end();
8595 Field != FieldEnd;
8596 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008597 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008598 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008599 if (CXXMethodDecl *MoveAssign =
8600 LookupMovingAssignment(FieldClassDecl,
8601 FieldType.getCVRQualifiers(),
8602 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008603 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008604 }
8605 }
8606
8607 return ExceptSpec;
8608}
8609
Richard Smith1c931be2012-04-02 18:40:40 +00008610/// Determine whether the class type has any direct or indirect virtual base
8611/// classes which have a non-trivial move assignment operator.
8612static bool
8613hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8614 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8615 BaseEnd = ClassDecl->vbases_end();
8616 Base != BaseEnd; ++Base) {
8617 CXXRecordDecl *BaseClass =
8618 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8619
8620 // Try to declare the move assignment. If it would be deleted, then the
8621 // class does not have a non-trivial move assignment.
8622 if (BaseClass->needsImplicitMoveAssignment())
8623 S.DeclareImplicitMoveAssignment(BaseClass);
8624
Richard Smith426391c2012-11-16 00:53:38 +00008625 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008626 return true;
8627 }
8628
8629 return false;
8630}
8631
8632/// Determine whether the given type either has a move constructor or is
8633/// trivially copyable.
8634static bool
8635hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8636 Type = S.Context.getBaseElementType(Type);
8637
8638 // FIXME: Technically, non-trivially-copyable non-class types, such as
8639 // reference types, are supposed to return false here, but that appears
8640 // to be a standard defect.
8641 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008642 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008643 return true;
8644
8645 if (Type.isTriviallyCopyableType(S.Context))
8646 return true;
8647
8648 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008649 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8650 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008651 if (ClassDecl->needsImplicitMoveConstructor())
8652 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008653 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008654 }
8655
Richard Smithe5411b72012-12-01 02:35:44 +00008656 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8657 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008658 if (ClassDecl->needsImplicitMoveAssignment())
8659 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008660 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008661}
8662
8663/// Determine whether all non-static data members and direct or virtual bases
8664/// of class \p ClassDecl have either a move operation, or are trivially
8665/// copyable.
8666static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8667 bool IsConstructor) {
8668 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8669 BaseEnd = ClassDecl->bases_end();
8670 Base != BaseEnd; ++Base) {
8671 if (Base->isVirtual())
8672 continue;
8673
8674 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8675 return false;
8676 }
8677
8678 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8679 BaseEnd = ClassDecl->vbases_end();
8680 Base != BaseEnd; ++Base) {
8681 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8682 return false;
8683 }
8684
8685 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8686 FieldEnd = ClassDecl->field_end();
8687 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008688 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008689 return false;
8690 }
8691
8692 return true;
8693}
8694
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008695CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008696 // C++11 [class.copy]p20:
8697 // If the definition of a class X does not explicitly declare a move
8698 // assignment operator, one will be implicitly declared as defaulted
8699 // if and only if:
8700 //
8701 // - [first 4 bullets]
8702 assert(ClassDecl->needsImplicitMoveAssignment());
8703
Richard Smithafb49182012-11-29 01:34:07 +00008704 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8705 if (DSM.isAlreadyBeingDeclared())
8706 return 0;
8707
Richard Smith1c931be2012-04-02 18:40:40 +00008708 // [Checked after we build the declaration]
8709 // - the move assignment operator would not be implicitly defined as
8710 // deleted,
8711
8712 // [DR1402]:
8713 // - X has no direct or indirect virtual base class with a non-trivial
8714 // move assignment operator, and
8715 // - each of X's non-static data members and direct or virtual base classes
8716 // has a type that either has a move assignment operator or is trivially
8717 // copyable.
8718 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8719 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8720 ClassDecl->setFailedImplicitMoveAssignment();
8721 return 0;
8722 }
8723
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008724 // Note: The following rules are largely analoguous to the move
8725 // constructor rules.
8726
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008727 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8728 QualType RetType = Context.getLValueReferenceType(ArgType);
8729 ArgType = Context.getRValueReferenceType(ArgType);
8730
8731 // An implicitly-declared move assignment operator is an inline public
8732 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008733 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8734 SourceLocation ClassLoc = ClassDecl->getLocation();
8735 DeclarationNameInfo NameInfo(Name, ClassLoc);
8736 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008737 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008738 /*TInfo=*/0, /*isStatic=*/false,
8739 /*StorageClassAsWritten=*/SC_None,
8740 /*isInline=*/true,
8741 /*isConstexpr=*/false,
8742 SourceLocation());
8743 MoveAssignment->setAccess(AS_public);
8744 MoveAssignment->setDefaulted();
8745 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008746
Richard Smithb9d0b762012-07-27 04:22:15 +00008747 // Build an exception specification pointing back at this member.
8748 FunctionProtoType::ExtProtoInfo EPI;
8749 EPI.ExceptionSpecType = EST_Unevaluated;
8750 EPI.ExceptionSpecDecl = MoveAssignment;
8751 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8752
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008753 // Add the parameter to the operator.
8754 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8755 ClassLoc, ClassLoc, /*Id=*/0,
8756 ArgType, /*TInfo=*/0,
8757 SC_None,
8758 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008759 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008760
Richard Smithbc2a35d2012-12-08 08:32:28 +00008761 AddOverriddenMethods(ClassDecl, MoveAssignment);
8762
8763 MoveAssignment->setTrivial(
8764 ClassDecl->needsOverloadResolutionForMoveAssignment()
8765 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8766 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008767
8768 // C++0x [class.copy]p9:
8769 // If the definition of a class X does not explicitly declare a move
8770 // assignment operator, one will be implicitly declared as defaulted if and
8771 // only if:
8772 // [...]
8773 // - the move assignment operator would not be implicitly defined as
8774 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008775 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008776 // Cache this result so that we don't try to generate this over and over
8777 // on every lookup, leaking memory and wasting time.
8778 ClassDecl->setFailedImplicitMoveAssignment();
8779 return 0;
8780 }
8781
Richard Smithbc2a35d2012-12-08 08:32:28 +00008782 // Note that we have added this copy-assignment operator.
8783 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8784
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008785 if (Scope *S = getScopeForContext(ClassDecl))
8786 PushOnScopeChains(MoveAssignment, S, false);
8787 ClassDecl->addDecl(MoveAssignment);
8788
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008789 return MoveAssignment;
8790}
8791
8792void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8793 CXXMethodDecl *MoveAssignOperator) {
8794 assert((MoveAssignOperator->isDefaulted() &&
8795 MoveAssignOperator->isOverloadedOperator() &&
8796 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008797 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8798 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008799 "DefineImplicitMoveAssignment called for wrong function");
8800
8801 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8802
8803 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8804 MoveAssignOperator->setInvalidDecl();
8805 return;
8806 }
8807
8808 MoveAssignOperator->setUsed();
8809
Eli Friedman9a14db32012-10-18 20:14:08 +00008810 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008811 DiagnosticErrorTrap Trap(Diags);
8812
8813 // C++0x [class.copy]p28:
8814 // The implicitly-defined or move assignment operator for a non-union class
8815 // X performs memberwise move assignment of its subobjects. The direct base
8816 // classes of X are assigned first, in the order of their declaration in the
8817 // base-specifier-list, and then the immediate non-static data members of X
8818 // are assigned, in the order in which they were declared in the class
8819 // definition.
8820
8821 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008822 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008823
8824 // The parameter for the "other" object, which we are move from.
8825 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8826 QualType OtherRefType = Other->getType()->
8827 getAs<RValueReferenceType>()->getPointeeType();
8828 assert(OtherRefType.getQualifiers() == 0 &&
8829 "Bad argument type of defaulted move assignment");
8830
8831 // Our location for everything implicitly-generated.
8832 SourceLocation Loc = MoveAssignOperator->getLocation();
8833
8834 // Construct a reference to the "other" object. We'll be using this
8835 // throughout the generated ASTs.
8836 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8837 assert(OtherRef && "Reference to parameter cannot fail!");
8838 // Cast to rvalue.
8839 OtherRef = CastForMoving(*this, OtherRef);
8840
8841 // Construct the "this" pointer. We'll be using this throughout the generated
8842 // ASTs.
8843 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8844 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008845
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008846 // Assign base classes.
8847 bool Invalid = false;
8848 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8849 E = ClassDecl->bases_end(); Base != E; ++Base) {
8850 // Form the assignment:
8851 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8852 QualType BaseType = Base->getType().getUnqualifiedType();
8853 if (!BaseType->isRecordType()) {
8854 Invalid = true;
8855 continue;
8856 }
8857
8858 CXXCastPath BasePath;
8859 BasePath.push_back(Base);
8860
8861 // Construct the "from" expression, which is an implicit cast to the
8862 // appropriately-qualified base type.
8863 Expr *From = OtherRef;
8864 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008865 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008866
8867 // Dereference "this".
8868 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8869
8870 // Implicitly cast "this" to the appropriately-qualified base type.
8871 To = ImpCastExprToType(To.take(),
8872 Context.getCVRQualifiedType(BaseType,
8873 MoveAssignOperator->getTypeQualifiers()),
8874 CK_UncheckedDerivedToBase,
8875 VK_LValue, &BasePath);
8876
8877 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00008878 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008879 To.get(), From,
8880 /*CopyingBaseSubobject=*/true,
8881 /*Copying=*/false);
8882 if (Move.isInvalid()) {
8883 Diag(CurrentLocation, diag::note_member_synthesized_at)
8884 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8885 MoveAssignOperator->setInvalidDecl();
8886 return;
8887 }
8888
8889 // Success! Record the move.
8890 Statements.push_back(Move.takeAs<Expr>());
8891 }
8892
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008893 // Assign non-static members.
8894 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8895 FieldEnd = ClassDecl->field_end();
8896 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008897 if (Field->isUnnamedBitfield())
8898 continue;
8899
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008900 // Check for members of reference type; we can't move those.
8901 if (Field->getType()->isReferenceType()) {
8902 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8903 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8904 Diag(Field->getLocation(), diag::note_declared_at);
8905 Diag(CurrentLocation, diag::note_member_synthesized_at)
8906 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8907 Invalid = true;
8908 continue;
8909 }
8910
8911 // Check for members of const-qualified, non-class type.
8912 QualType BaseType = Context.getBaseElementType(Field->getType());
8913 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8914 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8915 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8916 Diag(Field->getLocation(), diag::note_declared_at);
8917 Diag(CurrentLocation, diag::note_member_synthesized_at)
8918 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8919 Invalid = true;
8920 continue;
8921 }
8922
8923 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008924 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8925 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008926
8927 QualType FieldType = Field->getType().getNonReferenceType();
8928 if (FieldType->isIncompleteArrayType()) {
8929 assert(ClassDecl->hasFlexibleArrayMember() &&
8930 "Incomplete array type is not valid");
8931 continue;
8932 }
8933
8934 // Build references to the field in the object we're copying from and to.
8935 CXXScopeSpec SS; // Intentionally empty
8936 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8937 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008938 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008939 MemberLookup.resolveKind();
8940 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8941 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008942 SS, SourceLocation(), 0,
8943 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008944 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8945 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008946 SS, SourceLocation(), 0,
8947 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008948 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8949 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8950
8951 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8952 "Member reference with rvalue base must be rvalue except for reference "
8953 "members, which aren't allowed for move assignment.");
8954
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008955 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008956 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008957 To.get(), From.get(),
8958 /*CopyingBaseSubobject=*/false,
8959 /*Copying=*/false);
8960 if (Move.isInvalid()) {
8961 Diag(CurrentLocation, diag::note_member_synthesized_at)
8962 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8963 MoveAssignOperator->setInvalidDecl();
8964 return;
8965 }
Richard Smithe7ce7092012-11-12 23:33:00 +00008966
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008967 // Success! Record the copy.
8968 Statements.push_back(Move.takeAs<Stmt>());
8969 }
8970
8971 if (!Invalid) {
8972 // Add a "return *this;"
8973 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8974
8975 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8976 if (Return.isInvalid())
8977 Invalid = true;
8978 else {
8979 Statements.push_back(Return.takeAs<Stmt>());
8980
8981 if (Trap.hasErrorOccurred()) {
8982 Diag(CurrentLocation, diag::note_member_synthesized_at)
8983 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8984 Invalid = true;
8985 }
8986 }
8987 }
8988
8989 if (Invalid) {
8990 MoveAssignOperator->setInvalidDecl();
8991 return;
8992 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008993
8994 StmtResult Body;
8995 {
8996 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008997 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008998 /*isStmtExpr=*/false);
8999 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9000 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009001 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9002
9003 if (ASTMutationListener *L = getASTMutationListener()) {
9004 L->CompletedImplicitDefinition(MoveAssignOperator);
9005 }
9006}
9007
Richard Smithb9d0b762012-07-27 04:22:15 +00009008Sema::ImplicitExceptionSpecification
9009Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9010 CXXRecordDecl *ClassDecl = MD->getParent();
9011
9012 ImplicitExceptionSpecification ExceptSpec(*this);
9013 if (ClassDecl->isInvalidDecl())
9014 return ExceptSpec;
9015
9016 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9017 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9018 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9019
Douglas Gregor0d405db2010-07-01 20:59:04 +00009020 // C++ [except.spec]p14:
9021 // An implicitly declared special member function (Clause 12) shall have an
9022 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009023 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9024 BaseEnd = ClassDecl->bases_end();
9025 Base != BaseEnd;
9026 ++Base) {
9027 // Virtual bases are handled below.
9028 if (Base->isVirtual())
9029 continue;
9030
Douglas Gregor22584312010-07-02 23:41:54 +00009031 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009032 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009033 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009034 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009035 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009036 }
9037 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9038 BaseEnd = ClassDecl->vbases_end();
9039 Base != BaseEnd;
9040 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009041 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009042 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009043 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009044 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009045 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009046 }
9047 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9048 FieldEnd = ClassDecl->field_end();
9049 Field != FieldEnd;
9050 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009051 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009052 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9053 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009054 LookupCopyingConstructor(FieldClassDecl,
9055 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009056 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009057 }
9058 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009059
Richard Smithb9d0b762012-07-27 04:22:15 +00009060 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009061}
9062
9063CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9064 CXXRecordDecl *ClassDecl) {
9065 // C++ [class.copy]p4:
9066 // If the class definition does not explicitly declare a copy
9067 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009068 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009069
Richard Smithafb49182012-11-29 01:34:07 +00009070 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9071 if (DSM.isAlreadyBeingDeclared())
9072 return 0;
9073
Sean Hunt49634cf2011-05-13 06:10:58 +00009074 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9075 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009076 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009077 if (Const)
9078 ArgType = ArgType.withConst();
9079 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009080
Richard Smith7756afa2012-06-10 05:43:50 +00009081 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9082 CXXCopyConstructor,
9083 Const);
9084
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009085 DeclarationName Name
9086 = Context.DeclarationNames.getCXXConstructorName(
9087 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009088 SourceLocation ClassLoc = ClassDecl->getLocation();
9089 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009090
9091 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009092 // member of its class.
9093 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009094 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009095 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009096 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009097 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009098 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009099
Richard Smithb9d0b762012-07-27 04:22:15 +00009100 // Build an exception specification pointing back at this member.
9101 FunctionProtoType::ExtProtoInfo EPI;
9102 EPI.ExceptionSpecType = EST_Unevaluated;
9103 EPI.ExceptionSpecDecl = CopyConstructor;
9104 CopyConstructor->setType(
9105 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9106
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009107 // Add the parameter to the constructor.
9108 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009109 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009110 /*IdentifierInfo=*/0,
9111 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009112 SC_None,
9113 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009114 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009115
Richard Smithbc2a35d2012-12-08 08:32:28 +00009116 CopyConstructor->setTrivial(
9117 ClassDecl->needsOverloadResolutionForCopyConstructor()
9118 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9119 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009120
Nico Weberafcc96a2012-01-23 03:19:29 +00009121 // C++11 [class.copy]p8:
9122 // ... If the class definition does not explicitly declare a copy
9123 // constructor, there is no user-declared move constructor, and there is no
9124 // user-declared move assignment operator, a copy constructor is implicitly
9125 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009126 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00009127 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00009128
Richard Smithbc2a35d2012-12-08 08:32:28 +00009129 // Note that we have declared this constructor.
9130 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9131
9132 if (Scope *S = getScopeForContext(ClassDecl))
9133 PushOnScopeChains(CopyConstructor, S, false);
9134 ClassDecl->addDecl(CopyConstructor);
9135
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009136 return CopyConstructor;
9137}
9138
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009139void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009140 CXXConstructorDecl *CopyConstructor) {
9141 assert((CopyConstructor->isDefaulted() &&
9142 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009143 !CopyConstructor->doesThisDeclarationHaveABody() &&
9144 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009145 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009146
Anders Carlsson63010a72010-04-23 16:24:12 +00009147 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009148 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009149
Eli Friedman9a14db32012-10-18 20:14:08 +00009150 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009151 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009152
Sean Huntcbb67482011-01-08 20:30:50 +00009153 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009154 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009155 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009156 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009157 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009158 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009159 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009160 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9161 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009162 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009163 /*isStmtExpr=*/false)
9164 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009165 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009166 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009167
9168 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009169 if (ASTMutationListener *L = getASTMutationListener()) {
9170 L->CompletedImplicitDefinition(CopyConstructor);
9171 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009172}
9173
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009174Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009175Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9176 CXXRecordDecl *ClassDecl = MD->getParent();
9177
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009178 // C++ [except.spec]p14:
9179 // An implicitly declared special member function (Clause 12) shall have an
9180 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009181 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009182 if (ClassDecl->isInvalidDecl())
9183 return ExceptSpec;
9184
9185 // Direct base-class constructors.
9186 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9187 BEnd = ClassDecl->bases_end();
9188 B != BEnd; ++B) {
9189 if (B->isVirtual()) // Handled below.
9190 continue;
9191
9192 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9193 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009194 CXXConstructorDecl *Constructor =
9195 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009196 // If this is a deleted function, add it anyway. This might be conformant
9197 // with the standard. This might not. I'm not sure. It might not matter.
9198 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009199 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009200 }
9201 }
9202
9203 // Virtual base-class constructors.
9204 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9205 BEnd = ClassDecl->vbases_end();
9206 B != BEnd; ++B) {
9207 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9208 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009209 CXXConstructorDecl *Constructor =
9210 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009211 // If this is a deleted function, add it anyway. This might be conformant
9212 // with the standard. This might not. I'm not sure. It might not matter.
9213 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009214 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009215 }
9216 }
9217
9218 // Field constructors.
9219 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9220 FEnd = ClassDecl->field_end();
9221 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009222 QualType FieldType = Context.getBaseElementType(F->getType());
9223 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9224 CXXConstructorDecl *Constructor =
9225 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009226 // If this is a deleted function, add it anyway. This might be conformant
9227 // with the standard. This might not. I'm not sure. It might not matter.
9228 // In particular, the problem is that this function never gets called. It
9229 // might just be ill-formed because this function attempts to refer to
9230 // a deleted function here.
9231 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009232 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009233 }
9234 }
9235
9236 return ExceptSpec;
9237}
9238
9239CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9240 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009241 // C++11 [class.copy]p9:
9242 // If the definition of a class X does not explicitly declare a move
9243 // constructor, one will be implicitly declared as defaulted if and only if:
9244 //
9245 // - [first 4 bullets]
9246 assert(ClassDecl->needsImplicitMoveConstructor());
9247
Richard Smithafb49182012-11-29 01:34:07 +00009248 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9249 if (DSM.isAlreadyBeingDeclared())
9250 return 0;
9251
Richard Smith1c931be2012-04-02 18:40:40 +00009252 // [Checked after we build the declaration]
9253 // - the move assignment operator would not be implicitly defined as
9254 // deleted,
9255
9256 // [DR1402]:
9257 // - each of X's non-static data members and direct or virtual base classes
9258 // has a type that either has a move constructor or is trivially copyable.
9259 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9260 ClassDecl->setFailedImplicitMoveConstructor();
9261 return 0;
9262 }
9263
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009264 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9265 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009266
Richard Smith7756afa2012-06-10 05:43:50 +00009267 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9268 CXXMoveConstructor,
9269 false);
9270
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009271 DeclarationName Name
9272 = Context.DeclarationNames.getCXXConstructorName(
9273 Context.getCanonicalType(ClassType));
9274 SourceLocation ClassLoc = ClassDecl->getLocation();
9275 DeclarationNameInfo NameInfo(Name, ClassLoc);
9276
9277 // C++0x [class.copy]p11:
9278 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009279 // member of its class.
9280 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009281 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009282 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009283 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009284 MoveConstructor->setAccess(AS_public);
9285 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009286
Richard Smithb9d0b762012-07-27 04:22:15 +00009287 // Build an exception specification pointing back at this member.
9288 FunctionProtoType::ExtProtoInfo EPI;
9289 EPI.ExceptionSpecType = EST_Unevaluated;
9290 EPI.ExceptionSpecDecl = MoveConstructor;
9291 MoveConstructor->setType(
9292 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9293
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009294 // Add the parameter to the constructor.
9295 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9296 ClassLoc, ClassLoc,
9297 /*IdentifierInfo=*/0,
9298 ArgType, /*TInfo=*/0,
9299 SC_None,
9300 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009301 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009302
Richard Smithbc2a35d2012-12-08 08:32:28 +00009303 MoveConstructor->setTrivial(
9304 ClassDecl->needsOverloadResolutionForMoveConstructor()
9305 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9306 : ClassDecl->hasTrivialMoveConstructor());
9307
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009308 // C++0x [class.copy]p9:
9309 // If the definition of a class X does not explicitly declare a move
9310 // constructor, one will be implicitly declared as defaulted if and only if:
9311 // [...]
9312 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009313 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009314 // Cache this result so that we don't try to generate this over and over
9315 // on every lookup, leaking memory and wasting time.
9316 ClassDecl->setFailedImplicitMoveConstructor();
9317 return 0;
9318 }
9319
9320 // Note that we have declared this constructor.
9321 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9322
9323 if (Scope *S = getScopeForContext(ClassDecl))
9324 PushOnScopeChains(MoveConstructor, S, false);
9325 ClassDecl->addDecl(MoveConstructor);
9326
9327 return MoveConstructor;
9328}
9329
9330void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9331 CXXConstructorDecl *MoveConstructor) {
9332 assert((MoveConstructor->isDefaulted() &&
9333 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009334 !MoveConstructor->doesThisDeclarationHaveABody() &&
9335 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009336 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9337
9338 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9339 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9340
Eli Friedman9a14db32012-10-18 20:14:08 +00009341 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009342 DiagnosticErrorTrap Trap(Diags);
9343
9344 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
9345 Trap.hasErrorOccurred()) {
9346 Diag(CurrentLocation, diag::note_member_synthesized_at)
9347 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9348 MoveConstructor->setInvalidDecl();
9349 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009350 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009351 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9352 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009353 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009354 /*isStmtExpr=*/false)
9355 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009356 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009357 }
9358
9359 MoveConstructor->setUsed();
9360
9361 if (ASTMutationListener *L = getASTMutationListener()) {
9362 L->CompletedImplicitDefinition(MoveConstructor);
9363 }
9364}
9365
Douglas Gregore4e68d42012-02-15 19:33:52 +00009366bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9367 return FD->isDeleted() &&
9368 (FD->isDefaulted() || FD->isImplicit()) &&
9369 isa<CXXMethodDecl>(FD);
9370}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009371
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009372/// \brief Mark the call operator of the given lambda closure type as "used".
9373static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9374 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009375 = cast<CXXMethodDecl>(
9376 *Lambda->lookup(
9377 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009378 CallOperator->setReferenced();
9379 CallOperator->setUsed();
9380}
9381
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009382void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9383 SourceLocation CurrentLocation,
9384 CXXConversionDecl *Conv)
9385{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009386 CXXRecordDecl *Lambda = Conv->getParent();
9387
9388 // Make sure that the lambda call operator is marked used.
9389 markLambdaCallOperatorUsed(*this, Lambda);
9390
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009391 Conv->setUsed();
9392
Eli Friedman9a14db32012-10-18 20:14:08 +00009393 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009394 DiagnosticErrorTrap Trap(Diags);
9395
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009396 // Return the address of the __invoke function.
9397 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9398 CXXMethodDecl *Invoke
9399 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
9400 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9401 VK_LValue, Conv->getLocation()).take();
9402 assert(FunctionRef && "Can't refer to __invoke function?");
9403 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
9404 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
9405 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009406 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009407
9408 // Fill in the __invoke function with a dummy implementation. IR generation
9409 // will fill in the actual details.
9410 Invoke->setUsed();
9411 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009412 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009413
9414 if (ASTMutationListener *L = getASTMutationListener()) {
9415 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009416 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009417 }
9418}
9419
9420void Sema::DefineImplicitLambdaToBlockPointerConversion(
9421 SourceLocation CurrentLocation,
9422 CXXConversionDecl *Conv)
9423{
9424 Conv->setUsed();
9425
Eli Friedman9a14db32012-10-18 20:14:08 +00009426 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009427 DiagnosticErrorTrap Trap(Diags);
9428
Douglas Gregorac1303e2012-02-22 05:02:47 +00009429 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009430 Expr *This = ActOnCXXThis(CurrentLocation).take();
9431 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009432
Eli Friedman23f02672012-03-01 04:01:32 +00009433 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9434 Conv->getLocation(),
9435 Conv, DerefThis);
9436
9437 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9438 // behavior. Note that only the general conversion function does this
9439 // (since it's unusable otherwise); in the case where we inline the
9440 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009441 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009442 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9443 CK_CopyAndAutoreleaseBlockObject,
9444 BuildBlock.get(), 0, VK_RValue);
9445
9446 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009447 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009448 Conv->setInvalidDecl();
9449 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009450 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009451
Douglas Gregorac1303e2012-02-22 05:02:47 +00009452 // Create the return statement that returns the block from the conversion
9453 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009454 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009455 if (Return.isInvalid()) {
9456 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9457 Conv->setInvalidDecl();
9458 return;
9459 }
9460
9461 // Set the body of the conversion function.
9462 Stmt *ReturnS = Return.take();
9463 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
9464 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009465 Conv->getLocation()));
9466
Douglas Gregorac1303e2012-02-22 05:02:47 +00009467 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009468 if (ASTMutationListener *L = getASTMutationListener()) {
9469 L->CompletedImplicitDefinition(Conv);
9470 }
9471}
9472
Douglas Gregorf52757d2012-03-10 06:53:13 +00009473/// \brief Determine whether the given list arguments contains exactly one
9474/// "real" (non-default) argument.
9475static bool hasOneRealArgument(MultiExprArg Args) {
9476 switch (Args.size()) {
9477 case 0:
9478 return false;
9479
9480 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009481 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009482 return false;
9483
9484 // fall through
9485 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009486 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009487 }
9488
9489 return false;
9490}
9491
John McCall60d7b3a2010-08-24 06:29:42 +00009492ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009493Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009494 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009495 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009496 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009497 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009498 unsigned ConstructKind,
9499 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009500 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009501
Douglas Gregor2f599792010-04-02 18:24:57 +00009502 // C++0x [class.copy]p34:
9503 // When certain criteria are met, an implementation is allowed to
9504 // omit the copy/move construction of a class object, even if the
9505 // copy/move constructor and/or destructor for the object have
9506 // side effects. [...]
9507 // - when a temporary class object that has not been bound to a
9508 // reference (12.2) would be copied/moved to a class object
9509 // with the same cv-unqualified type, the copy/move operation
9510 // can be omitted by constructing the temporary object
9511 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009512 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009513 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009514 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009515 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009516 }
Mike Stump1eb44332009-09-09 15:08:12 +00009517
9518 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009519 Elidable, ExprArgs, HadMultipleCandidates,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009520 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009521}
9522
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009523/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9524/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009525ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009526Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9527 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009528 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009529 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009530 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009531 unsigned ConstructKind,
9532 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009533 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009534 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009535 Constructor, Elidable, ExprArgs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00009536 HadMultipleCandidates, /*FIXME*/false,
9537 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009538 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9539 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009540}
9541
Mike Stump1eb44332009-09-09 15:08:12 +00009542bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009543 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009544 MultiExprArg Exprs,
9545 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009546 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009547 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009548 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009549 Exprs, HadMultipleCandidates, false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009550 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009551 if (TempResult.isInvalid())
9552 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009553
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009554 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009555 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009556 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009557 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009558 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009559
Anders Carlssonfe2de492009-08-25 05:18:00 +00009560 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009561}
9562
John McCall68c6c9a2010-02-02 09:10:11 +00009563void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009564 if (VD->isInvalidDecl()) return;
9565
John McCall68c6c9a2010-02-02 09:10:11 +00009566 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009567 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009568 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009569 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009570
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009571 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009572 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009573 CheckDestructorAccess(VD->getLocation(), Destructor,
9574 PDiag(diag::err_access_dtor_var)
9575 << VD->getDeclName()
9576 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009577 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009578
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009579 if (!VD->hasGlobalStorage()) return;
9580
9581 // Emit warning for non-trivial dtor in global scope (a real global,
9582 // class-static, function-static).
9583 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9584
9585 // TODO: this should be re-enabled for static locals by !CXAAtExit
9586 if (!VD->isStaticLocal())
9587 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009588}
9589
Douglas Gregor39da0b82009-09-09 23:08:42 +00009590/// \brief Given a constructor and the set of arguments provided for the
9591/// constructor, convert the arguments and add any required default arguments
9592/// to form a proper call to this constructor.
9593///
9594/// \returns true if an error occurred, false otherwise.
9595bool
9596Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9597 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009598 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009599 SmallVectorImpl<Expr*> &ConvertedArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009600 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009601 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9602 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009603 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009604
9605 const FunctionProtoType *Proto
9606 = Constructor->getType()->getAs<FunctionProtoType>();
9607 assert(Proto && "Constructor without a prototype?");
9608 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009609
9610 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009611 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009612 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009613 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009614 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009615
9616 VariadicCallType CallType =
9617 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009618 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009619 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9620 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009621 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009622 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009623
9624 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9625
Richard Smith831421f2012-06-25 20:30:08 +00009626 CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9627 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009628
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009629 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009630}
9631
Anders Carlsson20d45d22009-12-12 00:32:00 +00009632static inline bool
9633CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9634 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009635 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009636 if (isa<NamespaceDecl>(DC)) {
9637 return SemaRef.Diag(FnDecl->getLocation(),
9638 diag::err_operator_new_delete_declared_in_namespace)
9639 << FnDecl->getDeclName();
9640 }
9641
9642 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009643 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009644 return SemaRef.Diag(FnDecl->getLocation(),
9645 diag::err_operator_new_delete_declared_static)
9646 << FnDecl->getDeclName();
9647 }
9648
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009649 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009650}
9651
Anders Carlsson156c78e2009-12-13 17:53:43 +00009652static inline bool
9653CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9654 CanQualType ExpectedResultType,
9655 CanQualType ExpectedFirstParamType,
9656 unsigned DependentParamTypeDiag,
9657 unsigned InvalidParamTypeDiag) {
9658 QualType ResultType =
9659 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9660
9661 // Check that the result type is not dependent.
9662 if (ResultType->isDependentType())
9663 return SemaRef.Diag(FnDecl->getLocation(),
9664 diag::err_operator_new_delete_dependent_result_type)
9665 << FnDecl->getDeclName() << ExpectedResultType;
9666
9667 // Check that the result type is what we expect.
9668 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9669 return SemaRef.Diag(FnDecl->getLocation(),
9670 diag::err_operator_new_delete_invalid_result_type)
9671 << FnDecl->getDeclName() << ExpectedResultType;
9672
9673 // A function template must have at least 2 parameters.
9674 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9675 return SemaRef.Diag(FnDecl->getLocation(),
9676 diag::err_operator_new_delete_template_too_few_parameters)
9677 << FnDecl->getDeclName();
9678
9679 // The function decl must have at least 1 parameter.
9680 if (FnDecl->getNumParams() == 0)
9681 return SemaRef.Diag(FnDecl->getLocation(),
9682 diag::err_operator_new_delete_too_few_parameters)
9683 << FnDecl->getDeclName();
9684
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009685 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009686 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9687 if (FirstParamType->isDependentType())
9688 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9689 << FnDecl->getDeclName() << ExpectedFirstParamType;
9690
9691 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009692 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009693 ExpectedFirstParamType)
9694 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9695 << FnDecl->getDeclName() << ExpectedFirstParamType;
9696
9697 return false;
9698}
9699
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009700static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009701CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009702 // C++ [basic.stc.dynamic.allocation]p1:
9703 // A program is ill-formed if an allocation function is declared in a
9704 // namespace scope other than global scope or declared static in global
9705 // scope.
9706 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9707 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009708
9709 CanQualType SizeTy =
9710 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9711
9712 // C++ [basic.stc.dynamic.allocation]p1:
9713 // The return type shall be void*. The first parameter shall have type
9714 // std::size_t.
9715 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9716 SizeTy,
9717 diag::err_operator_new_dependent_param_type,
9718 diag::err_operator_new_param_type))
9719 return true;
9720
9721 // C++ [basic.stc.dynamic.allocation]p1:
9722 // The first parameter shall not have an associated default argument.
9723 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009724 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009725 diag::err_operator_new_default_arg)
9726 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9727
9728 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009729}
9730
9731static bool
Richard Smith444d3842012-10-20 08:26:51 +00009732CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009733 // C++ [basic.stc.dynamic.deallocation]p1:
9734 // A program is ill-formed if deallocation functions are declared in a
9735 // namespace scope other than global scope or declared static in global
9736 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009737 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9738 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009739
9740 // C++ [basic.stc.dynamic.deallocation]p2:
9741 // Each deallocation function shall return void and its first parameter
9742 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009743 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9744 SemaRef.Context.VoidPtrTy,
9745 diag::err_operator_delete_dependent_param_type,
9746 diag::err_operator_delete_param_type))
9747 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009748
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009749 return false;
9750}
9751
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009752/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9753/// of this overloaded operator is well-formed. If so, returns false;
9754/// otherwise, emits appropriate diagnostics and returns true.
9755bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009756 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009757 "Expected an overloaded operator declaration");
9758
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009759 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9760
Mike Stump1eb44332009-09-09 15:08:12 +00009761 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009762 // The allocation and deallocation functions, operator new,
9763 // operator new[], operator delete and operator delete[], are
9764 // described completely in 3.7.3. The attributes and restrictions
9765 // found in the rest of this subclause do not apply to them unless
9766 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009767 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009768 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009769
Anders Carlssona3ccda52009-12-12 00:26:23 +00009770 if (Op == OO_New || Op == OO_Array_New)
9771 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009772
9773 // C++ [over.oper]p6:
9774 // An operator function shall either be a non-static member
9775 // function or be a non-member function and have at least one
9776 // parameter whose type is a class, a reference to a class, an
9777 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009778 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9779 if (MethodDecl->isStatic())
9780 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009781 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009782 } else {
9783 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009784 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9785 ParamEnd = FnDecl->param_end();
9786 Param != ParamEnd; ++Param) {
9787 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009788 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9789 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009790 ClassOrEnumParam = true;
9791 break;
9792 }
9793 }
9794
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009795 if (!ClassOrEnumParam)
9796 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009797 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009798 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009799 }
9800
9801 // C++ [over.oper]p8:
9802 // An operator function cannot have default arguments (8.3.6),
9803 // except where explicitly stated below.
9804 //
Mike Stump1eb44332009-09-09 15:08:12 +00009805 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009806 // (C++ [over.call]p1).
9807 if (Op != OO_Call) {
9808 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9809 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009810 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009811 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009812 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009813 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009814 }
9815 }
9816
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009817 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9818 { false, false, false }
9819#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9820 , { Unary, Binary, MemberOnly }
9821#include "clang/Basic/OperatorKinds.def"
9822 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009823
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009824 bool CanBeUnaryOperator = OperatorUses[Op][0];
9825 bool CanBeBinaryOperator = OperatorUses[Op][1];
9826 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009827
9828 // C++ [over.oper]p8:
9829 // [...] Operator functions cannot have more or fewer parameters
9830 // than the number required for the corresponding operator, as
9831 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009832 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009833 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009834 if (Op != OO_Call &&
9835 ((NumParams == 1 && !CanBeUnaryOperator) ||
9836 (NumParams == 2 && !CanBeBinaryOperator) ||
9837 (NumParams < 1) || (NumParams > 2))) {
9838 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009839 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009840 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009841 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009842 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009843 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009844 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009845 assert(CanBeBinaryOperator &&
9846 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009847 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009848 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009849
Chris Lattner416e46f2008-11-21 07:57:12 +00009850 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009851 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009852 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009853
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009854 // Overloaded operators other than operator() cannot be variadic.
9855 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009856 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009857 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009858 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009859 }
9860
9861 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009862 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9863 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009864 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009865 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009866 }
9867
9868 // C++ [over.inc]p1:
9869 // The user-defined function called operator++ implements the
9870 // prefix and postfix ++ operator. If this function is a member
9871 // function with no parameters, or a non-member function with one
9872 // parameter of class or enumeration type, it defines the prefix
9873 // increment operator ++ for objects of that type. If the function
9874 // is a member function with one parameter (which shall be of type
9875 // int) or a non-member function with two parameters (the second
9876 // of which shall be of type int), it defines the postfix
9877 // increment operator ++ for objects of that type.
9878 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9879 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9880 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009881 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009882 ParamIsInt = BT->getKind() == BuiltinType::Int;
9883
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009884 if (!ParamIsInt)
9885 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009886 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009887 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009888 }
9889
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009890 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009891}
Chris Lattner5a003a42008-12-17 07:09:26 +00009892
Sean Hunta6c058d2010-01-13 09:01:02 +00009893/// CheckLiteralOperatorDeclaration - Check whether the declaration
9894/// of this literal operator function is well-formed. If so, returns
9895/// false; otherwise, emits appropriate diagnostics and returns true.
9896bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009897 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009898 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9899 << FnDecl->getDeclName();
9900 return true;
9901 }
9902
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009903 if (FnDecl->isExternC()) {
9904 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9905 return true;
9906 }
9907
Sean Hunta6c058d2010-01-13 09:01:02 +00009908 bool Valid = false;
9909
Richard Smith36f5cfe2012-03-09 08:00:36 +00009910 // This might be the definition of a literal operator template.
9911 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9912 // This might be a specialization of a literal operator template.
9913 if (!TpDecl)
9914 TpDecl = FnDecl->getPrimaryTemplate();
9915
Sean Hunt216c2782010-04-07 23:11:06 +00009916 // template <char...> type operator "" name() is the only valid template
9917 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009918 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009919 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009920 // Must have only one template parameter
9921 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9922 if (Params->size() == 1) {
9923 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009924 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009925
Sean Hunt216c2782010-04-07 23:11:06 +00009926 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009927 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9928 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9929 Valid = true;
9930 }
9931 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009932 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009933 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009934 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9935
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009936 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009937
Sean Hunt30019c02010-04-07 22:57:35 +00009938 // unsigned long long int, long double, and any character type are allowed
9939 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009940 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9941 Context.hasSameType(T, Context.LongDoubleTy) ||
9942 Context.hasSameType(T, Context.CharTy) ||
9943 Context.hasSameType(T, Context.WCharTy) ||
9944 Context.hasSameType(T, Context.Char16Ty) ||
9945 Context.hasSameType(T, Context.Char32Ty)) {
9946 if (++Param == FnDecl->param_end())
9947 Valid = true;
9948 goto FinishedParams;
9949 }
9950
Sean Hunt30019c02010-04-07 22:57:35 +00009951 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009952 const PointerType *PT = T->getAs<PointerType>();
9953 if (!PT)
9954 goto FinishedParams;
9955 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009956 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009957 goto FinishedParams;
9958 T = T.getUnqualifiedType();
9959
9960 // Move on to the second parameter;
9961 ++Param;
9962
9963 // If there is no second parameter, the first must be a const char *
9964 if (Param == FnDecl->param_end()) {
9965 if (Context.hasSameType(T, Context.CharTy))
9966 Valid = true;
9967 goto FinishedParams;
9968 }
9969
9970 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9971 // are allowed as the first parameter to a two-parameter function
9972 if (!(Context.hasSameType(T, Context.CharTy) ||
9973 Context.hasSameType(T, Context.WCharTy) ||
9974 Context.hasSameType(T, Context.Char16Ty) ||
9975 Context.hasSameType(T, Context.Char32Ty)))
9976 goto FinishedParams;
9977
9978 // The second and final parameter must be an std::size_t
9979 T = (*Param)->getType().getUnqualifiedType();
9980 if (Context.hasSameType(T, Context.getSizeType()) &&
9981 ++Param == FnDecl->param_end())
9982 Valid = true;
9983 }
9984
9985 // FIXME: This diagnostic is absolutely terrible.
9986FinishedParams:
9987 if (!Valid) {
9988 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9989 << FnDecl->getDeclName();
9990 return true;
9991 }
9992
Richard Smitha9e88b22012-03-09 08:16:22 +00009993 // A parameter-declaration-clause containing a default argument is not
9994 // equivalent to any of the permitted forms.
9995 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9996 ParamEnd = FnDecl->param_end();
9997 Param != ParamEnd; ++Param) {
9998 if ((*Param)->hasDefaultArg()) {
9999 Diag((*Param)->getDefaultArgRange().getBegin(),
10000 diag::err_literal_operator_default_argument)
10001 << (*Param)->getDefaultArgRange();
10002 break;
10003 }
10004 }
10005
Richard Smith2fb4ae32012-03-08 02:39:21 +000010006 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010007 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10008 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010009 // C++11 [usrlit.suffix]p1:
10010 // Literal suffix identifiers that do not start with an underscore
10011 // are reserved for future standardization.
10012 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010013 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010014
Sean Hunta6c058d2010-01-13 09:01:02 +000010015 return false;
10016}
10017
Douglas Gregor074149e2009-01-05 19:45:36 +000010018/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10019/// linkage specification, including the language and (if present)
10020/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10021/// the location of the language string literal, which is provided
10022/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10023/// the '{' brace. Otherwise, this linkage specification does not
10024/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010025Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10026 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010027 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010028 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010029 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010030 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010031 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010032 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010033 Language = LinkageSpecDecl::lang_cxx;
10034 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010035 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010036 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010037 }
Mike Stump1eb44332009-09-09 15:08:12 +000010038
Chris Lattnercc98eac2008-12-17 07:13:27 +000010039 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010040
Douglas Gregor074149e2009-01-05 19:45:36 +000010041 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010042 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010043 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010044 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010045 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010046}
10047
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010048/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010049/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10050/// valid, it's the position of the closing '}' brace in a linkage
10051/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010052Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010053 Decl *LinkageSpec,
10054 SourceLocation RBraceLoc) {
10055 if (LinkageSpec) {
10056 if (RBraceLoc.isValid()) {
10057 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10058 LSDecl->setRBraceLoc(RBraceLoc);
10059 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010060 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010061 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010062 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010063}
10064
Douglas Gregord308e622009-05-18 20:51:54 +000010065/// \brief Perform semantic analysis for the variable declaration that
10066/// occurs within a C++ catch clause, returning the newly-created
10067/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010068VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010069 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010070 SourceLocation StartLoc,
10071 SourceLocation Loc,
10072 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010073 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010074 QualType ExDeclType = TInfo->getType();
10075
Sebastian Redl4b07b292008-12-22 19:15:10 +000010076 // Arrays and functions decay.
10077 if (ExDeclType->isArrayType())
10078 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10079 else if (ExDeclType->isFunctionType())
10080 ExDeclType = Context.getPointerType(ExDeclType);
10081
10082 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10083 // The exception-declaration shall not denote a pointer or reference to an
10084 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010085 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010086 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010087 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010088 Invalid = true;
10089 }
Douglas Gregord308e622009-05-18 20:51:54 +000010090
Sebastian Redl4b07b292008-12-22 19:15:10 +000010091 QualType BaseType = ExDeclType;
10092 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010093 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010094 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010095 BaseType = Ptr->getPointeeType();
10096 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010097 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010098 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010099 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010100 BaseType = Ref->getPointeeType();
10101 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010102 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010103 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010104 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010105 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010106 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010107
Mike Stump1eb44332009-09-09 15:08:12 +000010108 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010109 RequireNonAbstractType(Loc, ExDeclType,
10110 diag::err_abstract_type_in_decl,
10111 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010112 Invalid = true;
10113
John McCall5a180392010-07-24 00:37:23 +000010114 // Only the non-fragile NeXT runtime currently supports C++ catches
10115 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010116 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010117 QualType T = ExDeclType;
10118 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10119 T = RT->getPointeeType();
10120
10121 if (T->isObjCObjectType()) {
10122 Diag(Loc, diag::err_objc_object_catch);
10123 Invalid = true;
10124 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010125 // FIXME: should this be a test for macosx-fragile specifically?
10126 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010127 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010128 }
10129 }
10130
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010131 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10132 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010133 ExDecl->setExceptionVariable(true);
10134
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010135 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010136 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010137 Invalid = true;
10138
Douglas Gregorc41b8782011-07-06 18:14:43 +000010139 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010140 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +000010141 // C++ [except.handle]p16:
10142 // The object declared in an exception-declaration or, if the
10143 // exception-declaration does not specify a name, a temporary (12.2) is
10144 // copy-initialized (8.5) from the exception object. [...]
10145 // The object is destroyed when the handler exits, after the destruction
10146 // of any automatic objects initialized within the handler.
10147 //
10148 // We just pretend to initialize the object with itself, then make sure
10149 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010150 QualType initType = ExDeclType;
10151
10152 InitializedEntity entity =
10153 InitializedEntity::InitializeVariable(ExDecl);
10154 InitializationKind initKind =
10155 InitializationKind::CreateCopy(Loc, SourceLocation());
10156
10157 Expr *opaqueValue =
10158 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10159 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10160 ExprResult result = sequence.Perform(*this, entity, initKind,
10161 MultiExprArg(&opaqueValue, 1));
10162 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010163 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010164 else {
10165 // If the constructor used was non-trivial, set this as the
10166 // "initializer".
10167 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10168 if (!construct->getConstructor()->isTrivial()) {
10169 Expr *init = MaybeCreateExprWithCleanups(construct);
10170 ExDecl->setInit(init);
10171 }
10172
10173 // And make sure it's destructable.
10174 FinalizeVarWithDestructor(ExDecl, recordType);
10175 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010176 }
10177 }
10178
Douglas Gregord308e622009-05-18 20:51:54 +000010179 if (Invalid)
10180 ExDecl->setInvalidDecl();
10181
10182 return ExDecl;
10183}
10184
10185/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10186/// handler.
John McCalld226f652010-08-21 09:40:31 +000010187Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010188 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010189 bool Invalid = D.isInvalidType();
10190
10191 // Check for unexpanded parameter packs.
10192 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10193 UPPC_ExceptionType)) {
10194 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10195 D.getIdentifierLoc());
10196 Invalid = true;
10197 }
10198
Sebastian Redl4b07b292008-12-22 19:15:10 +000010199 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010200 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010201 LookupOrdinaryName,
10202 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010203 // The scope should be freshly made just for us. There is just no way
10204 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010205 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010206 if (PrevDecl->isTemplateParameter()) {
10207 // Maybe we will complain about the shadowed template parameter.
10208 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010209 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010210 }
10211 }
10212
Chris Lattnereaaebc72009-04-25 08:06:05 +000010213 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010214 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10215 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010216 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010217 }
10218
Douglas Gregor83cb9422010-09-09 17:09:21 +000010219 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010220 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010221 D.getIdentifierLoc(),
10222 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010223 if (Invalid)
10224 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010225
Sebastian Redl4b07b292008-12-22 19:15:10 +000010226 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010227 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010228 PushOnScopeChains(ExDecl, S);
10229 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010230 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010231
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010232 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010233 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010234}
Anders Carlssonfb311762009-03-14 00:25:26 +000010235
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010236Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010237 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010238 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010239 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010240 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010241
Richard Smithe3f470a2012-07-11 22:37:56 +000010242 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10243 return 0;
10244
10245 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10246 AssertMessage, RParenLoc, false);
10247}
10248
10249Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10250 Expr *AssertExpr,
10251 StringLiteral *AssertMessage,
10252 SourceLocation RParenLoc,
10253 bool Failed) {
10254 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10255 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010256 // In a static_assert-declaration, the constant-expression shall be a
10257 // constant expression that can be contextually converted to bool.
10258 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10259 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010260 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010261
Richard Smithdaaefc52011-12-14 23:32:26 +000010262 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010263 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010264 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010265 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010266 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010267
Richard Smithe3f470a2012-07-11 22:37:56 +000010268 if (!Failed && !Cond) {
Richard Smith0cc323c2012-03-05 23:20:05 +000010269 llvm::SmallString<256> MsgBuffer;
10270 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010271 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010272 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010273 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010274 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010275 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010276 }
Mike Stump1eb44332009-09-09 15:08:12 +000010277
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010278 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010279 AssertExpr, AssertMessage, RParenLoc,
10280 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010281
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010282 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010283 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010284}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010285
Douglas Gregor1d869352010-04-07 16:53:43 +000010286/// \brief Perform semantic analysis of the given friend type declaration.
10287///
10288/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010289FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010290 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010291 TypeSourceInfo *TSInfo) {
10292 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10293
10294 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010295 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010296
Richard Smith6b130222011-10-18 21:39:00 +000010297 // C++03 [class.friend]p2:
10298 // An elaborated-type-specifier shall be used in a friend declaration
10299 // for a class.*
10300 //
10301 // * The class-key of the elaborated-type-specifier is required.
10302 if (!ActiveTemplateInstantiations.empty()) {
10303 // Do not complain about the form of friend template types during
10304 // template instantiation; we will already have complained when the
10305 // template was declared.
10306 } else if (!T->isElaboratedTypeSpecifier()) {
10307 // If we evaluated the type to a record type, suggest putting
10308 // a tag in front.
10309 if (const RecordType *RT = T->getAs<RecordType>()) {
10310 RecordDecl *RD = RT->getDecl();
10311
10312 std::string InsertionText = std::string(" ") + RD->getKindName();
10313
10314 Diag(TypeRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010315 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +000010316 diag::warn_cxx98_compat_unelaborated_friend_type :
10317 diag::ext_unelaborated_friend_type)
10318 << (unsigned) RD->getTagKind()
10319 << T
10320 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10321 InsertionText);
10322 } else {
10323 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +000010324 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +000010325 diag::warn_cxx98_compat_nonclass_type_friend :
10326 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010327 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010328 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010329 }
Richard Smith6b130222011-10-18 21:39:00 +000010330 } else if (T->getAs<EnumType>()) {
10331 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +000010332 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +000010333 diag::warn_cxx98_compat_enum_friend :
10334 diag::ext_enum_friend)
10335 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010336 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010337 }
10338
Richard Smithd6f80da2012-09-20 01:31:00 +000010339 // C++11 [class.friend]p3:
10340 // A friend declaration that does not declare a function shall have one
10341 // of the following forms:
10342 // friend elaborated-type-specifier ;
10343 // friend simple-type-specifier ;
10344 // friend typename-specifier ;
10345 if (getLangOpts().CPlusPlus0x && LocStart != FriendLoc)
10346 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10347
Douglas Gregor06245bf2010-04-07 17:57:12 +000010348 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010349 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010350 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010351 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010352}
10353
John McCall9a34edb2010-10-19 01:40:49 +000010354/// Handle a friend tag declaration where the scope specifier was
10355/// templated.
10356Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10357 unsigned TagSpec, SourceLocation TagLoc,
10358 CXXScopeSpec &SS,
10359 IdentifierInfo *Name, SourceLocation NameLoc,
10360 AttributeList *Attr,
10361 MultiTemplateParamsArg TempParamLists) {
10362 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10363
10364 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010365 bool Invalid = false;
10366
10367 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010368 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010369 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010370 TempParamLists.size(),
10371 /*friend*/ true,
10372 isExplicitSpecialization,
10373 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010374 if (TemplateParams->size() > 0) {
10375 // This is a declaration of a class template.
10376 if (Invalid)
10377 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010378
Eric Christopher4110e132011-07-21 05:34:24 +000010379 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10380 SS, Name, NameLoc, Attr,
10381 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010382 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010383 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010384 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010385 } else {
10386 // The "template<>" header is extraneous.
10387 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10388 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10389 isExplicitSpecialization = true;
10390 }
10391 }
10392
10393 if (Invalid) return 0;
10394
John McCall9a34edb2010-10-19 01:40:49 +000010395 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010396 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010397 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010398 isAllExplicitSpecializations = false;
10399 break;
10400 }
10401 }
10402
10403 // FIXME: don't ignore attributes.
10404
10405 // If it's explicit specializations all the way down, just forget
10406 // about the template header and build an appropriate non-templated
10407 // friend. TODO: for source fidelity, remember the headers.
10408 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010409 if (SS.isEmpty()) {
10410 bool Owned = false;
10411 bool IsDependent = false;
10412 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10413 Attr, AS_public,
10414 /*ModulePrivateLoc=*/SourceLocation(),
10415 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010416 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010417 /*ScopedEnumUsesClassTag=*/false,
10418 /*UnderlyingType=*/TypeResult());
10419 }
10420
Douglas Gregor2494dd02011-03-01 01:34:45 +000010421 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010422 ElaboratedTypeKeyword Keyword
10423 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010424 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010425 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010426 if (T.isNull())
10427 return 0;
10428
10429 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10430 if (isa<DependentNameType>(T)) {
10431 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010432 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010433 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010434 TL.setNameLoc(NameLoc);
10435 } else {
10436 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010437 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010438 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010439 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10440 }
10441
10442 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10443 TSI, FriendLoc);
10444 Friend->setAccess(AS_public);
10445 CurContext->addDecl(Friend);
10446 return Friend;
10447 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010448
10449 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10450
10451
John McCall9a34edb2010-10-19 01:40:49 +000010452
10453 // Handle the case of a templated-scope friend class. e.g.
10454 // template <class T> class A<T>::B;
10455 // FIXME: we don't support these right now.
10456 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10457 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10458 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10459 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010460 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010461 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010462 TL.setNameLoc(NameLoc);
10463
10464 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10465 TSI, FriendLoc);
10466 Friend->setAccess(AS_public);
10467 Friend->setUnsupportedFriend(true);
10468 CurContext->addDecl(Friend);
10469 return Friend;
10470}
10471
10472
John McCalldd4a3b02009-09-16 22:47:08 +000010473/// Handle a friend type declaration. This works in tandem with
10474/// ActOnTag.
10475///
10476/// Notes on friend class templates:
10477///
10478/// We generally treat friend class declarations as if they were
10479/// declaring a class. So, for example, the elaborated type specifier
10480/// in a friend declaration is required to obey the restrictions of a
10481/// class-head (i.e. no typedefs in the scope chain), template
10482/// parameters are required to match up with simple template-ids, &c.
10483/// However, unlike when declaring a template specialization, it's
10484/// okay to refer to a template specialization without an empty
10485/// template parameter declaration, e.g.
10486/// friend class A<T>::B<unsigned>;
10487/// We permit this as a special case; if there are any template
10488/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010489/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010490Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010491 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010492 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010493
10494 assert(DS.isFriendSpecified());
10495 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10496
John McCalldd4a3b02009-09-16 22:47:08 +000010497 // Try to convert the decl specifier to a type. This works for
10498 // friend templates because ActOnTag never produces a ClassTemplateDecl
10499 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010500 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010501 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10502 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010503 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010504 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010505
Douglas Gregor6ccab972010-12-16 01:14:37 +000010506 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10507 return 0;
10508
John McCalldd4a3b02009-09-16 22:47:08 +000010509 // This is definitely an error in C++98. It's probably meant to
10510 // be forbidden in C++0x, too, but the specification is just
10511 // poorly written.
10512 //
10513 // The problem is with declarations like the following:
10514 // template <T> friend A<T>::foo;
10515 // where deciding whether a class C is a friend or not now hinges
10516 // on whether there exists an instantiation of A that causes
10517 // 'foo' to equal C. There are restrictions on class-heads
10518 // (which we declare (by fiat) elaborated friend declarations to
10519 // be) that makes this tractable.
10520 //
10521 // FIXME: handle "template <> friend class A<T>;", which
10522 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010523 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010524 Diag(Loc, diag::err_tagless_friend_type_template)
10525 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010526 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010527 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010528
John McCall02cace72009-08-28 07:59:38 +000010529 // C++98 [class.friend]p1: A friend of a class is a function
10530 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010531 // This is fixed in DR77, which just barely didn't make the C++03
10532 // deadline. It's also a very silly restriction that seriously
10533 // affects inner classes and which nobody else seems to implement;
10534 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010535 //
10536 // But note that we could warn about it: it's always useless to
10537 // friend one of your own members (it's not, however, worthless to
10538 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010539
John McCalldd4a3b02009-09-16 22:47:08 +000010540 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010541 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010542 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010543 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010544 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010545 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010546 DS.getFriendSpecLoc());
10547 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010548 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010549
10550 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010551 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010552
John McCalldd4a3b02009-09-16 22:47:08 +000010553 D->setAccess(AS_public);
10554 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010555
John McCalld226f652010-08-21 09:40:31 +000010556 return D;
John McCall02cace72009-08-28 07:59:38 +000010557}
10558
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010559Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010560 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010561 const DeclSpec &DS = D.getDeclSpec();
10562
10563 assert(DS.isFriendSpecified());
10564 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10565
10566 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010567 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010568
10569 // C++ [class.friend]p1
10570 // A friend of a class is a function or class....
10571 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010572 // It *doesn't* see through dependent types, which is correct
10573 // according to [temp.arg.type]p3:
10574 // If a declaration acquires a function type through a
10575 // type dependent on a template-parameter and this causes
10576 // a declaration that does not use the syntactic form of a
10577 // function declarator to have a function type, the program
10578 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010579 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010580 Diag(Loc, diag::err_unexpected_friend);
10581
10582 // It might be worthwhile to try to recover by creating an
10583 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010584 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010585 }
10586
10587 // C++ [namespace.memdef]p3
10588 // - If a friend declaration in a non-local class first declares a
10589 // class or function, the friend class or function is a member
10590 // of the innermost enclosing namespace.
10591 // - The name of the friend is not found by simple name lookup
10592 // until a matching declaration is provided in that namespace
10593 // scope (either before or after the class declaration granting
10594 // friendship).
10595 // - If a friend function is called, its name may be found by the
10596 // name lookup that considers functions from namespaces and
10597 // classes associated with the types of the function arguments.
10598 // - When looking for a prior declaration of a class or a function
10599 // declared as a friend, scopes outside the innermost enclosing
10600 // namespace scope are not considered.
10601
John McCall337ec3d2010-10-12 23:13:28 +000010602 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010603 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10604 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010605 assert(Name);
10606
Douglas Gregor6ccab972010-12-16 01:14:37 +000010607 // Check for unexpanded parameter packs.
10608 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10609 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10610 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10611 return 0;
10612
John McCall67d1a672009-08-06 02:15:43 +000010613 // The context we found the declaration in, or in which we should
10614 // create the declaration.
10615 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010616 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010617 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010618 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010619
John McCall337ec3d2010-10-12 23:13:28 +000010620 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010621
John McCall337ec3d2010-10-12 23:13:28 +000010622 // There are four cases here.
10623 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010624 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010625 // there as appropriate.
10626 // Recover from invalid scope qualifiers as if they just weren't there.
10627 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010628 // C++0x [namespace.memdef]p3:
10629 // If the name in a friend declaration is neither qualified nor
10630 // a template-id and the declaration is a function or an
10631 // elaborated-type-specifier, the lookup to determine whether
10632 // the entity has been previously declared shall not consider
10633 // any scopes outside the innermost enclosing namespace.
10634 // C++0x [class.friend]p11:
10635 // If a friend declaration appears in a local class and the name
10636 // specified is an unqualified name, a prior declaration is
10637 // looked up without considering scopes that are outside the
10638 // innermost enclosing non-class scope. For a friend function
10639 // declaration, if there is no prior declaration, the program is
10640 // ill-formed.
10641 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010642 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010643
John McCall29ae6e52010-10-13 05:45:15 +000010644 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010645 DC = CurContext;
10646 while (true) {
10647 // Skip class contexts. If someone can cite chapter and verse
10648 // for this behavior, that would be nice --- it's what GCC and
10649 // EDG do, and it seems like a reasonable intent, but the spec
10650 // really only says that checks for unqualified existing
10651 // declarations should stop at the nearest enclosing namespace,
10652 // not that they should only consider the nearest enclosing
10653 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010654 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010655 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010656
John McCall68263142009-11-18 22:49:29 +000010657 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010658
10659 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010660 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010661 break;
John McCall29ae6e52010-10-13 05:45:15 +000010662
John McCall8a407372010-10-14 22:22:28 +000010663 if (isTemplateId) {
10664 if (isa<TranslationUnitDecl>(DC)) break;
10665 } else {
10666 if (DC->isFileContext()) break;
10667 }
John McCall67d1a672009-08-06 02:15:43 +000010668 DC = DC->getParent();
10669 }
10670
10671 // C++ [class.friend]p1: A friend of a class is a function or
10672 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010673 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010674 // Most C++ 98 compilers do seem to give an error here, so
10675 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010676 if (!Previous.empty() && DC->Equals(CurContext))
10677 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010678 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010679 diag::warn_cxx98_compat_friend_is_member :
10680 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010681
John McCall380aaa42010-10-13 06:22:15 +000010682 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010683
Douglas Gregor883af832011-10-10 01:11:59 +000010684 // C++ [class.friend]p6:
10685 // A function can be defined in a friend declaration of a class if and
10686 // only if the class is a non-local class (9.8), the function name is
10687 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010688 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010689 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10690 }
10691
John McCall337ec3d2010-10-12 23:13:28 +000010692 // - There's a non-dependent scope specifier, in which case we
10693 // compute it and do a previous lookup there for a function
10694 // or function template.
10695 } else if (!SS.getScopeRep()->isDependent()) {
10696 DC = computeDeclContext(SS);
10697 if (!DC) return 0;
10698
10699 if (RequireCompleteDeclContext(SS, DC)) return 0;
10700
10701 LookupQualifiedName(Previous, DC);
10702
10703 // Ignore things found implicitly in the wrong scope.
10704 // TODO: better diagnostics for this case. Suggesting the right
10705 // qualified scope would be nice...
10706 LookupResult::Filter F = Previous.makeFilter();
10707 while (F.hasNext()) {
10708 NamedDecl *D = F.next();
10709 if (!DC->InEnclosingNamespaceSetOf(
10710 D->getDeclContext()->getRedeclContext()))
10711 F.erase();
10712 }
10713 F.done();
10714
10715 if (Previous.empty()) {
10716 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010717 Diag(Loc, diag::err_qualified_friend_not_found)
10718 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010719 return 0;
10720 }
10721
10722 // C++ [class.friend]p1: A friend of a class is a function or
10723 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010724 if (DC->Equals(CurContext))
10725 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010726 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010727 diag::warn_cxx98_compat_friend_is_member :
10728 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010729
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010730 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010731 // C++ [class.friend]p6:
10732 // A function can be defined in a friend declaration of a class if and
10733 // only if the class is a non-local class (9.8), the function name is
10734 // unqualified, and the function has namespace scope.
10735 SemaDiagnosticBuilder DB
10736 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10737
10738 DB << SS.getScopeRep();
10739 if (DC->isFileContext())
10740 DB << FixItHint::CreateRemoval(SS.getRange());
10741 SS.clear();
10742 }
John McCall337ec3d2010-10-12 23:13:28 +000010743
10744 // - There's a scope specifier that does not match any template
10745 // parameter lists, in which case we use some arbitrary context,
10746 // create a method or method template, and wait for instantiation.
10747 // - There's a scope specifier that does match some template
10748 // parameter lists, which we don't handle right now.
10749 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010750 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010751 // C++ [class.friend]p6:
10752 // A function can be defined in a friend declaration of a class if and
10753 // only if the class is a non-local class (9.8), the function name is
10754 // unqualified, and the function has namespace scope.
10755 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10756 << SS.getScopeRep();
10757 }
10758
John McCall337ec3d2010-10-12 23:13:28 +000010759 DC = CurContext;
10760 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010761 }
Douglas Gregor883af832011-10-10 01:11:59 +000010762
John McCall29ae6e52010-10-13 05:45:15 +000010763 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010764 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010765 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10766 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10767 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010768 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010769 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10770 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010771 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010772 }
John McCall67d1a672009-08-06 02:15:43 +000010773 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010774
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010775 // FIXME: This is an egregious hack to cope with cases where the scope stack
10776 // does not contain the declaration context, i.e., in an out-of-line
10777 // definition of a class.
10778 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10779 if (!DCScope) {
10780 FakeDCScope.setEntity(DC);
10781 DCScope = &FakeDCScope;
10782 }
10783
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010784 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010785 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010786 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010787 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010788
Douglas Gregor182ddf02009-09-28 00:08:27 +000010789 assert(ND->getDeclContext() == DC);
10790 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010791
John McCallab88d972009-08-31 22:39:49 +000010792 // Add the function declaration to the appropriate lookup tables,
10793 // adjusting the redeclarations list as necessary. We don't
10794 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010795 //
John McCallab88d972009-08-31 22:39:49 +000010796 // Also update the scope-based lookup if the target context's
10797 // lookup context is in lexical scope.
10798 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010799 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010800 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010801 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010802 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010803 }
John McCall02cace72009-08-28 07:59:38 +000010804
10805 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010806 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010807 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010808 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010809 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010810
John McCall1f2e1a92012-08-10 03:15:35 +000010811 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010812 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010813 } else {
10814 if (DC->isRecord()) CheckFriendAccess(ND);
10815
John McCall6102ca12010-10-16 06:59:13 +000010816 FunctionDecl *FD;
10817 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10818 FD = FTD->getTemplatedDecl();
10819 else
10820 FD = cast<FunctionDecl>(ND);
10821
10822 // Mark templated-scope function declarations as unsupported.
10823 if (FD->getNumTemplateParameterLists())
10824 FrD->setUnsupportedFriend(true);
10825 }
John McCall337ec3d2010-10-12 23:13:28 +000010826
John McCalld226f652010-08-21 09:40:31 +000010827 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010828}
10829
John McCalld226f652010-08-21 09:40:31 +000010830void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10831 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010832
Sebastian Redl50de12f2009-03-24 22:27:57 +000010833 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10834 if (!Fn) {
10835 Diag(DelLoc, diag::err_deleted_non_function);
10836 return;
10837 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010838 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010839 // Don't consider the implicit declaration we generate for explicit
10840 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010841 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10842 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010843 Diag(DelLoc, diag::err_deleted_decl_not_first);
10844 Diag(Prev->getLocation(), diag::note_previous_declaration);
10845 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010846 // If the declaration wasn't the first, we delete the function anyway for
10847 // recovery.
10848 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010849 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010850}
Sebastian Redl13e88542009-04-27 21:33:24 +000010851
Sean Hunte4246a62011-05-12 06:15:49 +000010852void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10853 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10854
10855 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010856 if (MD->getParent()->isDependentType()) {
10857 MD->setDefaulted();
10858 MD->setExplicitlyDefaulted();
10859 return;
10860 }
10861
Sean Hunte4246a62011-05-12 06:15:49 +000010862 CXXSpecialMember Member = getSpecialMember(MD);
10863 if (Member == CXXInvalid) {
10864 Diag(DefaultLoc, diag::err_default_special_members);
10865 return;
10866 }
10867
10868 MD->setDefaulted();
10869 MD->setExplicitlyDefaulted();
10870
Sean Huntcd10dec2011-05-23 23:14:04 +000010871 // If this definition appears within the record, do the checking when
10872 // the record is complete.
10873 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000010874 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000010875 // Find the uninstantiated declaration that actually had the '= default'
10876 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000010877 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000010878
10879 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010880 return;
10881
Richard Smithb9d0b762012-07-27 04:22:15 +000010882 CheckExplicitlyDefaultedSpecialMember(MD);
10883
Sean Hunte4246a62011-05-12 06:15:49 +000010884 switch (Member) {
10885 case CXXDefaultConstructor: {
10886 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010887 if (!CD->isInvalidDecl())
10888 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10889 break;
10890 }
10891
10892 case CXXCopyConstructor: {
10893 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010894 if (!CD->isInvalidDecl())
10895 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010896 break;
10897 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010898
Sean Hunt2b188082011-05-14 05:23:28 +000010899 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010900 if (!MD->isInvalidDecl())
10901 DefineImplicitCopyAssignment(DefaultLoc, MD);
10902 break;
10903 }
10904
Sean Huntcb45a0f2011-05-12 22:46:25 +000010905 case CXXDestructor: {
10906 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010907 if (!DD->isInvalidDecl())
10908 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010909 break;
10910 }
10911
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010912 case CXXMoveConstructor: {
10913 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010914 if (!CD->isInvalidDecl())
10915 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010916 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010917 }
Sean Hunt82713172011-05-25 23:16:36 +000010918
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010919 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010920 if (!MD->isInvalidDecl())
10921 DefineImplicitMoveAssignment(DefaultLoc, MD);
10922 break;
10923 }
10924
10925 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010926 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010927 }
10928 } else {
10929 Diag(DefaultLoc, diag::err_default_special_members);
10930 }
10931}
10932
Sebastian Redl13e88542009-04-27 21:33:24 +000010933static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010934 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010935 Stmt *SubStmt = *CI;
10936 if (!SubStmt)
10937 continue;
10938 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010939 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010940 diag::err_return_in_constructor_handler);
10941 if (!isa<Expr>(SubStmt))
10942 SearchForReturnInStmt(Self, SubStmt);
10943 }
10944}
10945
10946void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10947 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10948 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10949 SearchForReturnInStmt(*this, Handler);
10950 }
10951}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010952
Mike Stump1eb44332009-09-09 15:08:12 +000010953bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010954 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010955 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10956 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010957
Chandler Carruth73857792010-02-15 11:53:20 +000010958 if (Context.hasSameType(NewTy, OldTy) ||
10959 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010960 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010961
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010962 // Check if the return types are covariant
10963 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010964
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010965 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010966 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10967 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010968 NewClassTy = NewPT->getPointeeType();
10969 OldClassTy = OldPT->getPointeeType();
10970 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010971 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10972 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10973 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10974 NewClassTy = NewRT->getPointeeType();
10975 OldClassTy = OldRT->getPointeeType();
10976 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010977 }
10978 }
Mike Stump1eb44332009-09-09 15:08:12 +000010979
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010980 // The return types aren't either both pointers or references to a class type.
10981 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010982 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010983 diag::err_different_return_type_for_overriding_virtual_function)
10984 << New->getDeclName() << NewTy << OldTy;
10985 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010986
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010987 return true;
10988 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010989
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010990 // C++ [class.virtual]p6:
10991 // If the return type of D::f differs from the return type of B::f, the
10992 // class type in the return type of D::f shall be complete at the point of
10993 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010994 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10995 if (!RT->isBeingDefined() &&
10996 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000010997 diag::err_covariant_return_incomplete,
10998 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010999 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011000 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011001
Douglas Gregora4923eb2009-11-16 21:35:15 +000011002 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011003 // Check if the new class derives from the old class.
11004 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11005 Diag(New->getLocation(),
11006 diag::err_covariant_return_not_derived)
11007 << New->getDeclName() << NewTy << OldTy;
11008 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11009 return true;
11010 }
Mike Stump1eb44332009-09-09 15:08:12 +000011011
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011012 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011013 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011014 diag::err_covariant_return_inaccessible_base,
11015 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11016 // FIXME: Should this point to the return type?
11017 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011018 // FIXME: this note won't trigger for delayed access control
11019 // diagnostics, and it's impossible to get an undelayed error
11020 // here from access control during the original parse because
11021 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011022 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11023 return true;
11024 }
11025 }
Mike Stump1eb44332009-09-09 15:08:12 +000011026
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011027 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011028 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011029 Diag(New->getLocation(),
11030 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011031 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011032 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11033 return true;
11034 };
Mike Stump1eb44332009-09-09 15:08:12 +000011035
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011036
11037 // The new class type must have the same or less qualifiers as the old type.
11038 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11039 Diag(New->getLocation(),
11040 diag::err_covariant_return_type_class_type_more_qualified)
11041 << New->getDeclName() << NewTy << OldTy;
11042 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11043 return true;
11044 };
Mike Stump1eb44332009-09-09 15:08:12 +000011045
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011046 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011047}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011048
Douglas Gregor4ba31362009-12-01 17:24:26 +000011049/// \brief Mark the given method pure.
11050///
11051/// \param Method the method to be marked pure.
11052///
11053/// \param InitRange the source range that covers the "0" initializer.
11054bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011055 SourceLocation EndLoc = InitRange.getEnd();
11056 if (EndLoc.isValid())
11057 Method->setRangeEnd(EndLoc);
11058
Douglas Gregor4ba31362009-12-01 17:24:26 +000011059 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11060 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011061 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011062 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011063
11064 if (!Method->isInvalidDecl())
11065 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11066 << Method->getDeclName() << InitRange;
11067 return true;
11068}
11069
Douglas Gregor552e2992012-02-21 02:22:07 +000011070/// \brief Determine whether the given declaration is a static data member.
11071static bool isStaticDataMember(Decl *D) {
11072 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11073 if (!Var)
11074 return false;
11075
11076 return Var->isStaticDataMember();
11077}
John McCall731ad842009-12-19 09:28:58 +000011078/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11079/// an initializer for the out-of-line declaration 'Dcl'. The scope
11080/// is a fresh scope pushed for just this purpose.
11081///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011082/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11083/// static data member of class X, names should be looked up in the scope of
11084/// class X.
John McCalld226f652010-08-21 09:40:31 +000011085void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011086 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011087 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011088
John McCall731ad842009-12-19 09:28:58 +000011089 // We should only get called for declarations with scope specifiers, like:
11090 // int foo::bar;
11091 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011092 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011093
11094 // If we are parsing the initializer for a static data member, push a
11095 // new expression evaluation context that is associated with this static
11096 // data member.
11097 if (isStaticDataMember(D))
11098 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011099}
11100
11101/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011102/// initializer for the out-of-line declaration 'D'.
11103void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011104 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011105 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011106
Douglas Gregor552e2992012-02-21 02:22:07 +000011107 if (isStaticDataMember(D))
11108 PopExpressionEvaluationContext();
11109
John McCall731ad842009-12-19 09:28:58 +000011110 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011111 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011112}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011113
11114/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11115/// C++ if/switch/while/for statement.
11116/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011117DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011118 // C++ 6.4p2:
11119 // The declarator shall not specify a function or an array.
11120 // The type-specifier-seq shall not contain typedef and shall not declare a
11121 // new class or enumeration.
11122 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11123 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011124
11125 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011126 if (!Dcl)
11127 return true;
11128
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011129 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11130 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011131 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011132 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011133 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011134
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011135 return Dcl;
11136}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011137
Douglas Gregordfe65432011-07-28 19:11:31 +000011138void Sema::LoadExternalVTableUses() {
11139 if (!ExternalSource)
11140 return;
11141
11142 SmallVector<ExternalVTableUse, 4> VTables;
11143 ExternalSource->ReadUsedVTables(VTables);
11144 SmallVector<VTableUse, 4> NewUses;
11145 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11146 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11147 = VTablesUsed.find(VTables[I].Record);
11148 // Even if a definition wasn't required before, it may be required now.
11149 if (Pos != VTablesUsed.end()) {
11150 if (!Pos->second && VTables[I].DefinitionRequired)
11151 Pos->second = true;
11152 continue;
11153 }
11154
11155 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11156 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11157 }
11158
11159 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11160}
11161
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011162void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11163 bool DefinitionRequired) {
11164 // Ignore any vtable uses in unevaluated operands or for classes that do
11165 // not have a vtable.
11166 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11167 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011168 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011169 return;
11170
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011171 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011172 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011173 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11174 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11175 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11176 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011177 // If we already had an entry, check to see if we are promoting this vtable
11178 // to required a definition. If so, we need to reappend to the VTableUses
11179 // list, since we may have already processed the first entry.
11180 if (DefinitionRequired && !Pos.first->second) {
11181 Pos.first->second = true;
11182 } else {
11183 // Otherwise, we can early exit.
11184 return;
11185 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011186 }
11187
11188 // Local classes need to have their virtual members marked
11189 // immediately. For all other classes, we mark their virtual members
11190 // at the end of the translation unit.
11191 if (Class->isLocalClass())
11192 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011193 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011194 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011195}
11196
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011197bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011198 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011199 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011200 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011201
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011202 // Note: The VTableUses vector could grow as a result of marking
11203 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011204 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011205 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011206 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011207 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011208 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011209 if (!Class)
11210 continue;
11211
11212 SourceLocation Loc = VTableUses[I].second;
11213
Richard Smithb9d0b762012-07-27 04:22:15 +000011214 bool DefineVTable = true;
11215
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011216 // If this class has a key function, but that key function is
11217 // defined in another translation unit, we don't need to emit the
11218 // vtable even though we're using it.
11219 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011220 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011221 switch (KeyFunction->getTemplateSpecializationKind()) {
11222 case TSK_Undeclared:
11223 case TSK_ExplicitSpecialization:
11224 case TSK_ExplicitInstantiationDeclaration:
11225 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011226 DefineVTable = false;
11227 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011228
11229 case TSK_ExplicitInstantiationDefinition:
11230 case TSK_ImplicitInstantiation:
11231 // We will be instantiating the key function.
11232 break;
11233 }
11234 } else if (!KeyFunction) {
11235 // If we have a class with no key function that is the subject
11236 // of an explicit instantiation declaration, suppress the
11237 // vtable; it will live with the explicit instantiation
11238 // definition.
11239 bool IsExplicitInstantiationDeclaration
11240 = Class->getTemplateSpecializationKind()
11241 == TSK_ExplicitInstantiationDeclaration;
11242 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11243 REnd = Class->redecls_end();
11244 R != REnd; ++R) {
11245 TemplateSpecializationKind TSK
11246 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11247 if (TSK == TSK_ExplicitInstantiationDeclaration)
11248 IsExplicitInstantiationDeclaration = true;
11249 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11250 IsExplicitInstantiationDeclaration = false;
11251 break;
11252 }
11253 }
11254
11255 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011256 DefineVTable = false;
11257 }
11258
11259 // The exception specifications for all virtual members may be needed even
11260 // if we are not providing an authoritative form of the vtable in this TU.
11261 // We may choose to emit it available_externally anyway.
11262 if (!DefineVTable) {
11263 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11264 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011265 }
11266
11267 // Mark all of the virtual members of this class as referenced, so
11268 // that we can build a vtable. Then, tell the AST consumer that a
11269 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011270 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011271 MarkVirtualMembersReferenced(Loc, Class);
11272 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11273 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11274
11275 // Optionally warn if we're emitting a weak vtable.
11276 if (Class->getLinkage() == ExternalLinkage &&
11277 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011278 const FunctionDecl *KeyFunctionDef = 0;
11279 if (!KeyFunction ||
11280 (KeyFunction->hasBody(KeyFunctionDef) &&
11281 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011282 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11283 TSK_ExplicitInstantiationDefinition
11284 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11285 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011286 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011287 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011288 VTableUses.clear();
11289
Douglas Gregor78844032011-04-22 22:25:37 +000011290 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011291}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011292
Richard Smithb9d0b762012-07-27 04:22:15 +000011293void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11294 const CXXRecordDecl *RD) {
11295 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11296 E = RD->method_end(); I != E; ++I)
11297 if ((*I)->isVirtual() && !(*I)->isPure())
11298 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11299}
11300
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011301void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11302 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011303 // Mark all functions which will appear in RD's vtable as used.
11304 CXXFinalOverriderMap FinalOverriders;
11305 RD->getFinalOverriders(FinalOverriders);
11306 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11307 E = FinalOverriders.end();
11308 I != E; ++I) {
11309 for (OverridingMethods::const_iterator OI = I->second.begin(),
11310 OE = I->second.end();
11311 OI != OE; ++OI) {
11312 assert(OI->second.size() > 0 && "no final overrider");
11313 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011314
Richard Smithff817f72012-07-07 06:59:51 +000011315 // C++ [basic.def.odr]p2:
11316 // [...] A virtual member function is used if it is not pure. [...]
11317 if (!Overrider->isPure())
11318 MarkFunctionReferenced(Loc, Overrider);
11319 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011320 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011321
11322 // Only classes that have virtual bases need a VTT.
11323 if (RD->getNumVBases() == 0)
11324 return;
11325
11326 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11327 e = RD->bases_end(); i != e; ++i) {
11328 const CXXRecordDecl *Base =
11329 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011330 if (Base->getNumVBases() == 0)
11331 continue;
11332 MarkVirtualMembersReferenced(Loc, Base);
11333 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011334}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011335
11336/// SetIvarInitializers - This routine builds initialization ASTs for the
11337/// Objective-C implementation whose ivars need be initialized.
11338void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011339 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011340 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011341 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011342 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011343 CollectIvarsToConstructOrDestruct(OID, ivars);
11344 if (ivars.empty())
11345 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011346 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011347 for (unsigned i = 0; i < ivars.size(); i++) {
11348 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011349 if (Field->isInvalidDecl())
11350 continue;
11351
Sean Huntcbb67482011-01-08 20:30:50 +000011352 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011353 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11354 InitializationKind InitKind =
11355 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11356
11357 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011358 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011359 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011360 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011361 // Note, MemberInit could actually come back empty if no initialization
11362 // is required (e.g., because it would call a trivial default constructor)
11363 if (!MemberInit.get() || MemberInit.isInvalid())
11364 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011365
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011366 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011367 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11368 SourceLocation(),
11369 MemberInit.takeAs<Expr>(),
11370 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011371 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011372
11373 // Be sure that the destructor is accessible and is marked as referenced.
11374 if (const RecordType *RecordTy
11375 = Context.getBaseElementType(Field->getType())
11376 ->getAs<RecordType>()) {
11377 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011378 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011379 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011380 CheckDestructorAccess(Field->getLocation(), Destructor,
11381 PDiag(diag::err_access_dtor_ivar)
11382 << Context.getBaseElementType(Field->getType()));
11383 }
11384 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011385 }
11386 ObjCImplementation->setIvarInitializers(Context,
11387 AllToInit.data(), AllToInit.size());
11388 }
11389}
Sean Huntfe57eef2011-05-04 05:57:24 +000011390
Sean Huntebcbe1d2011-05-04 23:29:54 +000011391static
11392void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11393 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11394 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11395 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11396 Sema &S) {
11397 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11398 CE = Current.end();
11399 if (Ctor->isInvalidDecl())
11400 return;
11401
Richard Smitha8eaf002012-08-23 06:16:52 +000011402 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11403
11404 // Target may not be determinable yet, for instance if this is a dependent
11405 // call in an uninstantiated template.
11406 if (Target) {
11407 const FunctionDecl *FNTarget = 0;
11408 (void)Target->hasBody(FNTarget);
11409 Target = const_cast<CXXConstructorDecl*>(
11410 cast_or_null<CXXConstructorDecl>(FNTarget));
11411 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011412
11413 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11414 // Avoid dereferencing a null pointer here.
11415 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11416
11417 if (!Current.insert(Canonical))
11418 return;
11419
11420 // We know that beyond here, we aren't chaining into a cycle.
11421 if (!Target || !Target->isDelegatingConstructor() ||
11422 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11423 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11424 Valid.insert(*CI);
11425 Current.clear();
11426 // We've hit a cycle.
11427 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11428 Current.count(TCanonical)) {
11429 // If we haven't diagnosed this cycle yet, do so now.
11430 if (!Invalid.count(TCanonical)) {
11431 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011432 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011433 << Ctor;
11434
Richard Smitha8eaf002012-08-23 06:16:52 +000011435 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011436 if (TCanonical != Canonical)
11437 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11438
11439 CXXConstructorDecl *C = Target;
11440 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011441 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011442 (void)C->getTargetConstructor()->hasBody(FNTarget);
11443 assert(FNTarget && "Ctor cycle through bodiless function");
11444
Richard Smitha8eaf002012-08-23 06:16:52 +000011445 C = const_cast<CXXConstructorDecl*>(
11446 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011447 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11448 }
11449 }
11450
11451 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11452 Invalid.insert(*CI);
11453 Current.clear();
11454 } else {
11455 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11456 }
11457}
11458
11459
Sean Huntfe57eef2011-05-04 05:57:24 +000011460void Sema::CheckDelegatingCtorCycles() {
11461 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11462
Sean Huntebcbe1d2011-05-04 23:29:54 +000011463 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11464 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011465
Douglas Gregor0129b562011-07-27 21:57:17 +000011466 for (DelegatingCtorDeclsType::iterator
11467 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011468 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011469 I != E; ++I)
11470 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011471
11472 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11473 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011474}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011475
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011476namespace {
11477 /// \brief AST visitor that finds references to the 'this' expression.
11478 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11479 Sema &S;
11480
11481 public:
11482 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11483
11484 bool VisitCXXThisExpr(CXXThisExpr *E) {
11485 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11486 << E->isImplicit();
11487 return false;
11488 }
11489 };
11490}
11491
11492bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11493 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11494 if (!TSInfo)
11495 return false;
11496
11497 TypeLoc TL = TSInfo->getTypeLoc();
11498 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11499 if (!ProtoTL)
11500 return false;
11501
11502 // C++11 [expr.prim.general]p3:
11503 // [The expression this] shall not appear before the optional
11504 // cv-qualifier-seq and it shall not appear within the declaration of a
11505 // static member function (although its type and value category are defined
11506 // within a static member function as they are within a non-static member
11507 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011508 // until the complete declarator is known. - end note ]
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011509 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11510 FindCXXThisExpr Finder(*this);
11511
11512 // If the return type came after the cv-qualifier-seq, check it now.
11513 if (Proto->hasTrailingReturn() &&
11514 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11515 return true;
11516
11517 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011518 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11519 return true;
11520
11521 return checkThisInStaticMemberFunctionAttributes(Method);
11522}
11523
11524bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11525 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11526 if (!TSInfo)
11527 return false;
11528
11529 TypeLoc TL = TSInfo->getTypeLoc();
11530 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11531 if (!ProtoTL)
11532 return false;
11533
11534 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11535 FindCXXThisExpr Finder(*this);
11536
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011537 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011538 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011539 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011540 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011541 case EST_DynamicNone:
11542 case EST_MSAny:
11543 case EST_None:
11544 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011545
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011546 case EST_ComputedNoexcept:
11547 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11548 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011549
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011550 case EST_Dynamic:
11551 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011552 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011553 E != EEnd; ++E) {
11554 if (!Finder.TraverseType(*E))
11555 return true;
11556 }
11557 break;
11558 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011559
11560 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011561}
11562
11563bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11564 FindCXXThisExpr Finder(*this);
11565
11566 // Check attributes.
11567 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11568 A != AEnd; ++A) {
11569 // FIXME: This should be emitted by tblgen.
11570 Expr *Arg = 0;
11571 ArrayRef<Expr *> Args;
11572 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11573 Arg = G->getArg();
11574 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11575 Arg = G->getArg();
11576 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11577 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11578 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11579 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11580 else if (ExclusiveLockFunctionAttr *ELF
11581 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11582 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11583 else if (SharedLockFunctionAttr *SLF
11584 = dyn_cast<SharedLockFunctionAttr>(*A))
11585 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11586 else if (ExclusiveTrylockFunctionAttr *ETLF
11587 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11588 Arg = ETLF->getSuccessValue();
11589 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11590 } else if (SharedTrylockFunctionAttr *STLF
11591 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11592 Arg = STLF->getSuccessValue();
11593 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11594 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11595 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11596 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11597 Arg = LR->getArg();
11598 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11599 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11600 else if (ExclusiveLocksRequiredAttr *ELR
11601 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11602 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11603 else if (SharedLocksRequiredAttr *SLR
11604 = dyn_cast<SharedLocksRequiredAttr>(*A))
11605 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11606
11607 if (Arg && !Finder.TraverseStmt(Arg))
11608 return true;
11609
11610 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11611 if (!Finder.TraverseStmt(Args[I]))
11612 return true;
11613 }
11614 }
11615
11616 return false;
11617}
11618
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011619void
11620Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11621 ArrayRef<ParsedType> DynamicExceptions,
11622 ArrayRef<SourceRange> DynamicExceptionRanges,
11623 Expr *NoexceptExpr,
11624 llvm::SmallVectorImpl<QualType> &Exceptions,
11625 FunctionProtoType::ExtProtoInfo &EPI) {
11626 Exceptions.clear();
11627 EPI.ExceptionSpecType = EST;
11628 if (EST == EST_Dynamic) {
11629 Exceptions.reserve(DynamicExceptions.size());
11630 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11631 // FIXME: Preserve type source info.
11632 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11633
11634 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11635 collectUnexpandedParameterPacks(ET, Unexpanded);
11636 if (!Unexpanded.empty()) {
11637 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11638 UPPC_ExceptionType,
11639 Unexpanded);
11640 continue;
11641 }
11642
11643 // Check that the type is valid for an exception spec, and
11644 // drop it if not.
11645 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11646 Exceptions.push_back(ET);
11647 }
11648 EPI.NumExceptions = Exceptions.size();
11649 EPI.Exceptions = Exceptions.data();
11650 return;
11651 }
11652
11653 if (EST == EST_ComputedNoexcept) {
11654 // If an error occurred, there's no expression here.
11655 if (NoexceptExpr) {
11656 assert((NoexceptExpr->isTypeDependent() ||
11657 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11658 Context.BoolTy) &&
11659 "Parser should have made sure that the expression is boolean");
11660 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11661 EPI.ExceptionSpecType = EST_BasicNoexcept;
11662 return;
11663 }
11664
11665 if (!NoexceptExpr->isValueDependent())
11666 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011667 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011668 /*AllowFold*/ false).take();
11669 EPI.NoexceptExpr = NoexceptExpr;
11670 }
11671 return;
11672 }
11673}
11674
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011675/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11676Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11677 // Implicitly declared functions (e.g. copy constructors) are
11678 // __host__ __device__
11679 if (D->isImplicit())
11680 return CFT_HostDevice;
11681
11682 if (D->hasAttr<CUDAGlobalAttr>())
11683 return CFT_Global;
11684
11685 if (D->hasAttr<CUDADeviceAttr>()) {
11686 if (D->hasAttr<CUDAHostAttr>())
11687 return CFT_HostDevice;
11688 else
11689 return CFT_Device;
11690 }
11691
11692 return CFT_Host;
11693}
11694
11695bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11696 CUDAFunctionTarget CalleeTarget) {
11697 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11698 // Callable from the device only."
11699 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11700 return true;
11701
11702 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11703 // Callable from the host only."
11704 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11705 // Callable from the host only."
11706 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11707 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11708 return true;
11709
11710 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11711 return true;
11712
11713 return false;
11714}