blob: 9fbe14a16cb49f233fd3946c345bce1b32fcb4c6 [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"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Eli Friedman7badd242012-02-09 20:13:14 +000019#include "clang/Sema/ScopeInfo.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000020#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000021#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000025#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000027#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000028#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000029#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000030#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000031#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000032#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000033#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000035#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000036#include "clang/Lex/Preprocessor.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000037#include "llvm/ADT/SmallString.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.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
Chris Lattner3d1cee32008-04-08 05:04:30 +0000376// MergeCXXFunctionDecl - Merge two declarations of the same C++
377// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000378// 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();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000520 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
521 CXXSpecialMember NewSM = getSpecialMember(Ctor),
522 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
523 if (NewSM != OldSM) {
524 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
525 << NewParam->getDefaultArgRange() << NewSM;
526 Diag(Old->getLocation(), diag::note_previous_declaration_special)
527 << OldSM;
528 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000529 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000530 }
531 }
532
Richard Smithff234882012-02-20 23:28:05 +0000533 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000534 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000535 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000536 if (New->isConstexpr() != Old->isConstexpr()) {
537 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
538 << New << New->isConstexpr();
539 Diag(Old->getLocation(), diag::note_previous_declaration);
540 Invalid = true;
541 }
542
Douglas Gregore13ad832010-02-12 07:32:17 +0000543 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000544 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000545
Douglas Gregorcda9c672009-02-16 17:45:42 +0000546 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000547}
548
Sebastian Redl60618fa2011-03-12 11:50:43 +0000549/// \brief Merge the exception specifications of two variable declarations.
550///
551/// This is called when there's a redeclaration of a VarDecl. The function
552/// checks if the redeclaration might have an exception specification and
553/// validates compatibility and merges the specs if necessary.
554void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
555 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000556 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000557 return;
558
559 assert(Context.hasSameType(New->getType(), Old->getType()) &&
560 "Should only be called if types are otherwise the same.");
561
562 QualType NewType = New->getType();
563 QualType OldType = Old->getType();
564
565 // We're only interested in pointers and references to functions, as well
566 // as pointers to member functions.
567 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
568 NewType = R->getPointeeType();
569 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
570 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
571 NewType = P->getPointeeType();
572 OldType = OldType->getAs<PointerType>()->getPointeeType();
573 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
574 NewType = M->getPointeeType();
575 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
576 }
577
578 if (!NewType->isFunctionProtoType())
579 return;
580
581 // There's lots of special cases for functions. For function pointers, system
582 // libraries are hopefully not as broken so that we don't need these
583 // workarounds.
584 if (CheckEquivalentExceptionSpec(
585 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
586 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
587 New->setInvalidDecl();
588 }
589}
590
Chris Lattner3d1cee32008-04-08 05:04:30 +0000591/// CheckCXXDefaultArguments - Verify that the default arguments for a
592/// function declaration are well-formed according to C++
593/// [dcl.fct.default].
594void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
595 unsigned NumParams = FD->getNumParams();
596 unsigned p;
597
Douglas Gregorc6889e72012-02-14 22:28:59 +0000598 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
599 isa<CXXMethodDecl>(FD) &&
600 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
601
Chris Lattner3d1cee32008-04-08 05:04:30 +0000602 // Find first parameter with a default argument
603 for (p = 0; p < NumParams; ++p) {
604 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000605 if (Param->hasDefaultArg()) {
606 // C++11 [expr.prim.lambda]p5:
607 // [...] Default arguments (8.3.6) shall not be specified in the
608 // parameter-declaration-clause of a lambda-declarator.
609 //
610 // FIXME: Core issue 974 strikes this sentence, we only provide an
611 // extension warning.
612 if (IsLambda)
613 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
614 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000615 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000616 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000617 }
618
619 // C++ [dcl.fct.default]p4:
620 // In a given function declaration, all parameters
621 // subsequent to a parameter with a default argument shall
622 // have default arguments supplied in this or previous
623 // declarations. A default argument shall not be redefined
624 // by a later declaration (not even to the same value).
625 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000626 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000627 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000628 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000629 if (Param->isInvalidDecl())
630 /* We already complained about this parameter. */;
631 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000632 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000633 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000634 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000635 else
Mike Stump1eb44332009-09-09 15:08:12 +0000636 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000637 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Chris Lattner3d1cee32008-04-08 05:04:30 +0000639 LastMissingDefaultArg = p;
640 }
641 }
642
643 if (LastMissingDefaultArg > 0) {
644 // Some default arguments were missing. Clear out all of the
645 // default arguments up to (and including) the last missing
646 // default argument, so that we leave the function parameters
647 // in a semantically valid state.
648 for (p = 0; p <= LastMissingDefaultArg; ++p) {
649 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000650 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000651 Param->setDefaultArg(0);
652 }
653 }
654 }
655}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000656
Richard Smith9f569cc2011-10-01 02:31:28 +0000657// CheckConstexprParameterTypes - Check whether a function's parameter types
658// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000659// diagnostic and return false.
660static bool CheckConstexprParameterTypes(Sema &SemaRef,
661 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000662 unsigned ArgIndex = 0;
663 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
664 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
665 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
666 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
667 SourceLocation ParamLoc = PD->getLocation();
668 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000669 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000670 diag::err_constexpr_non_literal_param,
671 ArgIndex+1, PD->getSourceRange(),
672 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000673 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000674 }
675 return true;
676}
677
678// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
Richard Smith86c3ae42012-02-13 03:54:03 +0000679// the requirements of a constexpr function definition or a constexpr
680// constructor definition. If so, return true. If not, produce appropriate
681// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000682//
Richard Smith86c3ae42012-02-13 03:54:03 +0000683// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
684bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000685 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
686 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000687 // C++11 [dcl.constexpr]p4:
688 // The definition of a constexpr constructor shall satisfy the following
689 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000690 // - the class shall not have any virtual base classes;
Richard Smith35340502012-01-13 04:54:00 +0000691 const CXXRecordDecl *RD = MD->getParent();
Richard Smith9f569cc2011-10-01 02:31:28 +0000692 if (RD->getNumVBases()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000693 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
694 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
695 << RD->getNumVBases();
696 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
697 E = RD->vbases_end(); I != E; ++I)
Daniel Dunbar96a00142012-03-09 18:35:03 +0000698 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000699 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000700 return false;
701 }
Richard Smith35340502012-01-13 04:54:00 +0000702 }
703
704 if (!isa<CXXConstructorDecl>(NewFD)) {
705 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000706 // The definition of a constexpr function shall satisfy the following
707 // constraints:
708 // - it shall not be virtual;
709 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
710 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000711 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000712
Richard Smith86c3ae42012-02-13 03:54:03 +0000713 // If it's not obvious why this function is virtual, find an overridden
714 // function which uses the 'virtual' keyword.
715 const CXXMethodDecl *WrittenVirtual = Method;
716 while (!WrittenVirtual->isVirtualAsWritten())
717 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
718 if (WrittenVirtual != Method)
719 Diag(WrittenVirtual->getLocation(),
720 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000721 return false;
722 }
723
724 // - its return type shall be a literal type;
725 QualType RT = NewFD->getResultType();
726 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000727 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000728 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000729 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000730 }
731
Richard Smith35340502012-01-13 04:54:00 +0000732 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000733 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000734 return false;
735
Richard Smith9f569cc2011-10-01 02:31:28 +0000736 return true;
737}
738
739/// Check the given declaration statement is legal within a constexpr function
740/// body. C++0x [dcl.constexpr]p3,p4.
741///
742/// \return true if the body is OK, false if we have diagnosed a problem.
743static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
744 DeclStmt *DS) {
745 // C++0x [dcl.constexpr]p3 and p4:
746 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
747 // contain only
748 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
749 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
750 switch ((*DclIt)->getKind()) {
751 case Decl::StaticAssert:
752 case Decl::Using:
753 case Decl::UsingShadow:
754 case Decl::UsingDirective:
755 case Decl::UnresolvedUsingTypename:
756 // - static_assert-declarations
757 // - using-declarations,
758 // - using-directives,
759 continue;
760
761 case Decl::Typedef:
762 case Decl::TypeAlias: {
763 // - typedef declarations and alias-declarations that do not define
764 // classes or enumerations,
765 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
766 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
767 // Don't allow variably-modified types in constexpr functions.
768 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
769 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
770 << TL.getSourceRange() << TL.getType()
771 << isa<CXXConstructorDecl>(Dcl);
772 return false;
773 }
774 continue;
775 }
776
777 case Decl::Enum:
778 case Decl::CXXRecord:
779 // As an extension, we allow the declaration (but not the definition) of
780 // classes and enumerations in all declarations, not just in typedef and
781 // alias declarations.
782 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
783 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
784 << isa<CXXConstructorDecl>(Dcl);
785 return false;
786 }
787 continue;
788
789 case Decl::Var:
790 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
791 << isa<CXXConstructorDecl>(Dcl);
792 return false;
793
794 default:
795 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
796 << isa<CXXConstructorDecl>(Dcl);
797 return false;
798 }
799 }
800
801 return true;
802}
803
804/// Check that the given field is initialized within a constexpr constructor.
805///
806/// \param Dcl The constexpr constructor being checked.
807/// \param Field The field being checked. This may be a member of an anonymous
808/// struct or union nested within the class being checked.
809/// \param Inits All declarations, including anonymous struct/union members and
810/// indirect members, for which any initialization was provided.
811/// \param Diagnosed Set to true if an error is produced.
812static void CheckConstexprCtorInitializer(Sema &SemaRef,
813 const FunctionDecl *Dcl,
814 FieldDecl *Field,
815 llvm::SmallSet<Decl*, 16> &Inits,
816 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000817 if (Field->isUnnamedBitfield())
818 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000819
820 if (Field->isAnonymousStructOrUnion() &&
821 Field->getType()->getAsCXXRecordDecl()->isEmpty())
822 return;
823
Richard Smith9f569cc2011-10-01 02:31:28 +0000824 if (!Inits.count(Field)) {
825 if (!Diagnosed) {
826 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
827 Diagnosed = true;
828 }
829 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
830 } else if (Field->isAnonymousStructOrUnion()) {
831 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
832 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
833 I != E; ++I)
834 // If an anonymous union contains an anonymous struct of which any member
835 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000836 if (!RD->isUnion() || Inits.count(*I))
837 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000838 }
839}
840
841/// Check the body for the given constexpr function declaration only contains
842/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
843///
844/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000845bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000846 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000847 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000848 // The definition of a constexpr function shall satisfy the following
849 // constraints: [...]
850 // - its function-body shall be = delete, = default, or a
851 // compound-statement
852 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000853 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000854 // In the definition of a constexpr constructor, [...]
855 // - its function-body shall not be a function-try-block;
856 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
857 << isa<CXXConstructorDecl>(Dcl);
858 return false;
859 }
860
861 // - its function-body shall be [...] a compound-statement that contains only
862 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
863
864 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
865 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
866 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
867 switch ((*BodyIt)->getStmtClass()) {
868 case Stmt::NullStmtClass:
869 // - null statements,
870 continue;
871
872 case Stmt::DeclStmtClass:
873 // - static_assert-declarations
874 // - using-declarations,
875 // - using-directives,
876 // - typedef declarations and alias-declarations that do not define
877 // classes or enumerations,
878 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
879 return false;
880 continue;
881
882 case Stmt::ReturnStmtClass:
883 // - and exactly one return statement;
884 if (isa<CXXConstructorDecl>(Dcl))
885 break;
886
887 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000888 continue;
889
890 default:
891 break;
892 }
893
894 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
895 << isa<CXXConstructorDecl>(Dcl);
896 return false;
897 }
898
899 if (const CXXConstructorDecl *Constructor
900 = dyn_cast<CXXConstructorDecl>(Dcl)) {
901 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000902 // DR1359:
903 // - every non-variant non-static data member and base class sub-object
904 // shall be initialized;
905 // - if the class is a non-empty union, or for each non-empty anonymous
906 // union member of a non-union class, exactly one non-static data member
907 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000908 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000909 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000910 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
911 return false;
912 }
Richard Smith6e433752011-10-10 16:38:04 +0000913 } else if (!Constructor->isDependentContext() &&
914 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000915 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
916
917 // Skip detailed checking if we have enough initializers, and we would
918 // allow at most one initializer per member.
919 bool AnyAnonStructUnionMembers = false;
920 unsigned Fields = 0;
921 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
922 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000923 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000924 AnyAnonStructUnionMembers = true;
925 break;
926 }
927 }
928 if (AnyAnonStructUnionMembers ||
929 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
930 // Check initialization of non-static data members. Base classes are
931 // always initialized so do not need to be checked. Dependent bases
932 // might not have initializers in the member initializer list.
933 llvm::SmallSet<Decl*, 16> Inits;
934 for (CXXConstructorDecl::init_const_iterator
935 I = Constructor->init_begin(), E = Constructor->init_end();
936 I != E; ++I) {
937 if (FieldDecl *FD = (*I)->getMember())
938 Inits.insert(FD);
939 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
940 Inits.insert(ID->chain_begin(), ID->chain_end());
941 }
942
943 bool Diagnosed = false;
944 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
945 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000946 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000947 if (Diagnosed)
948 return false;
949 }
950 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000951 } else {
952 if (ReturnStmts.empty()) {
953 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
954 return false;
955 }
956 if (ReturnStmts.size() > 1) {
957 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
958 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
959 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
960 return false;
961 }
962 }
963
Richard Smith5ba73e12012-02-04 00:33:54 +0000964 // C++11 [dcl.constexpr]p5:
965 // if no function argument values exist such that the function invocation
966 // substitution would produce a constant expression, the program is
967 // ill-formed; no diagnostic required.
968 // C++11 [dcl.constexpr]p3:
969 // - every constructor call and implicit conversion used in initializing the
970 // return value shall be one of those allowed in a constant expression.
971 // C++11 [dcl.constexpr]p4:
972 // - every constructor involved in initializing non-static data members and
973 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +0000974 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000975 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +0000976 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
977 << isa<CXXConstructorDecl>(Dcl);
978 for (size_t I = 0, N = Diags.size(); I != N; ++I)
979 Diag(Diags[I].first, Diags[I].second);
980 return false;
981 }
982
Richard Smith9f569cc2011-10-01 02:31:28 +0000983 return true;
984}
985
Douglas Gregorb48fe382008-10-31 09:07:45 +0000986/// isCurrentClassName - Determine whether the identifier II is the
987/// name of the class type currently being defined. In the case of
988/// nested classes, this will only return true if II is the name of
989/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000990bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
991 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000992 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000993
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000994 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000995 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000996 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000997 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
998 } else
999 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1000
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001001 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001002 return &II == CurDecl->getIdentifier();
1003 else
1004 return false;
1005}
1006
Mike Stump1eb44332009-09-09 15:08:12 +00001007/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001008///
1009/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1010/// and returns NULL otherwise.
1011CXXBaseSpecifier *
1012Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1013 SourceRange SpecifierRange,
1014 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001015 TypeSourceInfo *TInfo,
1016 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001017 QualType BaseType = TInfo->getType();
1018
Douglas Gregor2943aed2009-03-03 04:44:36 +00001019 // C++ [class.union]p1:
1020 // A union shall not have base classes.
1021 if (Class->isUnion()) {
1022 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1023 << SpecifierRange;
1024 return 0;
1025 }
1026
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001027 if (EllipsisLoc.isValid() &&
1028 !TInfo->getType()->containsUnexpandedParameterPack()) {
1029 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1030 << TInfo->getTypeLoc().getSourceRange();
1031 EllipsisLoc = SourceLocation();
1032 }
1033
Douglas Gregor2943aed2009-03-03 04:44:36 +00001034 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001035 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001036 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001037 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001038
1039 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001040
1041 // Base specifiers must be record types.
1042 if (!BaseType->isRecordType()) {
1043 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1044 return 0;
1045 }
1046
1047 // C++ [class.union]p1:
1048 // A union shall not be used as a base class.
1049 if (BaseType->isUnionType()) {
1050 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1051 return 0;
1052 }
1053
1054 // C++ [class.derived]p2:
1055 // The class-name in a base-specifier shall not be an incompletely
1056 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001057 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001058 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001059 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001060 return 0;
John McCall572fc622010-08-17 07:23:57 +00001061 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001062
Eli Friedman1d954f62009-08-15 21:55:26 +00001063 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001064 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001065 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001066 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001067 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001068 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1069 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001070
Anders Carlsson1d209272011-03-25 14:55:14 +00001071 // C++ [class]p3:
1072 // If a class is marked final and it appears as a base-type-specifier in
1073 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001074 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001075 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1076 << CXXBaseDecl->getDeclName();
1077 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1078 << CXXBaseDecl->getDeclName();
1079 return 0;
1080 }
1081
John McCall572fc622010-08-17 07:23:57 +00001082 if (BaseDecl->isInvalidDecl())
1083 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001084
1085 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001086 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001087 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001088 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001089}
1090
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001091/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1092/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001093/// example:
1094/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001095/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001096BaseResult
John McCalld226f652010-08-21 09:40:31 +00001097Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001098 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001099 ParsedType basetype, SourceLocation BaseLoc,
1100 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001101 if (!classdecl)
1102 return true;
1103
Douglas Gregor40808ce2009-03-09 23:48:35 +00001104 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001105 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001106 if (!Class)
1107 return true;
1108
Nick Lewycky56062202010-07-26 16:56:01 +00001109 TypeSourceInfo *TInfo = 0;
1110 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001111
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001112 if (EllipsisLoc.isInvalid() &&
1113 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001114 UPPC_BaseType))
1115 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001116
Douglas Gregor2943aed2009-03-03 04:44:36 +00001117 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001118 Virtual, Access, TInfo,
1119 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001120 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001121 else
1122 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Douglas Gregor2943aed2009-03-03 04:44:36 +00001124 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001125}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001126
Douglas Gregor2943aed2009-03-03 04:44:36 +00001127/// \brief Performs the actual work of attaching the given base class
1128/// specifiers to a C++ class.
1129bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1130 unsigned NumBases) {
1131 if (NumBases == 0)
1132 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001133
1134 // Used to keep track of which base types we have already seen, so
1135 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001136 // that the key is always the unqualified canonical type of the base
1137 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001138 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1139
1140 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001141 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001142 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001143 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001144 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001145 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001146 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001147
1148 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1149 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001150 // C++ [class.mi]p3:
1151 // A class shall not be specified as a direct base class of a
1152 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001153 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001154 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001155 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001156 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001157
1158 // Delete the duplicate base class specifier; we're going to
1159 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001160 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001161
1162 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001163 } else {
1164 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001165 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001166 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001167 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001168 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1169 if (RD->hasAttr<WeakAttr>())
1170 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001171 }
1172 }
1173
1174 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001175 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001176
1177 // Delete the remaining (good) base class specifiers, since their
1178 // data has been copied into the CXXRecordDecl.
1179 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001180 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001181
1182 return Invalid;
1183}
1184
1185/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1186/// class, after checking whether there are any duplicate base
1187/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001188void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001189 unsigned NumBases) {
1190 if (!ClassDecl || !Bases || !NumBases)
1191 return;
1192
1193 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001194 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001195 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001196}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001197
John McCall3cb0ebd2010-03-10 03:28:59 +00001198static CXXRecordDecl *GetClassForType(QualType T) {
1199 if (const RecordType *RT = T->getAs<RecordType>())
1200 return cast<CXXRecordDecl>(RT->getDecl());
1201 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1202 return ICT->getDecl();
1203 else
1204 return 0;
1205}
1206
Douglas Gregora8f32e02009-10-06 17:59:45 +00001207/// \brief Determine whether the type \p Derived is a C++ class that is
1208/// derived from the type \p Base.
1209bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001210 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001211 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001212
1213 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1214 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001215 return false;
1216
John McCall3cb0ebd2010-03-10 03:28:59 +00001217 CXXRecordDecl *BaseRD = GetClassForType(Base);
1218 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001219 return false;
1220
John McCall86ff3082010-02-04 22:26:26 +00001221 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1222 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001223}
1224
1225/// \brief Determine whether the type \p Derived is a C++ class that is
1226/// derived from the type \p Base.
1227bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001228 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001229 return false;
1230
John McCall3cb0ebd2010-03-10 03:28:59 +00001231 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1232 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001233 return false;
1234
John McCall3cb0ebd2010-03-10 03:28:59 +00001235 CXXRecordDecl *BaseRD = GetClassForType(Base);
1236 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001237 return false;
1238
Douglas Gregora8f32e02009-10-06 17:59:45 +00001239 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1240}
1241
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001242void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001243 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001244 assert(BasePathArray.empty() && "Base path array must be empty!");
1245 assert(Paths.isRecordingPaths() && "Must record paths!");
1246
1247 const CXXBasePath &Path = Paths.front();
1248
1249 // We first go backward and check if we have a virtual base.
1250 // FIXME: It would be better if CXXBasePath had the base specifier for
1251 // the nearest virtual base.
1252 unsigned Start = 0;
1253 for (unsigned I = Path.size(); I != 0; --I) {
1254 if (Path[I - 1].Base->isVirtual()) {
1255 Start = I - 1;
1256 break;
1257 }
1258 }
1259
1260 // Now add all bases.
1261 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001262 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001263}
1264
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001265/// \brief Determine whether the given base path includes a virtual
1266/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001267bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1268 for (CXXCastPath::const_iterator B = BasePath.begin(),
1269 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001270 B != BEnd; ++B)
1271 if ((*B)->isVirtual())
1272 return true;
1273
1274 return false;
1275}
1276
Douglas Gregora8f32e02009-10-06 17:59:45 +00001277/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1278/// conversion (where Derived and Base are class types) is
1279/// well-formed, meaning that the conversion is unambiguous (and
1280/// that all of the base classes are accessible). Returns true
1281/// and emits a diagnostic if the code is ill-formed, returns false
1282/// otherwise. Loc is the location where this routine should point to
1283/// if there is an error, and Range is the source range to highlight
1284/// if there is an error.
1285bool
1286Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001287 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001288 unsigned AmbigiousBaseConvID,
1289 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001290 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001291 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001292 // First, determine whether the path from Derived to Base is
1293 // ambiguous. This is slightly more expensive than checking whether
1294 // the Derived to Base conversion exists, because here we need to
1295 // explore multiple paths to determine if there is an ambiguity.
1296 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1297 /*DetectVirtual=*/false);
1298 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1299 assert(DerivationOkay &&
1300 "Can only be used with a derived-to-base conversion");
1301 (void)DerivationOkay;
1302
1303 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001304 if (InaccessibleBaseID) {
1305 // Check that the base class can be accessed.
1306 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1307 InaccessibleBaseID)) {
1308 case AR_inaccessible:
1309 return true;
1310 case AR_accessible:
1311 case AR_dependent:
1312 case AR_delayed:
1313 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001314 }
John McCall6b2accb2010-02-10 09:31:12 +00001315 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001316
1317 // Build a base path if necessary.
1318 if (BasePath)
1319 BuildBasePathArray(Paths, *BasePath);
1320 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001321 }
1322
1323 // We know that the derived-to-base conversion is ambiguous, and
1324 // we're going to produce a diagnostic. Perform the derived-to-base
1325 // search just one more time to compute all of the possible paths so
1326 // that we can print them out. This is more expensive than any of
1327 // the previous derived-to-base checks we've done, but at this point
1328 // performance isn't as much of an issue.
1329 Paths.clear();
1330 Paths.setRecordingPaths(true);
1331 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1332 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1333 (void)StillOkay;
1334
1335 // Build up a textual representation of the ambiguous paths, e.g.,
1336 // D -> B -> A, that will be used to illustrate the ambiguous
1337 // conversions in the diagnostic. We only print one of the paths
1338 // to each base class subobject.
1339 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1340
1341 Diag(Loc, AmbigiousBaseConvID)
1342 << Derived << Base << PathDisplayStr << Range << Name;
1343 return true;
1344}
1345
1346bool
1347Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001348 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001349 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001350 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001351 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001352 IgnoreAccess ? 0
1353 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001354 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001355 Loc, Range, DeclarationName(),
1356 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001357}
1358
1359
1360/// @brief Builds a string representing ambiguous paths from a
1361/// specific derived class to different subobjects of the same base
1362/// class.
1363///
1364/// This function builds a string that can be used in error messages
1365/// to show the different paths that one can take through the
1366/// inheritance hierarchy to go from the derived class to different
1367/// subobjects of a base class. The result looks something like this:
1368/// @code
1369/// struct D -> struct B -> struct A
1370/// struct D -> struct C -> struct A
1371/// @endcode
1372std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1373 std::string PathDisplayStr;
1374 std::set<unsigned> DisplayedPaths;
1375 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1376 Path != Paths.end(); ++Path) {
1377 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1378 // We haven't displayed a path to this particular base
1379 // class subobject yet.
1380 PathDisplayStr += "\n ";
1381 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1382 for (CXXBasePath::const_iterator Element = Path->begin();
1383 Element != Path->end(); ++Element)
1384 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1385 }
1386 }
1387
1388 return PathDisplayStr;
1389}
1390
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001391//===----------------------------------------------------------------------===//
1392// C++ class member Handling
1393//===----------------------------------------------------------------------===//
1394
Abramo Bagnara6206d532010-06-05 05:09:32 +00001395/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001396bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1397 SourceLocation ASLoc,
1398 SourceLocation ColonLoc,
1399 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001400 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001401 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001402 ASLoc, ColonLoc);
1403 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001404 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001405}
1406
Richard Smitha4b39652012-08-06 03:25:17 +00001407/// CheckOverrideControl - Check C++11 override control semantics.
1408void Sema::CheckOverrideControl(Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001409 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001410
Richard Smitha4b39652012-08-06 03:25:17 +00001411 // Do we know which functions this declaration might be overriding?
1412 bool OverridesAreKnown = !MD ||
1413 (!MD->getParent()->hasAnyDependentBases() &&
1414 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001415
Richard Smitha4b39652012-08-06 03:25:17 +00001416 if (!MD || !MD->isVirtual()) {
1417 if (OverridesAreKnown) {
1418 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1419 Diag(OA->getLocation(),
1420 diag::override_keyword_only_allowed_on_virtual_member_functions)
1421 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1422 D->dropAttr<OverrideAttr>();
1423 }
1424 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1425 Diag(FA->getLocation(),
1426 diag::override_keyword_only_allowed_on_virtual_member_functions)
1427 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1428 D->dropAttr<FinalAttr>();
1429 }
1430 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001431 return;
1432 }
Richard Smitha4b39652012-08-06 03:25:17 +00001433
1434 if (!OverridesAreKnown)
1435 return;
1436
1437 // C++11 [class.virtual]p5:
1438 // If a virtual function is marked with the virt-specifier override and
1439 // does not override a member function of a base class, the program is
1440 // ill-formed.
1441 bool HasOverriddenMethods =
1442 MD->begin_overridden_methods() != MD->end_overridden_methods();
1443 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1444 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1445 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001446}
1447
Richard Smitha4b39652012-08-06 03:25:17 +00001448/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001449/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001450/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001451bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1452 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001453 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001454 return false;
1455
1456 Diag(New->getLocation(), diag::err_final_function_overridden)
1457 << New->getDeclName();
1458 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1459 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001460}
1461
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001462static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001463 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1464 // FIXME: Destruction of ObjC lifetime types has side-effects.
1465 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1466 return !RD->isCompleteDefinition() ||
1467 !RD->hasTrivialDefaultConstructor() ||
1468 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001469 return false;
1470}
1471
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001472/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1473/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001474/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001475/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1476/// present (but parsing it has been deferred).
John McCalld226f652010-08-21 09:40:31 +00001477Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001478Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001479 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001480 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001481 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001482 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001483 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1484 DeclarationName Name = NameInfo.getName();
1485 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001486
1487 // For anonymous bitfields, the location should point to the type.
1488 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001489 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001490
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001491 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001492
John McCall4bde1e12010-06-04 08:34:12 +00001493 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001494 assert(!DS.isFriendSpecified());
1495
Richard Smith1ab0d902011-06-25 02:28:38 +00001496 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001497
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001498 // C++ 9.2p6: A member shall not be declared to have automatic storage
1499 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001500 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1501 // data members and cannot be applied to names declared const or static,
1502 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001503 switch (DS.getStorageClassSpec()) {
1504 case DeclSpec::SCS_unspecified:
1505 case DeclSpec::SCS_typedef:
1506 case DeclSpec::SCS_static:
1507 // FALL THROUGH.
1508 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001509 case DeclSpec::SCS_mutable:
1510 if (isFunc) {
1511 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001512 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001513 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001514 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001515
Sebastian Redla11f42f2008-11-17 23:24:37 +00001516 // FIXME: It would be nicer if the keyword was ignored only for this
1517 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001518 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001519 }
1520 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001521 default:
1522 if (DS.getStorageClassSpecLoc().isValid())
1523 Diag(DS.getStorageClassSpecLoc(),
1524 diag::err_storageclass_invalid_for_member);
1525 else
1526 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1527 D.getMutableDeclSpec().ClearStorageClassSpecs();
1528 }
1529
Sebastian Redl669d5d72008-11-14 23:42:31 +00001530 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1531 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001532 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001533
1534 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001535 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001536 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001537
1538 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001539 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001540 Diag(Loc, diag::err_bad_variable_name)
1541 << Name;
1542 return 0;
1543 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001544
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001545 IdentifierInfo *II = Name.getAsIdentifierInfo();
1546
Douglas Gregorf2503652011-09-21 14:40:46 +00001547 // Member field could not be with "template" keyword.
1548 // So TemplateParameterLists should be empty in this case.
1549 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001550 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001551 if (TemplateParams->size()) {
1552 // There is no such thing as a member field template.
1553 Diag(D.getIdentifierLoc(), diag::err_template_member)
1554 << II
1555 << SourceRange(TemplateParams->getTemplateLoc(),
1556 TemplateParams->getRAngleLoc());
1557 } else {
1558 // There is an extraneous 'template<>' for this member.
1559 Diag(TemplateParams->getTemplateLoc(),
1560 diag::err_template_member_noparams)
1561 << II
1562 << SourceRange(TemplateParams->getTemplateLoc(),
1563 TemplateParams->getRAngleLoc());
1564 }
1565 return 0;
1566 }
1567
Douglas Gregor922fff22010-10-13 22:19:53 +00001568 if (SS.isSet() && !SS.isInvalid()) {
1569 // The user provided a superfluous scope specifier inside a class
1570 // definition:
1571 //
1572 // class X {
1573 // int X::member;
1574 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001575 if (DeclContext *DC = computeDeclContext(SS, false))
1576 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001577 else
1578 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1579 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001580
Douglas Gregor922fff22010-10-13 22:19:53 +00001581 SS.clear();
1582 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001583
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001584 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001585 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001586 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001587 } else {
Richard Smithca523302012-06-10 03:12:00 +00001588 assert(InitStyle == ICIS_NoInit);
Richard Smith7a614d82011-06-11 17:19:42 +00001589
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001590 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001591 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001592 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001593 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001594
1595 // Non-instance-fields can't have a bitfield.
1596 if (BitWidth) {
1597 if (Member->isInvalidDecl()) {
1598 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001599 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001600 // C++ 9.6p3: A bit-field shall not be a static member.
1601 // "static member 'A' cannot be a bit-field"
1602 Diag(Loc, diag::err_static_not_bitfield)
1603 << Name << BitWidth->getSourceRange();
1604 } else if (isa<TypedefDecl>(Member)) {
1605 // "typedef member 'x' cannot be a bit-field"
1606 Diag(Loc, diag::err_typedef_not_bitfield)
1607 << Name << BitWidth->getSourceRange();
1608 } else {
1609 // A function typedef ("typedef int f(); f a;").
1610 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1611 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001612 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001613 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001614 }
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Chris Lattner8b963ef2009-03-05 23:01:03 +00001616 BitWidth = 0;
1617 Member->setInvalidDecl();
1618 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001619
1620 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Douglas Gregor37b372b2009-08-20 22:52:58 +00001622 // If we have declared a member function template, set the access of the
1623 // templated declaration as well.
1624 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1625 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001626 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001627
Richard Smitha4b39652012-08-06 03:25:17 +00001628 if (VS.isOverrideSpecified())
1629 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1630 if (VS.isFinalSpecified())
1631 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001632
Douglas Gregorf5251602011-03-08 17:10:18 +00001633 if (VS.getLastLocation().isValid()) {
1634 // Update the end location of a method that has a virt-specifiers.
1635 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1636 MD->setRangeEnd(VS.getLastLocation());
1637 }
Richard Smitha4b39652012-08-06 03:25:17 +00001638
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001639 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001640
Douglas Gregor10bd3682008-11-17 22:58:34 +00001641 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001642
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001643 if (isInstField) {
1644 FieldDecl *FD = cast<FieldDecl>(Member);
1645 FieldCollector->Add(FD);
1646
1647 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1648 FD->getLocation())
1649 != DiagnosticsEngine::Ignored) {
1650 // Remember all explicit private FieldDecls that have a name, no side
1651 // effects and are not part of a dependent type declaration.
1652 if (!FD->isImplicit() && FD->getDeclName() &&
1653 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001654 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001655 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001656 !InitializationHasSideEffects(*FD))
1657 UnusedPrivateFields.insert(FD);
1658 }
1659 }
1660
John McCalld226f652010-08-21 09:40:31 +00001661 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001662}
1663
Richard Smith7a614d82011-06-11 17:19:42 +00001664/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001665/// in-class initializer for a non-static C++ class member, and after
1666/// instantiating an in-class initializer in a class template. Such actions
1667/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001668void
Richard Smithca523302012-06-10 03:12:00 +00001669Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001670 Expr *InitExpr) {
1671 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001672 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1673 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001674
1675 if (!InitExpr) {
1676 FD->setInvalidDecl();
1677 FD->removeInClassInitializer();
1678 return;
1679 }
1680
Peter Collingbournefef21892011-10-23 18:59:44 +00001681 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1682 FD->setInvalidDecl();
1683 FD->removeInClassInitializer();
1684 return;
1685 }
1686
Richard Smith7a614d82011-06-11 17:19:42 +00001687 ExprResult Init = InitExpr;
1688 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001689 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001690 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001691 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1692 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001693 Expr **Inits = &InitExpr;
1694 unsigned NumInits = 1;
1695 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00001696 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00001697 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00001698 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00001699 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1700 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001701 if (Init.isInvalid()) {
1702 FD->setInvalidDecl();
1703 return;
1704 }
1705
Richard Smithca523302012-06-10 03:12:00 +00001706 CheckImplicitConversions(Init.get(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00001707 }
1708
1709 // C++0x [class.base.init]p7:
1710 // The initialization of each base and member constitutes a
1711 // full-expression.
1712 Init = MaybeCreateExprWithCleanups(Init);
1713 if (Init.isInvalid()) {
1714 FD->setInvalidDecl();
1715 return;
1716 }
1717
1718 InitExpr = Init.release();
1719
1720 FD->setInClassInitializer(InitExpr);
1721}
1722
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001723/// \brief Find the direct and/or virtual base specifiers that
1724/// correspond to the given base type, for use in base initialization
1725/// within a constructor.
1726static bool FindBaseInitializer(Sema &SemaRef,
1727 CXXRecordDecl *ClassDecl,
1728 QualType BaseType,
1729 const CXXBaseSpecifier *&DirectBaseSpec,
1730 const CXXBaseSpecifier *&VirtualBaseSpec) {
1731 // First, check for a direct base class.
1732 DirectBaseSpec = 0;
1733 for (CXXRecordDecl::base_class_const_iterator Base
1734 = ClassDecl->bases_begin();
1735 Base != ClassDecl->bases_end(); ++Base) {
1736 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1737 // We found a direct base of this type. That's what we're
1738 // initializing.
1739 DirectBaseSpec = &*Base;
1740 break;
1741 }
1742 }
1743
1744 // Check for a virtual base class.
1745 // FIXME: We might be able to short-circuit this if we know in advance that
1746 // there are no virtual bases.
1747 VirtualBaseSpec = 0;
1748 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1749 // We haven't found a base yet; search the class hierarchy for a
1750 // virtual base class.
1751 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1752 /*DetectVirtual=*/false);
1753 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1754 BaseType, Paths)) {
1755 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1756 Path != Paths.end(); ++Path) {
1757 if (Path->back().Base->isVirtual()) {
1758 VirtualBaseSpec = Path->back().Base;
1759 break;
1760 }
1761 }
1762 }
1763 }
1764
1765 return DirectBaseSpec || VirtualBaseSpec;
1766}
1767
Sebastian Redl6df65482011-09-24 17:48:25 +00001768/// \brief Handle a C++ member initializer using braced-init-list syntax.
1769MemInitResult
1770Sema::ActOnMemInitializer(Decl *ConstructorD,
1771 Scope *S,
1772 CXXScopeSpec &SS,
1773 IdentifierInfo *MemberOrBase,
1774 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001775 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001776 SourceLocation IdLoc,
1777 Expr *InitList,
1778 SourceLocation EllipsisLoc) {
1779 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001780 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00001781 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001782}
1783
1784/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001785MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001786Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001787 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001788 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001789 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001790 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001791 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001792 SourceLocation IdLoc,
1793 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001794 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001795 SourceLocation RParenLoc,
1796 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001797 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
1798 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001799 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001800 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001801 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001802}
1803
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001804namespace {
1805
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001806// Callback to only accept typo corrections that can be a valid C++ member
1807// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001808class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1809 public:
1810 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1811 : ClassDecl(ClassDecl) {}
1812
1813 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1814 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1815 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1816 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1817 else
1818 return isa<TypeDecl>(ND);
1819 }
1820 return false;
1821 }
1822
1823 private:
1824 CXXRecordDecl *ClassDecl;
1825};
1826
1827}
1828
Sebastian Redl6df65482011-09-24 17:48:25 +00001829/// \brief Handle a C++ member initializer.
1830MemInitResult
1831Sema::BuildMemInitializer(Decl *ConstructorD,
1832 Scope *S,
1833 CXXScopeSpec &SS,
1834 IdentifierInfo *MemberOrBase,
1835 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001836 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001837 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001838 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00001839 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001840 if (!ConstructorD)
1841 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001842
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001843 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001844
1845 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001846 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001847 if (!Constructor) {
1848 // The user wrote a constructor initializer on a function that is
1849 // not a C++ constructor. Ignore the error for now, because we may
1850 // have more member initializers coming; we'll diagnose it just
1851 // once in ActOnMemInitializers.
1852 return true;
1853 }
1854
1855 CXXRecordDecl *ClassDecl = Constructor->getParent();
1856
1857 // C++ [class.base.init]p2:
1858 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001859 // constructor's class and, if not found in that scope, are looked
1860 // up in the scope containing the constructor's definition.
1861 // [Note: if the constructor's class contains a member with the
1862 // same name as a direct or virtual base class of the class, a
1863 // mem-initializer-id naming the member or base class and composed
1864 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001865 // mem-initializer-id for the hidden base class may be specified
1866 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001867 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001868 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001869 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001870 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001871 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001872 ValueDecl *Member;
1873 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1874 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001875 if (EllipsisLoc.isValid())
1876 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001877 << MemberOrBase
1878 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00001879
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001880 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001881 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001882 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001883 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001884 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001885 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001886 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001887
1888 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001889 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001890 } else if (DS.getTypeSpecType() == TST_decltype) {
1891 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001892 } else {
1893 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1894 LookupParsedName(R, S, &SS);
1895
1896 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1897 if (!TyD) {
1898 if (R.isAmbiguous()) return true;
1899
John McCallfd225442010-04-09 19:01:14 +00001900 // We don't want access-control diagnostics here.
1901 R.suppressDiagnostics();
1902
Douglas Gregor7a886e12010-01-19 06:46:48 +00001903 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1904 bool NotUnknownSpecialization = false;
1905 DeclContext *DC = computeDeclContext(SS, false);
1906 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1907 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1908
1909 if (!NotUnknownSpecialization) {
1910 // When the scope specifier can refer to a member of an unknown
1911 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001912 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1913 SS.getWithLocInContext(Context),
1914 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001915 if (BaseType.isNull())
1916 return true;
1917
Douglas Gregor7a886e12010-01-19 06:46:48 +00001918 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001919 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001920 }
1921 }
1922
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001923 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001924 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001925 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001926 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001927 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001928 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001929 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1930 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001931 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001932 // We have found a non-static data member with a similar
1933 // name to what was typed; complain and initialize that
1934 // member.
1935 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1936 << MemberOrBase << true << CorrectedQuotedStr
1937 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1938 Diag(Member->getLocation(), diag::note_previous_decl)
1939 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001940
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001941 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001942 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001943 const CXXBaseSpecifier *DirectBaseSpec;
1944 const CXXBaseSpecifier *VirtualBaseSpec;
1945 if (FindBaseInitializer(*this, ClassDecl,
1946 Context.getTypeDeclType(Type),
1947 DirectBaseSpec, VirtualBaseSpec)) {
1948 // We have found a direct or virtual base class with a
1949 // similar name to what was typed; complain and initialize
1950 // that base class.
1951 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001952 << MemberOrBase << false << CorrectedQuotedStr
1953 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001954
1955 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1956 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00001957 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00001958 diag::note_base_class_specified_here)
1959 << BaseSpec->getType()
1960 << BaseSpec->getSourceRange();
1961
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001962 TyD = Type;
1963 }
1964 }
1965 }
1966
Douglas Gregor7a886e12010-01-19 06:46:48 +00001967 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001968 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001969 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001970 return true;
1971 }
John McCall2b194412009-12-21 10:41:20 +00001972 }
1973
Douglas Gregor7a886e12010-01-19 06:46:48 +00001974 if (BaseType.isNull()) {
1975 BaseType = Context.getTypeDeclType(TyD);
1976 if (SS.isSet()) {
1977 NestedNameSpecifier *Qualifier =
1978 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001979
Douglas Gregor7a886e12010-01-19 06:46:48 +00001980 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001981 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001982 }
John McCall2b194412009-12-21 10:41:20 +00001983 }
1984 }
Mike Stump1eb44332009-09-09 15:08:12 +00001985
John McCalla93c9342009-12-07 02:54:59 +00001986 if (!TInfo)
1987 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001988
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001989 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001990}
1991
Chandler Carruth81c64772011-09-03 01:14:15 +00001992/// Checks a member initializer expression for cases where reference (or
1993/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001994static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1995 Expr *Init,
1996 SourceLocation IdLoc) {
1997 QualType MemberTy = Member->getType();
1998
1999 // We only handle pointers and references currently.
2000 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2001 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2002 return;
2003
2004 const bool IsPointer = MemberTy->isPointerType();
2005 if (IsPointer) {
2006 if (const UnaryOperator *Op
2007 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2008 // The only case we're worried about with pointers requires taking the
2009 // address.
2010 if (Op->getOpcode() != UO_AddrOf)
2011 return;
2012
2013 Init = Op->getSubExpr();
2014 } else {
2015 // We only handle address-of expression initializers for pointers.
2016 return;
2017 }
2018 }
2019
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002020 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2021 // Taking the address of a temporary will be diagnosed as a hard error.
2022 if (IsPointer)
2023 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002024
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002025 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2026 << Member << Init->getSourceRange();
2027 } else if (const DeclRefExpr *DRE
2028 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2029 // We only warn when referring to a non-reference parameter declaration.
2030 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2031 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002032 return;
2033
2034 S.Diag(Init->getExprLoc(),
2035 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2036 : diag::warn_bind_ref_member_to_parameter)
2037 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002038 } else {
2039 // Other initializers are fine.
2040 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002041 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002042
2043 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2044 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002045}
2046
Richard Trieude5e75c2012-06-14 23:11:34 +00002047namespace {
2048 class UninitializedFieldVisitor
2049 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2050 Sema &S;
2051 ValueDecl *VD;
2052 public:
2053 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2054 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
2055 S(S), VD(VD) {
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002056 }
2057
Richard Trieude5e75c2012-06-14 23:11:34 +00002058 void HandleExpr(Expr *E) {
2059 if (!E) return;
2060
2061 // Expressions like x(x) sometimes lack the surrounding expressions
2062 // but need to be checked anyways.
2063 HandleValue(E);
2064 Visit(E);
2065 }
2066
2067 void HandleValue(Expr *E) {
2068 E = E->IgnoreParens();
2069
Richard Trieue0991252012-06-14 23:18:09 +00002070 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieude5e75c2012-06-14 23:11:34 +00002071 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2072 return;
Richard Trieue0991252012-06-14 23:18:09 +00002073 Expr *Base = E;
Richard Trieude5e75c2012-06-14 23:11:34 +00002074 while (isa<MemberExpr>(Base)) {
2075 ME = dyn_cast<MemberExpr>(Base);
2076 if (VarDecl *VarD = dyn_cast<VarDecl>(ME->getMemberDecl()))
2077 if (VarD->hasGlobalStorage())
2078 return;
2079 Base = ME->getBase();
2080 }
2081
2082 if (VD == ME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg5965b7c2012-08-20 08:52:22 +00002083 unsigned diag = VD->getType()->isReferenceType()
2084 ? diag::warn_reference_field_is_uninit
2085 : diag::warn_field_is_uninit;
2086 S.Diag(ME->getExprLoc(), diag);
Richard Trieude5e75c2012-06-14 23:11:34 +00002087 return;
2088 }
John McCallb4190042009-11-04 23:02:40 +00002089 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002090
2091 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2092 HandleValue(CO->getTrueExpr());
2093 HandleValue(CO->getFalseExpr());
2094 return;
2095 }
2096
2097 if (BinaryConditionalOperator *BCO =
2098 dyn_cast<BinaryConditionalOperator>(E)) {
2099 HandleValue(BCO->getCommon());
2100 HandleValue(BCO->getFalseExpr());
2101 return;
2102 }
2103
2104 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2105 switch (BO->getOpcode()) {
2106 default:
2107 return;
2108 case(BO_PtrMemD):
2109 case(BO_PtrMemI):
2110 HandleValue(BO->getLHS());
2111 return;
2112 case(BO_Comma):
2113 HandleValue(BO->getRHS());
2114 return;
2115 }
2116 }
John McCallb4190042009-11-04 23:02:40 +00002117 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002118
2119 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2120 if (E->getCastKind() == CK_LValueToRValue)
2121 HandleValue(E->getSubExpr());
2122
2123 Inherited::VisitImplicitCastExpr(E);
John McCallb4190042009-11-04 23:02:40 +00002124 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002125
2126 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2127 Expr *Callee = E->getCallee();
2128 if (isa<MemberExpr>(Callee))
2129 HandleValue(Callee);
2130
2131 Inherited::VisitCXXMemberCallExpr(E);
2132 }
2133 };
2134 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2135 ValueDecl *VD) {
2136 UninitializedFieldVisitor(S, VD).HandleExpr(E);
John McCallb4190042009-11-04 23:02:40 +00002137 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002138} // namespace
John McCallb4190042009-11-04 23:02:40 +00002139
John McCallf312b1e2010-08-26 23:41:50 +00002140MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002141Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002142 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002143 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2144 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2145 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002146 "Member must be a FieldDecl or IndirectFieldDecl");
2147
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002148 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002149 return true;
2150
Douglas Gregor464b2f02010-11-05 22:21:31 +00002151 if (Member->isInvalidDecl())
2152 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002153
John McCallb4190042009-11-04 23:02:40 +00002154 // Diagnose value-uses of fields to initialize themselves, e.g.
2155 // foo(foo)
2156 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002157 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002158 Expr **Args;
2159 unsigned NumArgs;
2160 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2161 Args = ParenList->getExprs();
2162 NumArgs = ParenList->getNumExprs();
2163 } else {
2164 InitListExpr *InitList = cast<InitListExpr>(Init);
2165 Args = InitList->getInits();
2166 NumArgs = InitList->getNumInits();
2167 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002168
Richard Trieude5e75c2012-06-14 23:11:34 +00002169 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2170 != DiagnosticsEngine::Ignored)
2171 for (unsigned i = 0; i < NumArgs; ++i)
2172 // FIXME: Warn about the case when other fields are used before being
John McCallb4190042009-11-04 23:02:40 +00002173 // uninitialized. For example, let this field be the i'th field. When
2174 // initializing the i'th field, throw a warning if any of the >= i'th
2175 // fields are used, as they are not yet initialized.
2176 // Right now we are only handling the case where the i'th field uses
2177 // itself in its initializer.
Richard Trieude5e75c2012-06-14 23:11:34 +00002178 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002179
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002180 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002181
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002182 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002183 // Can't check initialization for a member of dependent type or when
2184 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002185 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002186 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002187 bool InitList = false;
2188 if (isa<InitListExpr>(Init)) {
2189 InitList = true;
2190 Args = &Init;
2191 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002192
2193 if (isStdInitializerList(Member->getType(), 0)) {
2194 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2195 << /*at end of ctor*/1 << InitRange;
2196 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002197 }
2198
Chandler Carruth894aed92010-12-06 09:23:57 +00002199 // Initialize the member.
2200 InitializedEntity MemberEntity =
2201 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2202 : InitializedEntity::InitializeMember(IndirectMember, 0);
2203 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002204 InitList ? InitializationKind::CreateDirectList(IdLoc)
2205 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2206 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002207
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002208 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2209 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002210 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002211 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002212 if (MemberInit.isInvalid())
2213 return true;
2214
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002215 CheckImplicitConversions(MemberInit.get(),
2216 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002217
2218 // C++0x [class.base.init]p7:
2219 // The initialization of each base and member constitutes a
2220 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002221 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002222 if (MemberInit.isInvalid())
2223 return true;
2224
2225 // If we are in a dependent context, template instantiation will
2226 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002227 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002228 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2229 // of the information that we have about the member
2230 // initializer. However, deconstructing the ASTs is a dicey process,
2231 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002232 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002233 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002234 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002235 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002236 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2237 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002238 }
2239
Chandler Carruth894aed92010-12-06 09:23:57 +00002240 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002241 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2242 InitRange.getBegin(), Init,
2243 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002244 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002245 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2246 InitRange.getBegin(), Init,
2247 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002248 }
Eli Friedman59c04372009-07-29 19:44:27 +00002249}
2250
John McCallf312b1e2010-08-26 23:41:50 +00002251MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002252Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002253 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002254 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002255 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002256 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002257 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002258 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002259
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002260 bool InitList = true;
2261 Expr **Args = &Init;
2262 unsigned NumArgs = 1;
2263 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2264 InitList = false;
2265 Args = ParenList->getExprs();
2266 NumArgs = ParenList->getNumExprs();
2267 }
2268
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002269 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002270 // Initialize the object.
2271 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2272 QualType(ClassDecl->getTypeForDecl(), 0));
2273 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002274 InitList ? InitializationKind::CreateDirectList(NameLoc)
2275 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2276 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002277 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2278 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002279 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002280 0);
Sean Hunt41717662011-02-26 19:13:13 +00002281 if (DelegationInit.isInvalid())
2282 return true;
2283
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002284 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2285 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002286
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002287 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002288
2289 // C++0x [class.base.init]p7:
2290 // The initialization of each base and member constitutes a
2291 // full-expression.
2292 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2293 if (DelegationInit.isInvalid())
2294 return true;
2295
Eli Friedmand21016f2012-05-19 23:35:23 +00002296 // If we are in a dependent context, template instantiation will
2297 // perform this type-checking again. Just save the arguments that we
2298 // received in a ParenListExpr.
2299 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2300 // of the information that we have about the base
2301 // initializer. However, deconstructing the ASTs is a dicey process,
2302 // and this approach is far more likely to get the corner cases right.
2303 if (CurContext->isDependentContext())
2304 DelegationInit = Owned(Init);
2305
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002306 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002307 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002308 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002309}
2310
2311MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002312Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002313 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002314 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002315 SourceLocation BaseLoc
2316 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002317
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002318 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2319 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2320 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2321
2322 // C++ [class.base.init]p2:
2323 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002324 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002325 // of that class, the mem-initializer is ill-formed. A
2326 // mem-initializer-list can initialize a base class using any
2327 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002328 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002329
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002330 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002331 if (EllipsisLoc.isValid()) {
2332 // This is a pack expansion.
2333 if (!BaseType->containsUnexpandedParameterPack()) {
2334 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002335 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002336
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002337 EllipsisLoc = SourceLocation();
2338 }
2339 } else {
2340 // Check for any unexpanded parameter packs.
2341 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2342 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002343
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002344 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002345 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002346 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002347
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002348 // Check for direct and virtual base classes.
2349 const CXXBaseSpecifier *DirectBaseSpec = 0;
2350 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2351 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002352 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2353 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002354 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002355
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002356 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2357 VirtualBaseSpec);
2358
2359 // C++ [base.class.init]p2:
2360 // Unless the mem-initializer-id names a nonstatic data member of the
2361 // constructor's class or a direct or virtual base of that class, the
2362 // mem-initializer is ill-formed.
2363 if (!DirectBaseSpec && !VirtualBaseSpec) {
2364 // If the class has any dependent bases, then it's possible that
2365 // one of those types will resolve to the same type as
2366 // BaseType. Therefore, just treat this as a dependent base
2367 // class initialization. FIXME: Should we try to check the
2368 // initialization anyway? It seems odd.
2369 if (ClassDecl->hasAnyDependentBases())
2370 Dependent = true;
2371 else
2372 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2373 << BaseType << Context.getTypeDeclType(ClassDecl)
2374 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2375 }
2376 }
2377
2378 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002379 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Sebastian Redl6df65482011-09-24 17:48:25 +00002381 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2382 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002383 InitRange.getBegin(), Init,
2384 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002385 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002386
2387 // C++ [base.class.init]p2:
2388 // If a mem-initializer-id is ambiguous because it designates both
2389 // a direct non-virtual base class and an inherited virtual base
2390 // class, the mem-initializer is ill-formed.
2391 if (DirectBaseSpec && VirtualBaseSpec)
2392 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002393 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002394
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002395 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002396 if (!BaseSpec)
2397 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2398
2399 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002400 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002401 Expr **Args = &Init;
2402 unsigned NumArgs = 1;
2403 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002404 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002405 Args = ParenList->getExprs();
2406 NumArgs = ParenList->getNumExprs();
2407 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002408
2409 InitializedEntity BaseEntity =
2410 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2411 InitializationKind Kind =
2412 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2413 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2414 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002415 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2416 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002417 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002418 if (BaseInit.isInvalid())
2419 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002420
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002421 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002422
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002423 // C++0x [class.base.init]p7:
2424 // The initialization of each base and member constitutes a
2425 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002426 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002427 if (BaseInit.isInvalid())
2428 return true;
2429
2430 // If we are in a dependent context, template instantiation will
2431 // perform this type-checking again. Just save the arguments that we
2432 // received in a ParenListExpr.
2433 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2434 // of the information that we have about the base
2435 // initializer. However, deconstructing the ASTs is a dicey process,
2436 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002437 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002438 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002439
Sean Huntcbb67482011-01-08 20:30:50 +00002440 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002441 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002442 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002443 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002444 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002445}
2446
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002447// Create a static_cast\<T&&>(expr).
2448static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2449 QualType ExprType = E->getType();
2450 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2451 SourceLocation ExprLoc = E->getLocStart();
2452 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2453 TargetType, ExprLoc);
2454
2455 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2456 SourceRange(ExprLoc, ExprLoc),
2457 E->getSourceRange()).take();
2458}
2459
Anders Carlssone5ef7402010-04-23 03:10:23 +00002460/// ImplicitInitializerKind - How an implicit base or member initializer should
2461/// initialize its base or member.
2462enum ImplicitInitializerKind {
2463 IIK_Default,
2464 IIK_Copy,
2465 IIK_Move
2466};
2467
Anders Carlssondefefd22010-04-23 02:00:02 +00002468static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002469BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002470 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002471 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002472 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002473 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002474 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002475 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2476 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002477
John McCall60d7b3a2010-08-24 06:29:42 +00002478 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002479
2480 switch (ImplicitInitKind) {
2481 case IIK_Default: {
2482 InitializationKind InitKind
2483 = InitializationKind::CreateDefault(Constructor->getLocation());
2484 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002485 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002486 break;
2487 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002488
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002489 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002490 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002491 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002492 ParmVarDecl *Param = Constructor->getParamDecl(0);
2493 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002494
Anders Carlssone5ef7402010-04-23 03:10:23 +00002495 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002496 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002497 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002498 Constructor->getLocation(), ParamType,
2499 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002500
Eli Friedman5f2987c2012-02-02 03:46:19 +00002501 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2502
Anders Carlssonc7957502010-04-24 22:02:54 +00002503 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002504 QualType ArgTy =
2505 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2506 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002507
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002508 if (Moving) {
2509 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2510 }
2511
John McCallf871d0c2010-08-07 06:22:56 +00002512 CXXCastPath BasePath;
2513 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002514 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2515 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002516 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002517 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002518
Anders Carlssone5ef7402010-04-23 03:10:23 +00002519 InitializationKind InitKind
2520 = InitializationKind::CreateDirect(Constructor->getLocation(),
2521 SourceLocation(), SourceLocation());
2522 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2523 &CopyCtorArg, 1);
2524 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002525 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002526 break;
2527 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002528 }
John McCall9ae2f072010-08-23 23:25:46 +00002529
Douglas Gregor53c374f2010-12-07 00:41:46 +00002530 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002531 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002532 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002533
Anders Carlssondefefd22010-04-23 02:00:02 +00002534 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002535 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002536 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2537 SourceLocation()),
2538 BaseSpec->isVirtual(),
2539 SourceLocation(),
2540 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002541 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002542 SourceLocation());
2543
Anders Carlssondefefd22010-04-23 02:00:02 +00002544 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002545}
2546
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002547static bool RefersToRValueRef(Expr *MemRef) {
2548 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2549 return Referenced->getType()->isRValueReferenceType();
2550}
2551
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002552static bool
2553BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002554 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002555 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002556 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002557 if (Field->isInvalidDecl())
2558 return true;
2559
Chandler Carruthf186b542010-06-29 23:50:44 +00002560 SourceLocation Loc = Constructor->getLocation();
2561
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002562 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2563 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002564 ParmVarDecl *Param = Constructor->getParamDecl(0);
2565 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002566
2567 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002568 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2569 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002570
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002571 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002572 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002573 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002574 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002575
Eli Friedman5f2987c2012-02-02 03:46:19 +00002576 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2577
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002578 if (Moving) {
2579 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2580 }
2581
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002582 // Build a reference to this field within the parameter.
2583 CXXScopeSpec SS;
2584 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2585 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002586 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2587 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002588 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002589 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002590 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002591 ParamType, Loc,
2592 /*IsArrow=*/false,
2593 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002594 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002595 /*FirstQualifierInScope=*/0,
2596 MemberLookup,
2597 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002598 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002599 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002600
2601 // C++11 [class.copy]p15:
2602 // - if a member m has rvalue reference type T&&, it is direct-initialized
2603 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002604 if (RefersToRValueRef(CtorArg.get())) {
2605 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002606 }
2607
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002608 // When the field we are copying is an array, create index variables for
2609 // each dimension of the array. We use these index variables to subscript
2610 // the source array, and other clients (e.g., CodeGen) will perform the
2611 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002612 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002613 QualType BaseType = Field->getType();
2614 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002615 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002616 while (const ConstantArrayType *Array
2617 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002618 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002619 // Create the iteration variable for this array index.
2620 IdentifierInfo *IterationVarName = 0;
2621 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002622 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002623 llvm::raw_svector_ostream OS(Str);
2624 OS << "__i" << IndexVariables.size();
2625 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2626 }
2627 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002628 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002629 IterationVarName, SizeType,
2630 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002631 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002632 IndexVariables.push_back(IterationVar);
2633
2634 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002635 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002636 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002637 assert(!IterationVarRef.isInvalid() &&
2638 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002639 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2640 assert(!IterationVarRef.isInvalid() &&
2641 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002642
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002643 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002644 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002645 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002646 Loc);
2647 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002648 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002649
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002650 BaseType = Array->getElementType();
2651 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002652
2653 // The array subscript expression is an lvalue, which is wrong for moving.
2654 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002655 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002656
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002657 // Construct the entity that we will be initializing. For an array, this
2658 // will be first element in the array, which may require several levels
2659 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002660 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002661 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002662 if (Indirect)
2663 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2664 else
2665 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002666 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2667 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2668 0,
2669 Entities.back()));
2670
2671 // Direct-initialize to use the copy constructor.
2672 InitializationKind InitKind =
2673 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2674
Sebastian Redl74e611a2011-09-04 18:14:28 +00002675 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002676 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002677 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002678
John McCall60d7b3a2010-08-24 06:29:42 +00002679 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002680 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002681 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002682 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002683 if (MemberInit.isInvalid())
2684 return true;
2685
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002686 if (Indirect) {
2687 assert(IndexVariables.size() == 0 &&
2688 "Indirect field improperly initialized");
2689 CXXMemberInit
2690 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2691 Loc, Loc,
2692 MemberInit.takeAs<Expr>(),
2693 Loc);
2694 } else
2695 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2696 Loc, MemberInit.takeAs<Expr>(),
2697 Loc,
2698 IndexVariables.data(),
2699 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002700 return false;
2701 }
2702
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002703 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2704
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002705 QualType FieldBaseElementType =
2706 SemaRef.Context.getBaseElementType(Field->getType());
2707
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002708 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002709 InitializedEntity InitEntity
2710 = Indirect? InitializedEntity::InitializeMember(Indirect)
2711 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002712 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002713 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002714
2715 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002716 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002717 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002718
Douglas Gregor53c374f2010-12-07 00:41:46 +00002719 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002720 if (MemberInit.isInvalid())
2721 return true;
2722
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002723 if (Indirect)
2724 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2725 Indirect, Loc,
2726 Loc,
2727 MemberInit.get(),
2728 Loc);
2729 else
2730 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2731 Field, Loc, Loc,
2732 MemberInit.get(),
2733 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002734 return false;
2735 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002736
Sean Hunt1f2f3842011-05-17 00:19:05 +00002737 if (!Field->getParent()->isUnion()) {
2738 if (FieldBaseElementType->isReferenceType()) {
2739 SemaRef.Diag(Constructor->getLocation(),
2740 diag::err_uninitialized_member_in_ctor)
2741 << (int)Constructor->isImplicit()
2742 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2743 << 0 << Field->getDeclName();
2744 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2745 return true;
2746 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002747
Sean Hunt1f2f3842011-05-17 00:19:05 +00002748 if (FieldBaseElementType.isConstQualified()) {
2749 SemaRef.Diag(Constructor->getLocation(),
2750 diag::err_uninitialized_member_in_ctor)
2751 << (int)Constructor->isImplicit()
2752 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2753 << 1 << Field->getDeclName();
2754 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2755 return true;
2756 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002757 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002758
David Blaikie4e4d0842012-03-11 07:00:24 +00002759 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002760 FieldBaseElementType->isObjCRetainableType() &&
2761 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2762 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002763 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002764 // Default-initialize Objective-C pointers to NULL.
2765 CXXMemberInit
2766 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2767 Loc, Loc,
2768 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2769 Loc);
2770 return false;
2771 }
2772
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002773 // Nothing to initialize.
2774 CXXMemberInit = 0;
2775 return false;
2776}
John McCallf1860e52010-05-20 23:23:51 +00002777
2778namespace {
2779struct BaseAndFieldInfo {
2780 Sema &S;
2781 CXXConstructorDecl *Ctor;
2782 bool AnyErrorsInInits;
2783 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002784 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002785 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002786
2787 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2788 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002789 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2790 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002791 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002792 else if (Generated && Ctor->isMoveConstructor())
2793 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002794 else
2795 IIK = IIK_Default;
2796 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002797
2798 bool isImplicitCopyOrMove() const {
2799 switch (IIK) {
2800 case IIK_Copy:
2801 case IIK_Move:
2802 return true;
2803
2804 case IIK_Default:
2805 return false;
2806 }
David Blaikie30263482012-01-20 21:50:17 +00002807
2808 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002809 }
Richard Smith0b8220a2012-08-07 21:30:42 +00002810
2811 bool addFieldInitializer(CXXCtorInitializer *Init) {
2812 AllToInit.push_back(Init);
2813
2814 // Check whether this initializer makes the field "used".
2815 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2816 S.UnusedPrivateFields.remove(Init->getAnyMember());
2817
2818 return false;
2819 }
John McCallf1860e52010-05-20 23:23:51 +00002820};
2821}
2822
Richard Smitha4950662011-09-19 13:34:43 +00002823/// \brief Determine whether the given indirect field declaration is somewhere
2824/// within an anonymous union.
2825static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2826 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2827 CEnd = F->chain_end();
2828 C != CEnd; ++C)
2829 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2830 if (Record->isUnion())
2831 return true;
2832
2833 return false;
2834}
2835
Douglas Gregorddb21472011-11-02 23:04:16 +00002836/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2837/// array type.
2838static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2839 if (T->isIncompleteArrayType())
2840 return true;
2841
2842 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2843 if (!ArrayT->getSize())
2844 return true;
2845
2846 T = ArrayT->getElementType();
2847 }
2848
2849 return false;
2850}
2851
Richard Smith7a614d82011-06-11 17:19:42 +00002852static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002853 FieldDecl *Field,
2854 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002855
Chandler Carruthe861c602010-06-30 02:59:29 +00002856 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00002857 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
2858 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00002859
Richard Smith0b8220a2012-08-07 21:30:42 +00002860 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00002861 // has a brace-or-equal-initializer, the entity is initialized as specified
2862 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002863 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002864 CXXCtorInitializer *Init;
2865 if (Indirect)
2866 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2867 SourceLocation(),
2868 SourceLocation(), 0,
2869 SourceLocation());
2870 else
2871 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2872 SourceLocation(),
2873 SourceLocation(), 0,
2874 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00002875 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002876 }
2877
Richard Smithc115f632011-09-18 11:14:50 +00002878 // Don't build an implicit initializer for union members if none was
2879 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002880 if (Field->getParent()->isUnion() ||
2881 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002882 return false;
2883
Douglas Gregorddb21472011-11-02 23:04:16 +00002884 // Don't initialize incomplete or zero-length arrays.
2885 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2886 return false;
2887
John McCallf1860e52010-05-20 23:23:51 +00002888 // Don't try to build an implicit initializer if there were semantic
2889 // errors in any of the initializers (and therefore we might be
2890 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002891 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002892 return false;
2893
Sean Huntcbb67482011-01-08 20:30:50 +00002894 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002895 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2896 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002897 return true;
John McCallf1860e52010-05-20 23:23:51 +00002898
Richard Smith0b8220a2012-08-07 21:30:42 +00002899 if (!Init)
2900 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00002901
Richard Smith0b8220a2012-08-07 21:30:42 +00002902 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00002903}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002904
2905bool
2906Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2907 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002908 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002909 Constructor->setNumCtorInitializers(1);
2910 CXXCtorInitializer **initializer =
2911 new (Context) CXXCtorInitializer*[1];
2912 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2913 Constructor->setCtorInitializers(initializer);
2914
Sean Huntb76af9c2011-05-03 23:05:34 +00002915 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002916 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002917 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2918 }
2919
Sean Huntc1598702011-05-05 00:05:47 +00002920 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002921
Sean Hunt059ce0d2011-05-01 07:04:31 +00002922 return false;
2923}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002924
John McCallb77115d2011-06-17 00:18:42 +00002925bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2926 CXXCtorInitializer **Initializers,
2927 unsigned NumInitializers,
2928 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002929 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002930 // Just store the initializers as written, they will be checked during
2931 // instantiation.
2932 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002933 Constructor->setNumCtorInitializers(NumInitializers);
2934 CXXCtorInitializer **baseOrMemberInitializers =
2935 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002936 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002937 NumInitializers * sizeof(CXXCtorInitializer*));
2938 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002939 }
2940
2941 return false;
2942 }
2943
John McCallf1860e52010-05-20 23:23:51 +00002944 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002945
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002946 // We need to build the initializer AST according to order of construction
2947 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002948 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002949 if (!ClassDecl)
2950 return true;
2951
Eli Friedman80c30da2009-11-09 19:20:36 +00002952 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002953
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002954 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002955 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002956
2957 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002958 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002959 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002960 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002961 }
2962
Anders Carlsson711f34a2010-04-21 19:52:01 +00002963 // Keep track of the direct virtual bases.
2964 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2965 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2966 E = ClassDecl->bases_end(); I != E; ++I) {
2967 if (I->isVirtual())
2968 DirectVBases.insert(I);
2969 }
2970
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002971 // Push virtual bases before others.
2972 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2973 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2974
Sean Huntcbb67482011-01-08 20:30:50 +00002975 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002976 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2977 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002978 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002979 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002980 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002981 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002982 VBase, IsInheritedVirtualBase,
2983 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002984 HadError = true;
2985 continue;
2986 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002987
John McCallf1860e52010-05-20 23:23:51 +00002988 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002989 }
2990 }
Mike Stump1eb44332009-09-09 15:08:12 +00002991
John McCallf1860e52010-05-20 23:23:51 +00002992 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002993 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2994 E = ClassDecl->bases_end(); Base != E; ++Base) {
2995 // Virtuals are in the virtual base list and already constructed.
2996 if (Base->isVirtual())
2997 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002998
Sean Huntcbb67482011-01-08 20:30:50 +00002999 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003000 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3001 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003002 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003003 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003004 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003005 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003006 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003007 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003008 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003009 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003010
John McCallf1860e52010-05-20 23:23:51 +00003011 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003012 }
3013 }
Mike Stump1eb44332009-09-09 15:08:12 +00003014
John McCallf1860e52010-05-20 23:23:51 +00003015 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003016 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3017 MemEnd = ClassDecl->decls_end();
3018 Mem != MemEnd; ++Mem) {
3019 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003020 // C++ [class.bit]p2:
3021 // A declaration for a bit-field that omits the identifier declares an
3022 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3023 // initialized.
3024 if (F->isUnnamedBitfield())
3025 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003026
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003027 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003028 // handle anonymous struct/union fields based on their individual
3029 // indirect fields.
3030 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3031 continue;
3032
3033 if (CollectFieldInitializer(*this, Info, F))
3034 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003035 continue;
3036 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003037
3038 // Beyond this point, we only consider default initialization.
3039 if (Info.IIK != IIK_Default)
3040 continue;
3041
3042 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3043 if (F->getType()->isIncompleteArrayType()) {
3044 assert(ClassDecl->hasFlexibleArrayMember() &&
3045 "Incomplete array type is not valid");
3046 continue;
3047 }
3048
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003049 // Initialize each field of an anonymous struct individually.
3050 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3051 HadError = true;
3052
3053 continue;
3054 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003055 }
Mike Stump1eb44332009-09-09 15:08:12 +00003056
John McCallf1860e52010-05-20 23:23:51 +00003057 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003058 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003059 Constructor->setNumCtorInitializers(NumInitializers);
3060 CXXCtorInitializer **baseOrMemberInitializers =
3061 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003062 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003063 NumInitializers * sizeof(CXXCtorInitializer*));
3064 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003065
John McCallef027fe2010-03-16 21:39:52 +00003066 // Constructors implicitly reference the base and member
3067 // destructors.
3068 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3069 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003070 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003071
3072 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003073}
3074
Eli Friedman6347f422009-07-21 19:28:10 +00003075static void *GetKeyForTopLevelField(FieldDecl *Field) {
3076 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003077 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003078 if (RT->getDecl()->isAnonymousStructOrUnion())
3079 return static_cast<void *>(RT->getDecl());
3080 }
3081 return static_cast<void *>(Field);
3082}
3083
Anders Carlssonea356fb2010-04-02 05:42:15 +00003084static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003085 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003086}
3087
Anders Carlssonea356fb2010-04-02 05:42:15 +00003088static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003089 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003090 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003091 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003092
Eli Friedman6347f422009-07-21 19:28:10 +00003093 // For fields injected into the class via declaration of an anonymous union,
3094 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003095 FieldDecl *Field = Member->getAnyMember();
3096
John McCall3c3ccdb2010-04-10 09:28:51 +00003097 // If the field is a member of an anonymous struct or union, our key
3098 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003099 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003100 if (RD->isAnonymousStructOrUnion()) {
3101 while (true) {
3102 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3103 if (Parent->isAnonymousStructOrUnion())
3104 RD = Parent;
3105 else
3106 break;
3107 }
3108
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003109 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003110 }
Mike Stump1eb44332009-09-09 15:08:12 +00003111
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003112 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003113}
3114
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003115static void
3116DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003117 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003118 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003119 unsigned NumInits) {
3120 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003121 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003122
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003123 // Don't check initializers order unless the warning is enabled at the
3124 // location of at least one initializer.
3125 bool ShouldCheckOrder = false;
3126 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003127 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003128 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3129 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003130 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003131 ShouldCheckOrder = true;
3132 break;
3133 }
3134 }
3135 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003136 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003137
John McCalld6ca8da2010-04-10 07:37:23 +00003138 // Build the list of bases and members in the order that they'll
3139 // actually be initialized. The explicit initializers should be in
3140 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003141 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003142
Anders Carlsson071d6102010-04-02 03:38:04 +00003143 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3144
John McCalld6ca8da2010-04-10 07:37:23 +00003145 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003146 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003147 ClassDecl->vbases_begin(),
3148 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003149 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003150
John McCalld6ca8da2010-04-10 07:37:23 +00003151 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003152 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003153 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003154 if (Base->isVirtual())
3155 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003156 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003157 }
Mike Stump1eb44332009-09-09 15:08:12 +00003158
John McCalld6ca8da2010-04-10 07:37:23 +00003159 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003160 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003161 E = ClassDecl->field_end(); Field != E; ++Field) {
3162 if (Field->isUnnamedBitfield())
3163 continue;
3164
David Blaikie581deb32012-06-06 20:45:41 +00003165 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003166 }
3167
John McCalld6ca8da2010-04-10 07:37:23 +00003168 unsigned NumIdealInits = IdealInitKeys.size();
3169 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003170
Sean Huntcbb67482011-01-08 20:30:50 +00003171 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003172 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003173 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003174 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003175
3176 // Scan forward to try to find this initializer in the idealized
3177 // initializers list.
3178 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3179 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003180 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003181
3182 // If we didn't find this initializer, it must be because we
3183 // scanned past it on a previous iteration. That can only
3184 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003185 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003186 Sema::SemaDiagnosticBuilder D =
3187 SemaRef.Diag(PrevInit->getSourceLocation(),
3188 diag::warn_initializer_out_of_order);
3189
Francois Pichet00eb3f92010-12-04 09:14:42 +00003190 if (PrevInit->isAnyMemberInitializer())
3191 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003192 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003193 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003194
Francois Pichet00eb3f92010-12-04 09:14:42 +00003195 if (Init->isAnyMemberInitializer())
3196 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003197 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003198 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003199
3200 // Move back to the initializer's location in the ideal list.
3201 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3202 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003203 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003204
3205 assert(IdealIndex != NumIdealInits &&
3206 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003207 }
John McCalld6ca8da2010-04-10 07:37:23 +00003208
3209 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003210 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003211}
3212
John McCall3c3ccdb2010-04-10 09:28:51 +00003213namespace {
3214bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003215 CXXCtorInitializer *Init,
3216 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003217 if (!PrevInit) {
3218 PrevInit = Init;
3219 return false;
3220 }
3221
3222 if (FieldDecl *Field = Init->getMember())
3223 S.Diag(Init->getSourceLocation(),
3224 diag::err_multiple_mem_initialization)
3225 << Field->getDeclName()
3226 << Init->getSourceRange();
3227 else {
John McCallf4c73712011-01-19 06:33:43 +00003228 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003229 assert(BaseClass && "neither field nor base");
3230 S.Diag(Init->getSourceLocation(),
3231 diag::err_multiple_base_initialization)
3232 << QualType(BaseClass, 0)
3233 << Init->getSourceRange();
3234 }
3235 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3236 << 0 << PrevInit->getSourceRange();
3237
3238 return true;
3239}
3240
Sean Huntcbb67482011-01-08 20:30:50 +00003241typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003242typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3243
3244bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003245 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003246 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003247 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003248 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003249 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003250
3251 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003252 if (Parent->isUnion()) {
3253 UnionEntry &En = Unions[Parent];
3254 if (En.first && En.first != Child) {
3255 S.Diag(Init->getSourceLocation(),
3256 diag::err_multiple_mem_union_initialization)
3257 << Field->getDeclName()
3258 << Init->getSourceRange();
3259 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3260 << 0 << En.second->getSourceRange();
3261 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003262 }
3263 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003264 En.first = Child;
3265 En.second = Init;
3266 }
David Blaikie6fe29652011-11-17 06:01:57 +00003267 if (!Parent->isAnonymousStructOrUnion())
3268 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003269 }
3270
3271 Child = Parent;
3272 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003273 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003274
3275 return false;
3276}
3277}
3278
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003279/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003280void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003281 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003282 CXXCtorInitializer **meminits,
3283 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003284 bool AnyErrors) {
3285 if (!ConstructorDecl)
3286 return;
3287
3288 AdjustDeclIfTemplate(ConstructorDecl);
3289
3290 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003291 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003292
3293 if (!Constructor) {
3294 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3295 return;
3296 }
3297
Sean Huntcbb67482011-01-08 20:30:50 +00003298 CXXCtorInitializer **MemInits =
3299 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003300
3301 // Mapping for the duplicate initializers check.
3302 // For member initializers, this is keyed with a FieldDecl*.
3303 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003304 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003305
3306 // Mapping for the inconsistent anonymous-union initializers check.
3307 RedundantUnionMap MemberUnions;
3308
Anders Carlssonea356fb2010-04-02 05:42:15 +00003309 bool HadError = false;
3310 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003311 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003312
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003313 // Set the source order index.
3314 Init->setSourceOrder(i);
3315
Francois Pichet00eb3f92010-12-04 09:14:42 +00003316 if (Init->isAnyMemberInitializer()) {
3317 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003318 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3319 CheckRedundantUnionInit(*this, Init, MemberUnions))
3320 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003321 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003322 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3323 if (CheckRedundantInit(*this, Init, Members[Key]))
3324 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003325 } else {
3326 assert(Init->isDelegatingInitializer());
3327 // This must be the only initializer
3328 if (i != 0 || NumMemInits > 1) {
3329 Diag(MemInits[0]->getSourceLocation(),
3330 diag::err_delegating_initializer_alone)
3331 << MemInits[0]->getSourceRange();
3332 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003333 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003334 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003335 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003336 // Return immediately as the initializer is set.
3337 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003338 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003339 }
3340
Anders Carlssonea356fb2010-04-02 05:42:15 +00003341 if (HadError)
3342 return;
3343
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003344 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003345
Sean Huntcbb67482011-01-08 20:30:50 +00003346 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003347}
3348
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003349void
John McCallef027fe2010-03-16 21:39:52 +00003350Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3351 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003352 // Ignore dependent contexts. Also ignore unions, since their members never
3353 // have destructors implicitly called.
3354 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003355 return;
John McCall58e6f342010-03-16 05:22:47 +00003356
3357 // FIXME: all the access-control diagnostics are positioned on the
3358 // field/base declaration. That's probably good; that said, the
3359 // user might reasonably want to know why the destructor is being
3360 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003361
Anders Carlsson9f853df2009-11-17 04:44:12 +00003362 // Non-static data members.
3363 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3364 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003365 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003366 if (Field->isInvalidDecl())
3367 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003368
3369 // Don't destroy incomplete or zero-length arrays.
3370 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3371 continue;
3372
Anders Carlsson9f853df2009-11-17 04:44:12 +00003373 QualType FieldType = Context.getBaseElementType(Field->getType());
3374
3375 const RecordType* RT = FieldType->getAs<RecordType>();
3376 if (!RT)
3377 continue;
3378
3379 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003380 if (FieldClassDecl->isInvalidDecl())
3381 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003382 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003383 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003384 // The destructor for an implicit anonymous union member is never invoked.
3385 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3386 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003387
Douglas Gregordb89f282010-07-01 22:47:18 +00003388 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003389 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003390 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003391 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003392 << Field->getDeclName()
3393 << FieldType);
3394
Eli Friedman5f2987c2012-02-02 03:46:19 +00003395 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003396 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003397 }
3398
John McCall58e6f342010-03-16 05:22:47 +00003399 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3400
Anders Carlsson9f853df2009-11-17 04:44:12 +00003401 // Bases.
3402 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3403 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003404 // Bases are always records in a well-formed non-dependent class.
3405 const RecordType *RT = Base->getType()->getAs<RecordType>();
3406
3407 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003408 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003409 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003410
John McCall58e6f342010-03-16 05:22:47 +00003411 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003412 // If our base class is invalid, we probably can't get its dtor anyway.
3413 if (BaseClassDecl->isInvalidDecl())
3414 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003415 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003416 continue;
John McCall58e6f342010-03-16 05:22:47 +00003417
Douglas Gregordb89f282010-07-01 22:47:18 +00003418 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003419 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003420
3421 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003422 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003423 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003424 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003425 << Base->getSourceRange(),
3426 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003427
Eli Friedman5f2987c2012-02-02 03:46:19 +00003428 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003429 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003430 }
3431
3432 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003433 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3434 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003435
3436 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003437 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003438
3439 // Ignore direct virtual bases.
3440 if (DirectVirtualBases.count(RT))
3441 continue;
3442
John McCall58e6f342010-03-16 05:22:47 +00003443 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003444 // If our base class is invalid, we probably can't get its dtor anyway.
3445 if (BaseClassDecl->isInvalidDecl())
3446 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003447 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003448 continue;
John McCall58e6f342010-03-16 05:22:47 +00003449
Douglas Gregordb89f282010-07-01 22:47:18 +00003450 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003451 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003452 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003453 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003454 << VBase->getType(),
3455 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003456
Eli Friedman5f2987c2012-02-02 03:46:19 +00003457 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003458 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003459 }
3460}
3461
John McCalld226f652010-08-21 09:40:31 +00003462void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003463 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003464 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003465
Mike Stump1eb44332009-09-09 15:08:12 +00003466 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003467 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003468 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003469}
3470
Mike Stump1eb44332009-09-09 15:08:12 +00003471bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003472 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003473 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3474 unsigned DiagID;
3475 AbstractDiagSelID SelID;
3476
3477 public:
3478 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3479 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3480
3481 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003482 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003483 if (SelID == -1)
3484 S.Diag(Loc, DiagID) << T;
3485 else
3486 S.Diag(Loc, DiagID) << SelID << T;
3487 }
3488 } Diagnoser(DiagID, SelID);
3489
3490 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003491}
3492
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003493bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003494 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003495 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003496 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003497
Anders Carlsson11f21a02009-03-23 19:10:31 +00003498 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003499 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003500
Ted Kremenek6217b802009-07-29 21:53:49 +00003501 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003502 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003503 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003504 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003505
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003506 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003507 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003508 }
Mike Stump1eb44332009-09-09 15:08:12 +00003509
Ted Kremenek6217b802009-07-29 21:53:49 +00003510 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003511 if (!RT)
3512 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003513
John McCall86ff3082010-02-04 22:26:26 +00003514 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003515
John McCall94c3b562010-08-18 09:41:07 +00003516 // We can't answer whether something is abstract until it has a
3517 // definition. If it's currently being defined, we'll walk back
3518 // over all the declarations when we have a full definition.
3519 const CXXRecordDecl *Def = RD->getDefinition();
3520 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003521 return false;
3522
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003523 if (!RD->isAbstract())
3524 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003525
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003526 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003527 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003528
John McCall94c3b562010-08-18 09:41:07 +00003529 return true;
3530}
3531
3532void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3533 // Check if we've already emitted the list of pure virtual functions
3534 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003535 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003536 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003537
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003538 CXXFinalOverriderMap FinalOverriders;
3539 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003540
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003541 // Keep a set of seen pure methods so we won't diagnose the same method
3542 // more than once.
3543 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3544
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003545 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3546 MEnd = FinalOverriders.end();
3547 M != MEnd;
3548 ++M) {
3549 for (OverridingMethods::iterator SO = M->second.begin(),
3550 SOEnd = M->second.end();
3551 SO != SOEnd; ++SO) {
3552 // C++ [class.abstract]p4:
3553 // A class is abstract if it contains or inherits at least one
3554 // pure virtual function for which the final overrider is pure
3555 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003556
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003557 //
3558 if (SO->second.size() != 1)
3559 continue;
3560
3561 if (!SO->second.front().Method->isPure())
3562 continue;
3563
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003564 if (!SeenPureMethods.insert(SO->second.front().Method))
3565 continue;
3566
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003567 Diag(SO->second.front().Method->getLocation(),
3568 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003569 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003570 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003571 }
3572
3573 if (!PureVirtualClassDiagSet)
3574 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3575 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003576}
3577
Anders Carlsson8211eff2009-03-24 01:19:16 +00003578namespace {
John McCall94c3b562010-08-18 09:41:07 +00003579struct AbstractUsageInfo {
3580 Sema &S;
3581 CXXRecordDecl *Record;
3582 CanQualType AbstractType;
3583 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003584
John McCall94c3b562010-08-18 09:41:07 +00003585 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3586 : S(S), Record(Record),
3587 AbstractType(S.Context.getCanonicalType(
3588 S.Context.getTypeDeclType(Record))),
3589 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003590
John McCall94c3b562010-08-18 09:41:07 +00003591 void DiagnoseAbstractType() {
3592 if (Invalid) return;
3593 S.DiagnoseAbstractType(Record);
3594 Invalid = true;
3595 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003596
John McCall94c3b562010-08-18 09:41:07 +00003597 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3598};
3599
3600struct CheckAbstractUsage {
3601 AbstractUsageInfo &Info;
3602 const NamedDecl *Ctx;
3603
3604 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3605 : Info(Info), Ctx(Ctx) {}
3606
3607 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3608 switch (TL.getTypeLocClass()) {
3609#define ABSTRACT_TYPELOC(CLASS, PARENT)
3610#define TYPELOC(CLASS, PARENT) \
3611 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3612#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003613 }
John McCall94c3b562010-08-18 09:41:07 +00003614 }
Mike Stump1eb44332009-09-09 15:08:12 +00003615
John McCall94c3b562010-08-18 09:41:07 +00003616 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3617 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3618 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003619 if (!TL.getArg(I))
3620 continue;
3621
John McCall94c3b562010-08-18 09:41:07 +00003622 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3623 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003624 }
John McCall94c3b562010-08-18 09:41:07 +00003625 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003626
John McCall94c3b562010-08-18 09:41:07 +00003627 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3628 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3629 }
Mike Stump1eb44332009-09-09 15:08:12 +00003630
John McCall94c3b562010-08-18 09:41:07 +00003631 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3632 // Visit the type parameters from a permissive context.
3633 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3634 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3635 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3636 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3637 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3638 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003639 }
John McCall94c3b562010-08-18 09:41:07 +00003640 }
Mike Stump1eb44332009-09-09 15:08:12 +00003641
John McCall94c3b562010-08-18 09:41:07 +00003642 // Visit pointee types from a permissive context.
3643#define CheckPolymorphic(Type) \
3644 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3645 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3646 }
3647 CheckPolymorphic(PointerTypeLoc)
3648 CheckPolymorphic(ReferenceTypeLoc)
3649 CheckPolymorphic(MemberPointerTypeLoc)
3650 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003651 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003652
John McCall94c3b562010-08-18 09:41:07 +00003653 /// Handle all the types we haven't given a more specific
3654 /// implementation for above.
3655 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3656 // Every other kind of type that we haven't called out already
3657 // that has an inner type is either (1) sugar or (2) contains that
3658 // inner type in some way as a subobject.
3659 if (TypeLoc Next = TL.getNextTypeLoc())
3660 return Visit(Next, Sel);
3661
3662 // If there's no inner type and we're in a permissive context,
3663 // don't diagnose.
3664 if (Sel == Sema::AbstractNone) return;
3665
3666 // Check whether the type matches the abstract type.
3667 QualType T = TL.getType();
3668 if (T->isArrayType()) {
3669 Sel = Sema::AbstractArrayType;
3670 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003671 }
John McCall94c3b562010-08-18 09:41:07 +00003672 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3673 if (CT != Info.AbstractType) return;
3674
3675 // It matched; do some magic.
3676 if (Sel == Sema::AbstractArrayType) {
3677 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3678 << T << TL.getSourceRange();
3679 } else {
3680 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3681 << Sel << T << TL.getSourceRange();
3682 }
3683 Info.DiagnoseAbstractType();
3684 }
3685};
3686
3687void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3688 Sema::AbstractDiagSelID Sel) {
3689 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3690}
3691
3692}
3693
3694/// Check for invalid uses of an abstract type in a method declaration.
3695static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3696 CXXMethodDecl *MD) {
3697 // No need to do the check on definitions, which require that
3698 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003699 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003700 return;
3701
3702 // For safety's sake, just ignore it if we don't have type source
3703 // information. This should never happen for non-implicit methods,
3704 // but...
3705 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3706 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3707}
3708
3709/// Check for invalid uses of an abstract type within a class definition.
3710static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3711 CXXRecordDecl *RD) {
3712 for (CXXRecordDecl::decl_iterator
3713 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3714 Decl *D = *I;
3715 if (D->isImplicit()) continue;
3716
3717 // Methods and method templates.
3718 if (isa<CXXMethodDecl>(D)) {
3719 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3720 } else if (isa<FunctionTemplateDecl>(D)) {
3721 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3722 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3723
3724 // Fields and static variables.
3725 } else if (isa<FieldDecl>(D)) {
3726 FieldDecl *FD = cast<FieldDecl>(D);
3727 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3728 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3729 } else if (isa<VarDecl>(D)) {
3730 VarDecl *VD = cast<VarDecl>(D);
3731 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3732 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3733
3734 // Nested classes and class templates.
3735 } else if (isa<CXXRecordDecl>(D)) {
3736 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3737 } else if (isa<ClassTemplateDecl>(D)) {
3738 CheckAbstractClassUsage(Info,
3739 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3740 }
3741 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003742}
3743
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003744/// \brief Perform semantic checks on a class definition that has been
3745/// completing, introducing implicitly-declared members, checking for
3746/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003747void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003748 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003749 return;
3750
John McCall94c3b562010-08-18 09:41:07 +00003751 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3752 AbstractUsageInfo Info(*this, Record);
3753 CheckAbstractClassUsage(Info, Record);
3754 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003755
3756 // If this is not an aggregate type and has no user-declared constructor,
3757 // complain about any non-static data members of reference or const scalar
3758 // type, since they will never get initializers.
3759 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003760 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3761 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003762 bool Complained = false;
3763 for (RecordDecl::field_iterator F = Record->field_begin(),
3764 FEnd = Record->field_end();
3765 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003766 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003767 continue;
3768
Douglas Gregor325e5932010-04-15 00:00:53 +00003769 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003770 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003771 if (!Complained) {
3772 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3773 << Record->getTagKind() << Record;
3774 Complained = true;
3775 }
3776
3777 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3778 << F->getType()->isReferenceType()
3779 << F->getDeclName();
3780 }
3781 }
3782 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003783
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003784 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003785 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003786
3787 if (Record->getIdentifier()) {
3788 // C++ [class.mem]p13:
3789 // If T is the name of a class, then each of the following shall have a
3790 // name different from T:
3791 // - every member of every anonymous union that is a member of class T.
3792 //
3793 // C++ [class.mem]p14:
3794 // In addition, if class T has a user-declared constructor (12.1), every
3795 // non-static data member of class T shall have a name different from T.
3796 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003797 R.first != R.second; ++R.first) {
3798 NamedDecl *D = *R.first;
3799 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3800 isa<IndirectFieldDecl>(D)) {
3801 Diag(D->getLocation(), diag::err_member_name_of_class)
3802 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003803 break;
3804 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003805 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003806 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003807
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003808 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003809 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003810 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003811 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003812 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3813 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3814 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003815
3816 // See if a method overloads virtual methods in a base
3817 /// class without overriding any.
3818 if (!Record->isDependentType()) {
3819 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3820 MEnd = Record->method_end();
3821 M != MEnd; ++M) {
David Blaikie262bc182012-04-30 02:36:29 +00003822 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003823 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003824 }
3825 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003826
Richard Smith9f569cc2011-10-01 02:31:28 +00003827 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3828 // function that is not a constructor declares that member function to be
3829 // const. [...] The class of which that function is a member shall be
3830 // a literal type.
3831 //
Richard Smith9f569cc2011-10-01 02:31:28 +00003832 // If the class has virtual bases, any constexpr members will already have
3833 // been diagnosed by the checks performed on the member declaration, so
3834 // suppress this (less useful) diagnostic.
3835 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3836 !Record->isLiteral() && !Record->getNumVBases()) {
3837 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3838 MEnd = Record->method_end();
3839 M != MEnd; ++M) {
Richard Smith86c3ae42012-02-13 03:54:03 +00003840 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003841 switch (Record->getTemplateSpecializationKind()) {
3842 case TSK_ImplicitInstantiation:
3843 case TSK_ExplicitInstantiationDeclaration:
3844 case TSK_ExplicitInstantiationDefinition:
3845 // If a template instantiates to a non-literal type, but its members
3846 // instantiate to constexpr functions, the template is technically
Richard Smith86c3ae42012-02-13 03:54:03 +00003847 // ill-formed, but we allow it for sanity.
Richard Smith9f569cc2011-10-01 02:31:28 +00003848 continue;
3849
3850 case TSK_Undeclared:
3851 case TSK_ExplicitSpecialization:
David Blaikie262bc182012-04-30 02:36:29 +00003852 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
Douglas Gregorf502d8e2012-05-04 16:48:41 +00003853 diag::err_constexpr_method_non_literal);
Richard Smith9f569cc2011-10-01 02:31:28 +00003854 break;
3855 }
3856
3857 // Only produce one error per class.
3858 break;
3859 }
3860 }
3861 }
3862
Sebastian Redlf677ea32011-02-05 19:23:19 +00003863 // Declare inherited constructors. We do this eagerly here because:
3864 // - The standard requires an eager diagnostic for conflicting inherited
3865 // constructors from different classes.
3866 // - The lazy declaration of the other implicit constructors is so as to not
3867 // waste space and performance on classes that are not meant to be
3868 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3869 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003870 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003871}
3872
3873void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003874 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3875 ME = Record->method_end();
Richard Smith3003e1d2012-05-15 04:39:51 +00003876 MI != ME; ++MI)
3877 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
David Blaikie581deb32012-06-06 20:45:41 +00003878 CheckExplicitlyDefaultedSpecialMember(*MI);
Sean Hunt001cad92011-05-10 00:49:42 +00003879}
3880
Richard Smith7756afa2012-06-10 05:43:50 +00003881/// Is the special member function which would be selected to perform the
3882/// specified operation on the specified class type a constexpr constructor?
3883static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3884 Sema::CXXSpecialMember CSM,
3885 bool ConstArg) {
3886 Sema::SpecialMemberOverloadResult *SMOR =
3887 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
3888 false, false, false, false);
3889 if (!SMOR || !SMOR->getMethod())
3890 // A constructor we wouldn't select can't be "involved in initializing"
3891 // anything.
3892 return true;
3893 return SMOR->getMethod()->isConstexpr();
3894}
3895
3896/// Determine whether the specified special member function would be constexpr
3897/// if it were implicitly defined.
3898static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3899 Sema::CXXSpecialMember CSM,
3900 bool ConstArg) {
3901 if (!S.getLangOpts().CPlusPlus0x)
3902 return false;
3903
3904 // C++11 [dcl.constexpr]p4:
3905 // In the definition of a constexpr constructor [...]
3906 switch (CSM) {
3907 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00003908 // Since default constructor lookup is essentially trivial (and cannot
3909 // involve, for instance, template instantiation), we compute whether a
3910 // defaulted default constructor is constexpr directly within CXXRecordDecl.
3911 //
3912 // This is important for performance; we need to know whether the default
3913 // constructor is constexpr to determine whether the type is a literal type.
3914 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
3915
Richard Smith7756afa2012-06-10 05:43:50 +00003916 case Sema::CXXCopyConstructor:
3917 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00003918 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00003919 break;
3920
3921 case Sema::CXXCopyAssignment:
3922 case Sema::CXXMoveAssignment:
3923 case Sema::CXXDestructor:
3924 case Sema::CXXInvalid:
3925 return false;
3926 }
3927
3928 // -- if the class is a non-empty union, or for each non-empty anonymous
3929 // union member of a non-union class, exactly one non-static data member
3930 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00003931 //
3932 // If we squint, this is guaranteed, since exactly one non-static data member
3933 // will be initialized (if the constructor isn't deleted), we just don't know
3934 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00003935 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00003936 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00003937
3938 // -- the class shall not have any virtual base classes;
3939 if (ClassDecl->getNumVBases())
3940 return false;
3941
3942 // -- every constructor involved in initializing [...] base class
3943 // sub-objects shall be a constexpr constructor;
3944 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
3945 BEnd = ClassDecl->bases_end();
3946 B != BEnd; ++B) {
3947 const RecordType *BaseType = B->getType()->getAs<RecordType>();
3948 if (!BaseType) continue;
3949
3950 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
3951 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
3952 return false;
3953 }
3954
3955 // -- every constructor involved in initializing non-static data members
3956 // [...] shall be a constexpr constructor;
3957 // -- every non-static data member and base class sub-object shall be
3958 // initialized
3959 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
3960 FEnd = ClassDecl->field_end();
3961 F != FEnd; ++F) {
3962 if (F->isInvalidDecl())
3963 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00003964 if (const RecordType *RecordTy =
3965 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00003966 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
3967 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
3968 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00003969 }
3970 }
3971
3972 // All OK, it's constexpr!
3973 return true;
3974}
3975
Richard Smithb9d0b762012-07-27 04:22:15 +00003976static Sema::ImplicitExceptionSpecification
3977computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
3978 switch (S.getSpecialMember(MD)) {
3979 case Sema::CXXDefaultConstructor:
3980 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
3981 case Sema::CXXCopyConstructor:
3982 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
3983 case Sema::CXXCopyAssignment:
3984 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
3985 case Sema::CXXMoveConstructor:
3986 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
3987 case Sema::CXXMoveAssignment:
3988 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
3989 case Sema::CXXDestructor:
3990 return S.ComputeDefaultedDtorExceptionSpec(MD);
3991 case Sema::CXXInvalid:
3992 break;
3993 }
3994 llvm_unreachable("only special members have implicit exception specs");
3995}
3996
Richard Smithdd25e802012-07-30 23:48:14 +00003997static void
3998updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
3999 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4000 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4001 ExceptSpec.getEPI(EPI);
4002 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4003 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4004 FPT->getNumArgs(), EPI));
4005 FD->setType(QualType(NewFPT, 0));
4006}
4007
Richard Smithb9d0b762012-07-27 04:22:15 +00004008void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4009 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4010 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4011 return;
4012
Richard Smithdd25e802012-07-30 23:48:14 +00004013 // Evaluate the exception specification.
4014 ImplicitExceptionSpecification ExceptSpec =
4015 computeImplicitExceptionSpec(*this, Loc, MD);
4016
4017 // Update the type of the special member to use it.
4018 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4019
4020 // A user-provided destructor can be defined outside the class. When that
4021 // happens, be sure to update the exception specification on both
4022 // declarations.
4023 const FunctionProtoType *CanonicalFPT =
4024 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4025 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4026 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4027 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004028}
4029
4030static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4031static bool isImplicitCopyAssignmentArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4032
Richard Smith3003e1d2012-05-15 04:39:51 +00004033void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4034 CXXRecordDecl *RD = MD->getParent();
4035 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004036
Richard Smith3003e1d2012-05-15 04:39:51 +00004037 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4038 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004039
4040 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004041 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004042 bool First = MD == MD->getCanonicalDecl();
4043
4044 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004045
4046 // C++11 [dcl.fct.def.default]p1:
4047 // A function that is explicitly defaulted shall
4048 // -- be a special member function (checked elsewhere),
4049 // -- have the same type (except for ref-qualifiers, and except that a
4050 // copy operation can take a non-const reference) as an implicit
4051 // declaration, and
4052 // -- not have default arguments.
4053 unsigned ExpectedParams = 1;
4054 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4055 ExpectedParams = 0;
4056 if (MD->getNumParams() != ExpectedParams) {
4057 // This also checks for default arguments: a copy or move constructor with a
4058 // default argument is classified as a default constructor, and assignment
4059 // operations and destructors can't have default arguments.
4060 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4061 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004062 HadError = true;
4063 }
4064
Richard Smith3003e1d2012-05-15 04:39:51 +00004065 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004066
Richard Smithb9d0b762012-07-27 04:22:15 +00004067 // Compute argument constness, constexpr, and triviality.
Richard Smith7756afa2012-06-10 05:43:50 +00004068 bool CanHaveConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004069 bool Trivial;
4070 switch (CSM) {
4071 case CXXDefaultConstructor:
Richard Smith3003e1d2012-05-15 04:39:51 +00004072 Trivial = RD->hasTrivialDefaultConstructor();
4073 break;
4074 case CXXCopyConstructor:
Richard Smithb9d0b762012-07-27 04:22:15 +00004075 CanHaveConstParam = isImplicitCopyCtorArgConst(*this, RD);
Richard Smith3003e1d2012-05-15 04:39:51 +00004076 Trivial = RD->hasTrivialCopyConstructor();
4077 break;
4078 case CXXCopyAssignment:
Richard Smithb9d0b762012-07-27 04:22:15 +00004079 CanHaveConstParam = isImplicitCopyAssignmentArgConst(*this, RD);
Richard Smith3003e1d2012-05-15 04:39:51 +00004080 Trivial = RD->hasTrivialCopyAssignment();
4081 break;
4082 case CXXMoveConstructor:
Richard Smith3003e1d2012-05-15 04:39:51 +00004083 Trivial = RD->hasTrivialMoveConstructor();
4084 break;
4085 case CXXMoveAssignment:
Richard Smith3003e1d2012-05-15 04:39:51 +00004086 Trivial = RD->hasTrivialMoveAssignment();
4087 break;
4088 case CXXDestructor:
Richard Smith3003e1d2012-05-15 04:39:51 +00004089 Trivial = RD->hasTrivialDestructor();
4090 break;
4091 case CXXInvalid:
4092 llvm_unreachable("non-special member explicitly defaulted!");
4093 }
Sean Hunt2b188082011-05-14 05:23:28 +00004094
Richard Smith3003e1d2012-05-15 04:39:51 +00004095 QualType ReturnType = Context.VoidTy;
4096 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4097 // Check for return type matching.
4098 ReturnType = Type->getResultType();
4099 QualType ExpectedReturnType =
4100 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4101 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4102 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4103 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4104 HadError = true;
4105 }
4106
4107 // A defaulted special member cannot have cv-qualifiers.
4108 if (Type->getTypeQuals()) {
4109 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4110 << (CSM == CXXMoveAssignment);
4111 HadError = true;
4112 }
4113 }
4114
4115 // Check for parameter type matching.
4116 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004117 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004118 if (ExpectedParams && ArgType->isReferenceType()) {
4119 // Argument must be reference to possibly-const T.
4120 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004121 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004122
4123 if (ReferentType.isVolatileQualified()) {
4124 Diag(MD->getLocation(),
4125 diag::err_defaulted_special_member_volatile_param) << CSM;
4126 HadError = true;
4127 }
4128
Richard Smith7756afa2012-06-10 05:43:50 +00004129 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004130 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4131 Diag(MD->getLocation(),
4132 diag::err_defaulted_special_member_copy_const_param)
4133 << (CSM == CXXCopyAssignment);
4134 // FIXME: Explain why this special member can't be const.
4135 } else {
4136 Diag(MD->getLocation(),
4137 diag::err_defaulted_special_member_move_const_param)
4138 << (CSM == CXXMoveAssignment);
4139 }
4140 HadError = true;
4141 }
4142
4143 // If a function is explicitly defaulted on its first declaration, it shall
4144 // have the same parameter type as if it had been implicitly declared.
4145 // (Presumably this is to prevent it from being trivial?)
Richard Smith7756afa2012-06-10 05:43:50 +00004146 if (!HasConstParam && CanHaveConstParam && First)
Richard Smith3003e1d2012-05-15 04:39:51 +00004147 Diag(MD->getLocation(),
4148 diag::err_defaulted_special_member_copy_non_const_param)
4149 << (CSM == CXXCopyAssignment);
4150 } else if (ExpectedParams) {
4151 // A copy assignment operator can take its argument by value, but a
4152 // defaulted one cannot.
4153 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004154 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004155 HadError = true;
4156 }
Sean Huntbe631222011-05-17 20:44:43 +00004157
Richard Smithb9d0b762012-07-27 04:22:15 +00004158 // Rebuild the type with the implicit exception specification added, if we
4159 // are going to need it.
4160 const FunctionProtoType *ImplicitType = 0;
4161 if (First || Type->hasExceptionSpec()) {
4162 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4163 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4164 ImplicitType = cast<FunctionProtoType>(
4165 Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
4166 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004167
Richard Smith61802452011-12-22 02:22:31 +00004168 // C++11 [dcl.fct.def.default]p2:
4169 // An explicitly-defaulted function may be declared constexpr only if it
4170 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004171 // Do not apply this rule to members of class templates, since core issue 1358
4172 // makes such functions always instantiate to constexpr functions. For
4173 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004174 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4175 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004176 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4177 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4178 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004179 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004180 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004181 }
4182 // and may have an explicit exception-specification only if it is compatible
4183 // with the exception-specification on the implicit declaration.
Richard Smith3003e1d2012-05-15 04:39:51 +00004184 if (Type->hasExceptionSpec() &&
4185 CheckEquivalentExceptionSpec(
4186 PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
4187 PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
4188 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004189
4190 // If a function is explicitly defaulted on its first declaration,
4191 if (First) {
4192 // -- it is implicitly considered to be constexpr if the implicit
4193 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004194 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004195
Richard Smith3003e1d2012-05-15 04:39:51 +00004196 // -- it is implicitly considered to have the same exception-specification
4197 // as if it had been implicitly declared,
4198 MD->setType(QualType(ImplicitType, 0));
Richard Smithe653ba22012-02-26 00:31:33 +00004199
4200 // Such a function is also trivial if the implicitly-declared function
4201 // would have been.
Richard Smith3003e1d2012-05-15 04:39:51 +00004202 MD->setTrivial(Trivial);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004203 }
4204
Richard Smith3003e1d2012-05-15 04:39:51 +00004205 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004206 if (First) {
4207 MD->setDeletedAsWritten();
4208 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004209 // C++11 [dcl.fct.def.default]p4:
4210 // [For a] user-provided explicitly-defaulted function [...] if such a
4211 // function is implicitly defined as deleted, the program is ill-formed.
4212 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4213 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004214 }
4215 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004216
Richard Smith3003e1d2012-05-15 04:39:51 +00004217 if (HadError)
4218 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004219}
4220
Richard Smith7d5088a2012-02-18 02:02:13 +00004221namespace {
4222struct SpecialMemberDeletionInfo {
4223 Sema &S;
4224 CXXMethodDecl *MD;
4225 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004226 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004227
4228 // Properties of the special member, computed for convenience.
4229 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4230 SourceLocation Loc;
4231
4232 bool AllFieldsAreConst;
4233
4234 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004235 Sema::CXXSpecialMember CSM, bool Diagnose)
4236 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004237 IsConstructor(false), IsAssignment(false), IsMove(false),
4238 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4239 AllFieldsAreConst(true) {
4240 switch (CSM) {
4241 case Sema::CXXDefaultConstructor:
4242 case Sema::CXXCopyConstructor:
4243 IsConstructor = true;
4244 break;
4245 case Sema::CXXMoveConstructor:
4246 IsConstructor = true;
4247 IsMove = true;
4248 break;
4249 case Sema::CXXCopyAssignment:
4250 IsAssignment = true;
4251 break;
4252 case Sema::CXXMoveAssignment:
4253 IsAssignment = true;
4254 IsMove = true;
4255 break;
4256 case Sema::CXXDestructor:
4257 break;
4258 case Sema::CXXInvalid:
4259 llvm_unreachable("invalid special member kind");
4260 }
4261
4262 if (MD->getNumParams()) {
4263 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4264 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4265 }
4266 }
4267
4268 bool inUnion() const { return MD->getParent()->isUnion(); }
4269
4270 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004271 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4272 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004273 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004274 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4275 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4276 Quals = 0;
4277 return S.LookupSpecialMember(Class, CSM,
4278 ConstArg || (Quals & Qualifiers::Const),
4279 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004280 MD->getRefQualifier() == RQ_RValue,
4281 TQ & Qualifiers::Const,
4282 TQ & Qualifiers::Volatile);
4283 }
4284
Richard Smith6c4c36c2012-03-30 20:53:28 +00004285 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004286
Richard Smith6c4c36c2012-03-30 20:53:28 +00004287 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004288 bool shouldDeleteForField(FieldDecl *FD);
4289 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004290
Richard Smith517bb842012-07-18 03:51:16 +00004291 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4292 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004293 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4294 Sema::SpecialMemberOverloadResult *SMOR,
4295 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004296
4297 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004298};
4299}
4300
John McCall12d8d802012-04-09 20:53:23 +00004301/// Is the given special member inaccessible when used on the given
4302/// sub-object.
4303bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4304 CXXMethodDecl *target) {
4305 /// If we're operating on a base class, the object type is the
4306 /// type of this special member.
4307 QualType objectTy;
4308 AccessSpecifier access = target->getAccess();;
4309 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4310 objectTy = S.Context.getTypeDeclType(MD->getParent());
4311 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4312
4313 // If we're operating on a field, the object type is the type of the field.
4314 } else {
4315 objectTy = S.Context.getTypeDeclType(target->getParent());
4316 }
4317
4318 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4319}
4320
Richard Smith6c4c36c2012-03-30 20:53:28 +00004321/// Check whether we should delete a special member due to the implicit
4322/// definition containing a call to a special member of a subobject.
4323bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4324 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4325 bool IsDtorCallInCtor) {
4326 CXXMethodDecl *Decl = SMOR->getMethod();
4327 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4328
4329 int DiagKind = -1;
4330
4331 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4332 DiagKind = !Decl ? 0 : 1;
4333 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4334 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004335 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004336 DiagKind = 3;
4337 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4338 !Decl->isTrivial()) {
4339 // A member of a union must have a trivial corresponding special member.
4340 // As a weird special case, a destructor call from a union's constructor
4341 // must be accessible and non-deleted, but need not be trivial. Such a
4342 // destructor is never actually called, but is semantically checked as
4343 // if it were.
4344 DiagKind = 4;
4345 }
4346
4347 if (DiagKind == -1)
4348 return false;
4349
4350 if (Diagnose) {
4351 if (Field) {
4352 S.Diag(Field->getLocation(),
4353 diag::note_deleted_special_member_class_subobject)
4354 << CSM << MD->getParent() << /*IsField*/true
4355 << Field << DiagKind << IsDtorCallInCtor;
4356 } else {
4357 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4358 S.Diag(Base->getLocStart(),
4359 diag::note_deleted_special_member_class_subobject)
4360 << CSM << MD->getParent() << /*IsField*/false
4361 << Base->getType() << DiagKind << IsDtorCallInCtor;
4362 }
4363
4364 if (DiagKind == 1)
4365 S.NoteDeletedFunction(Decl);
4366 // FIXME: Explain inaccessibility if DiagKind == 3.
4367 }
4368
4369 return true;
4370}
4371
Richard Smith9a561d52012-02-26 09:11:52 +00004372/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004373/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004374bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004375 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004376 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004377
4378 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004379 // -- any direct or virtual base class, or non-static data member with no
4380 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004381 // either M has no default constructor or overload resolution as applied
4382 // to M's default constructor results in an ambiguity or in a function
4383 // that is deleted or inaccessible
4384 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4385 // -- a direct or virtual base class B that cannot be copied/moved because
4386 // overload resolution, as applied to B's corresponding special member,
4387 // results in an ambiguity or a function that is deleted or inaccessible
4388 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004389 // C++11 [class.dtor]p5:
4390 // -- any direct or virtual base class [...] has a type with a destructor
4391 // that is deleted or inaccessible
4392 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004393 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004394 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004395 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004396
Richard Smith6c4c36c2012-03-30 20:53:28 +00004397 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4398 // -- any direct or virtual base class or non-static data member has a
4399 // type with a destructor that is deleted or inaccessible
4400 if (IsConstructor) {
4401 Sema::SpecialMemberOverloadResult *SMOR =
4402 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4403 false, false, false, false, false);
4404 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4405 return true;
4406 }
4407
Richard Smith9a561d52012-02-26 09:11:52 +00004408 return false;
4409}
4410
4411/// Check whether we should delete a special member function due to the class
4412/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004413bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004414 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004415 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004416}
4417
4418/// Check whether we should delete a special member function due to the class
4419/// having a particular non-static data member.
4420bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4421 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4422 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4423
4424 if (CSM == Sema::CXXDefaultConstructor) {
4425 // For a default constructor, all references must be initialized in-class
4426 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004427 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4428 if (Diagnose)
4429 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4430 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004431 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004432 }
Richard Smith79363f52012-02-27 06:07:25 +00004433 // C++11 [class.ctor]p5: any non-variant non-static data member of
4434 // const-qualified type (or array thereof) with no
4435 // brace-or-equal-initializer does not have a user-provided default
4436 // constructor.
4437 if (!inUnion() && FieldType.isConstQualified() &&
4438 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004439 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4440 if (Diagnose)
4441 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004442 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004443 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004444 }
4445
4446 if (inUnion() && !FieldType.isConstQualified())
4447 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004448 } else if (CSM == Sema::CXXCopyConstructor) {
4449 // For a copy constructor, data members must not be of rvalue reference
4450 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004451 if (FieldType->isRValueReferenceType()) {
4452 if (Diagnose)
4453 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4454 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004455 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004456 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004457 } else if (IsAssignment) {
4458 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004459 if (FieldType->isReferenceType()) {
4460 if (Diagnose)
4461 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4462 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004463 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004464 }
4465 if (!FieldRecord && FieldType.isConstQualified()) {
4466 // C++11 [class.copy]p23:
4467 // -- a non-static data member of const non-class type (or array thereof)
4468 if (Diagnose)
4469 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004470 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004471 return true;
4472 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004473 }
4474
4475 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004476 // Some additional restrictions exist on the variant members.
4477 if (!inUnion() && FieldRecord->isUnion() &&
4478 FieldRecord->isAnonymousStructOrUnion()) {
4479 bool AllVariantFieldsAreConst = true;
4480
Richard Smithdf8dc862012-03-29 19:00:10 +00004481 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004482 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4483 UE = FieldRecord->field_end();
4484 UI != UE; ++UI) {
4485 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004486
4487 if (!UnionFieldType.isConstQualified())
4488 AllVariantFieldsAreConst = false;
4489
Richard Smith9a561d52012-02-26 09:11:52 +00004490 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4491 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004492 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4493 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004494 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004495 }
4496
4497 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004498 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004499 FieldRecord->field_begin() != FieldRecord->field_end()) {
4500 if (Diagnose)
4501 S.Diag(FieldRecord->getLocation(),
4502 diag::note_deleted_default_ctor_all_const)
4503 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004504 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004505 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004506
Richard Smithdf8dc862012-03-29 19:00:10 +00004507 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004508 // This is technically non-conformant, but sanity demands it.
4509 return false;
4510 }
4511
Richard Smith517bb842012-07-18 03:51:16 +00004512 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4513 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004514 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004515 }
4516
4517 return false;
4518}
4519
4520/// C++11 [class.ctor] p5:
4521/// A defaulted default constructor for a class X is defined as deleted if
4522/// X is a union and all of its variant members are of const-qualified type.
4523bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004524 // This is a silly definition, because it gives an empty union a deleted
4525 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004526 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4527 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4528 if (Diagnose)
4529 S.Diag(MD->getParent()->getLocation(),
4530 diag::note_deleted_default_ctor_all_const)
4531 << MD->getParent() << /*not anonymous union*/0;
4532 return true;
4533 }
4534 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004535}
4536
4537/// Determine whether a defaulted special member function should be defined as
4538/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4539/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004540bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4541 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004542 if (MD->isInvalidDecl())
4543 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004544 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004545 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004546 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004547 return false;
4548
Richard Smith7d5088a2012-02-18 02:02:13 +00004549 // C++11 [expr.lambda.prim]p19:
4550 // The closure type associated with a lambda-expression has a
4551 // deleted (8.4.3) default constructor and a deleted copy
4552 // assignment operator.
4553 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004554 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4555 if (Diagnose)
4556 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004557 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004558 }
4559
Richard Smith5bdaac52012-04-02 20:59:25 +00004560 // For an anonymous struct or union, the copy and assignment special members
4561 // will never be used, so skip the check. For an anonymous union declared at
4562 // namespace scope, the constructor and destructor are used.
4563 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4564 RD->isAnonymousStructOrUnion())
4565 return false;
4566
Richard Smith6c4c36c2012-03-30 20:53:28 +00004567 // C++11 [class.copy]p7, p18:
4568 // If the class definition declares a move constructor or move assignment
4569 // operator, an implicitly declared copy constructor or copy assignment
4570 // operator is defined as deleted.
4571 if (MD->isImplicit() &&
4572 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4573 CXXMethodDecl *UserDeclaredMove = 0;
4574
4575 // In Microsoft mode, a user-declared move only causes the deletion of the
4576 // corresponding copy operation, not both copy operations.
4577 if (RD->hasUserDeclaredMoveConstructor() &&
4578 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4579 if (!Diagnose) return true;
4580 UserDeclaredMove = RD->getMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00004581 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004582 } else if (RD->hasUserDeclaredMoveAssignment() &&
4583 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4584 if (!Diagnose) return true;
4585 UserDeclaredMove = RD->getMoveAssignmentOperator();
Richard Smith1c931be2012-04-02 18:40:40 +00004586 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004587 }
4588
4589 if (UserDeclaredMove) {
4590 Diag(UserDeclaredMove->getLocation(),
4591 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004592 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004593 << UserDeclaredMove->isMoveAssignmentOperator();
4594 return true;
4595 }
4596 }
Sean Hunte16da072011-10-10 06:18:57 +00004597
Richard Smith5bdaac52012-04-02 20:59:25 +00004598 // Do access control from the special member function
4599 ContextRAII MethodContext(*this, MD);
4600
Richard Smith9a561d52012-02-26 09:11:52 +00004601 // C++11 [class.dtor]p5:
4602 // -- for a virtual destructor, lookup of the non-array deallocation function
4603 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004604 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004605 FunctionDecl *OperatorDelete = 0;
4606 DeclarationName Name =
4607 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4608 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004609 OperatorDelete, false)) {
4610 if (Diagnose)
4611 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004612 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004613 }
Richard Smith9a561d52012-02-26 09:11:52 +00004614 }
4615
Richard Smith6c4c36c2012-03-30 20:53:28 +00004616 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004617
Sean Huntcdee3fe2011-05-11 22:34:38 +00004618 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004619 BE = RD->bases_end(); BI != BE; ++BI)
4620 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004621 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004622 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004623
4624 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004625 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004626 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004627 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004628
4629 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004630 FE = RD->field_end(); FI != FE; ++FI)
4631 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004632 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004633 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004634
Richard Smith7d5088a2012-02-18 02:02:13 +00004635 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004636 return true;
4637
4638 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004639}
4640
4641/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004642namespace {
4643 struct FindHiddenVirtualMethodData {
4644 Sema *S;
4645 CXXMethodDecl *Method;
4646 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004647 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004648 };
4649}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004650
4651/// \brief Member lookup function that determines whether a given C++
4652/// method overloads virtual methods in a base class without overriding any,
4653/// to be used with CXXRecordDecl::lookupInBases().
4654static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4655 CXXBasePath &Path,
4656 void *UserData) {
4657 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4658
4659 FindHiddenVirtualMethodData &Data
4660 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4661
4662 DeclarationName Name = Data.Method->getDeclName();
4663 assert(Name.getNameKind() == DeclarationName::Identifier);
4664
4665 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004666 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004667 for (Path.Decls = BaseRecord->lookup(Name);
4668 Path.Decls.first != Path.Decls.second;
4669 ++Path.Decls.first) {
4670 NamedDecl *D = *Path.Decls.first;
4671 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004672 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004673 foundSameNameMethod = true;
4674 // Interested only in hidden virtual methods.
4675 if (!MD->isVirtual())
4676 continue;
4677 // If the method we are checking overrides a method from its base
4678 // don't warn about the other overloaded methods.
4679 if (!Data.S->IsOverload(Data.Method, MD, false))
4680 return true;
4681 // Collect the overload only if its hidden.
4682 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4683 overloadedMethods.push_back(MD);
4684 }
4685 }
4686
4687 if (foundSameNameMethod)
4688 Data.OverloadedMethods.append(overloadedMethods.begin(),
4689 overloadedMethods.end());
4690 return foundSameNameMethod;
4691}
4692
4693/// \brief See if a method overloads virtual methods in a base class without
4694/// overriding any.
4695void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4696 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004697 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004698 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00004699 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004700 return;
4701
4702 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4703 /*bool RecordPaths=*/false,
4704 /*bool DetectVirtual=*/false);
4705 FindHiddenVirtualMethodData Data;
4706 Data.Method = MD;
4707 Data.S = this;
4708
4709 // Keep the base methods that were overriden or introduced in the subclass
4710 // by 'using' in a set. A base method not in this set is hidden.
4711 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4712 res.first != res.second; ++res.first) {
4713 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4714 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4715 E = MD->end_overridden_methods();
4716 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004717 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004718 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4719 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004720 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004721 }
4722
4723 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4724 !Data.OverloadedMethods.empty()) {
4725 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4726 << MD << (Data.OverloadedMethods.size() > 1);
4727
4728 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4729 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4730 Diag(overloadedMD->getLocation(),
4731 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4732 }
4733 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004734}
4735
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004736void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004737 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004738 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004739 SourceLocation RBrac,
4740 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004741 if (!TagDecl)
4742 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004743
Douglas Gregor42af25f2009-05-11 19:58:34 +00004744 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004745
Rafael Espindolaf729ce02012-07-12 04:32:30 +00004746 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4747 if (l->getKind() != AttributeList::AT_Visibility)
4748 continue;
4749 l->setInvalid();
4750 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
4751 l->getName();
4752 }
4753
David Blaikie77b6de02011-09-22 02:58:26 +00004754 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00004755 // strict aliasing violation!
4756 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00004757 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004758
Douglas Gregor23c94db2010-07-02 17:43:08 +00004759 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004760 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004761}
4762
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004763/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4764/// special functions, such as the default constructor, copy
4765/// constructor, or destructor, to the given C++ class (C++
4766/// [special]p1). This routine can only be executed just before the
4767/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004768void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004769 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004770 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004771
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004772 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004773 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004774
David Blaikie4e4d0842012-03-11 07:00:24 +00004775 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
Richard Smithb701d3d2011-12-24 21:56:24 +00004776 ++ASTContext::NumImplicitMoveConstructors;
4777
Douglas Gregora376d102010-07-02 21:50:04 +00004778 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4779 ++ASTContext::NumImplicitCopyAssignmentOperators;
4780
4781 // If we have a dynamic class, then the copy assignment operator may be
4782 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4783 // it shows up in the right place in the vtable and that we diagnose
4784 // problems with the implicit exception specification.
4785 if (ClassDecl->isDynamicClass())
4786 DeclareImplicitCopyAssignment(ClassDecl);
4787 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004788
Richard Smith1c931be2012-04-02 18:40:40 +00004789 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00004790 ++ASTContext::NumImplicitMoveAssignmentOperators;
4791
4792 // Likewise for the move assignment operator.
4793 if (ClassDecl->isDynamicClass())
4794 DeclareImplicitMoveAssignment(ClassDecl);
4795 }
4796
Douglas Gregor4923aa22010-07-02 20:37:36 +00004797 if (!ClassDecl->hasUserDeclaredDestructor()) {
4798 ++ASTContext::NumImplicitDestructors;
4799
4800 // If we have a dynamic class, then the destructor may be virtual, so we
4801 // have to declare the destructor immediately. This ensures that, e.g., it
4802 // shows up in the right place in the vtable and that we diagnose problems
4803 // with the implicit exception specification.
4804 if (ClassDecl->isDynamicClass())
4805 DeclareImplicitDestructor(ClassDecl);
4806 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004807}
4808
Francois Pichet8387e2a2011-04-22 22:18:13 +00004809void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4810 if (!D)
4811 return;
4812
4813 int NumParamList = D->getNumTemplateParameterLists();
4814 for (int i = 0; i < NumParamList; i++) {
4815 TemplateParameterList* Params = D->getTemplateParameterList(i);
4816 for (TemplateParameterList::iterator Param = Params->begin(),
4817 ParamEnd = Params->end();
4818 Param != ParamEnd; ++Param) {
4819 NamedDecl *Named = cast<NamedDecl>(*Param);
4820 if (Named->getDeclName()) {
4821 S->AddDecl(Named);
4822 IdResolver.AddDecl(Named);
4823 }
4824 }
4825 }
4826}
4827
John McCalld226f652010-08-21 09:40:31 +00004828void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004829 if (!D)
4830 return;
4831
4832 TemplateParameterList *Params = 0;
4833 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4834 Params = Template->getTemplateParameters();
4835 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4836 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4837 Params = PartialSpec->getTemplateParameters();
4838 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004839 return;
4840
Douglas Gregor6569d682009-05-27 23:11:45 +00004841 for (TemplateParameterList::iterator Param = Params->begin(),
4842 ParamEnd = Params->end();
4843 Param != ParamEnd; ++Param) {
4844 NamedDecl *Named = cast<NamedDecl>(*Param);
4845 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004846 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004847 IdResolver.AddDecl(Named);
4848 }
4849 }
4850}
4851
John McCalld226f652010-08-21 09:40:31 +00004852void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004853 if (!RecordD) return;
4854 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004855 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004856 PushDeclContext(S, Record);
4857}
4858
John McCalld226f652010-08-21 09:40:31 +00004859void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004860 if (!RecordD) return;
4861 PopDeclContext();
4862}
4863
Douglas Gregor72b505b2008-12-16 21:30:33 +00004864/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4865/// parsing a top-level (non-nested) C++ class, and we are now
4866/// parsing those parts of the given Method declaration that could
4867/// not be parsed earlier (C++ [class.mem]p2), such as default
4868/// arguments. This action should enter the scope of the given
4869/// Method declaration as if we had just parsed the qualified method
4870/// name. However, it should not bring the parameters into scope;
4871/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004872void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004873}
4874
4875/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4876/// C++ method declaration. We're (re-)introducing the given
4877/// function parameter into scope for use in parsing later parts of
4878/// the method declaration. For example, we could see an
4879/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004880void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004881 if (!ParamD)
4882 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004883
John McCalld226f652010-08-21 09:40:31 +00004884 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004885
4886 // If this parameter has an unparsed default argument, clear it out
4887 // to make way for the parsed default argument.
4888 if (Param->hasUnparsedDefaultArg())
4889 Param->setDefaultArg(0);
4890
John McCalld226f652010-08-21 09:40:31 +00004891 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004892 if (Param->getDeclName())
4893 IdResolver.AddDecl(Param);
4894}
4895
4896/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4897/// processing the delayed method declaration for Method. The method
4898/// declaration is now considered finished. There may be a separate
4899/// ActOnStartOfFunctionDef action later (not necessarily
4900/// immediately!) for this method, if it was also defined inside the
4901/// class body.
John McCalld226f652010-08-21 09:40:31 +00004902void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004903 if (!MethodD)
4904 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004905
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004906 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004907
John McCalld226f652010-08-21 09:40:31 +00004908 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004909
4910 // Now that we have our default arguments, check the constructor
4911 // again. It could produce additional diagnostics or affect whether
4912 // the class has implicitly-declared destructors, among other
4913 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004914 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4915 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004916
4917 // Check the default arguments, which we may have added.
4918 if (!Method->isInvalidDecl())
4919 CheckCXXDefaultArguments(Method);
4920}
4921
Douglas Gregor42a552f2008-11-05 20:51:48 +00004922/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004923/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004924/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004925/// emit diagnostics and set the invalid bit to true. In any case, the type
4926/// will be updated to reflect a well-formed type for the constructor and
4927/// returned.
4928QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004929 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004930 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004931
4932 // C++ [class.ctor]p3:
4933 // A constructor shall not be virtual (10.3) or static (9.4). A
4934 // constructor can be invoked for a const, volatile or const
4935 // volatile object. A constructor shall not be declared const,
4936 // volatile, or const volatile (9.3.2).
4937 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004938 if (!D.isInvalidType())
4939 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4940 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4941 << SourceRange(D.getIdentifierLoc());
4942 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004943 }
John McCalld931b082010-08-26 03:08:43 +00004944 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004945 if (!D.isInvalidType())
4946 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4947 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4948 << SourceRange(D.getIdentifierLoc());
4949 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004950 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004951 }
Mike Stump1eb44332009-09-09 15:08:12 +00004952
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004953 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004954 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004955 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004956 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4957 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004958 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004959 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4960 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004961 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004962 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4963 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004964 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004965 }
Mike Stump1eb44332009-09-09 15:08:12 +00004966
Douglas Gregorc938c162011-01-26 05:01:58 +00004967 // C++0x [class.ctor]p4:
4968 // A constructor shall not be declared with a ref-qualifier.
4969 if (FTI.hasRefQualifier()) {
4970 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4971 << FTI.RefQualifierIsLValueRef
4972 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4973 D.setInvalidType();
4974 }
4975
Douglas Gregor42a552f2008-11-05 20:51:48 +00004976 // Rebuild the function type "R" without any type qualifiers (in
4977 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004978 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004979 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004980 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4981 return R;
4982
4983 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4984 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004985 EPI.RefQualifier = RQ_None;
4986
Chris Lattner65401802009-04-25 08:28:21 +00004987 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004988 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004989}
4990
Douglas Gregor72b505b2008-12-16 21:30:33 +00004991/// CheckConstructor - Checks a fully-formed constructor for
4992/// well-formedness, issuing any diagnostics required. Returns true if
4993/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004994void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004995 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004996 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4997 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00004998 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004999
5000 // C++ [class.copy]p3:
5001 // A declaration of a constructor for a class X is ill-formed if
5002 // its first parameter is of type (optionally cv-qualified) X and
5003 // either there are no other parameters or else all other
5004 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005005 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005006 ((Constructor->getNumParams() == 1) ||
5007 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005008 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5009 Constructor->getTemplateSpecializationKind()
5010 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005011 QualType ParamType = Constructor->getParamDecl(0)->getType();
5012 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5013 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005014 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005015 const char *ConstRef
5016 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5017 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005018 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005019 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005020
5021 // FIXME: Rather that making the constructor invalid, we should endeavor
5022 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005023 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005024 }
5025 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005026}
5027
John McCall15442822010-08-04 01:04:25 +00005028/// CheckDestructor - Checks a fully-formed destructor definition for
5029/// well-formedness, issuing any diagnostics required. Returns true
5030/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005031bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005032 CXXRecordDecl *RD = Destructor->getParent();
5033
5034 if (Destructor->isVirtual()) {
5035 SourceLocation Loc;
5036
5037 if (!Destructor->isImplicit())
5038 Loc = Destructor->getLocation();
5039 else
5040 Loc = RD->getLocation();
5041
5042 // If we have a virtual destructor, look up the deallocation function
5043 FunctionDecl *OperatorDelete = 0;
5044 DeclarationName Name =
5045 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005046 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005047 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005048
Eli Friedman5f2987c2012-02-02 03:46:19 +00005049 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005050
5051 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005052 }
Anders Carlsson37909802009-11-30 21:24:50 +00005053
5054 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005055}
5056
Mike Stump1eb44332009-09-09 15:08:12 +00005057static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005058FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5059 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5060 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005061 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005062}
5063
Douglas Gregor42a552f2008-11-05 20:51:48 +00005064/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5065/// the well-formednes of the destructor declarator @p D with type @p
5066/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005067/// emit diagnostics and set the declarator to invalid. Even if this happens,
5068/// will be updated to reflect a well-formed type for the destructor and
5069/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005070QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005071 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005072 // C++ [class.dtor]p1:
5073 // [...] A typedef-name that names a class is a class-name
5074 // (7.1.3); however, a typedef-name that names a class shall not
5075 // be used as the identifier in the declarator for a destructor
5076 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005077 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005078 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005079 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005080 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005081 else if (const TemplateSpecializationType *TST =
5082 DeclaratorType->getAs<TemplateSpecializationType>())
5083 if (TST->isTypeAlias())
5084 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5085 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005086
5087 // C++ [class.dtor]p2:
5088 // A destructor is used to destroy objects of its class type. A
5089 // destructor takes no parameters, and no return type can be
5090 // specified for it (not even void). The address of a destructor
5091 // shall not be taken. A destructor shall not be static. A
5092 // destructor can be invoked for a const, volatile or const
5093 // volatile object. A destructor shall not be declared const,
5094 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005095 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005096 if (!D.isInvalidType())
5097 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5098 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005099 << SourceRange(D.getIdentifierLoc())
5100 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5101
John McCalld931b082010-08-26 03:08:43 +00005102 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005103 }
Chris Lattner65401802009-04-25 08:28:21 +00005104 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005105 // Destructors don't have return types, but the parser will
5106 // happily parse something like:
5107 //
5108 // class X {
5109 // float ~X();
5110 // };
5111 //
5112 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005113 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5114 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5115 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005116 }
Mike Stump1eb44332009-09-09 15:08:12 +00005117
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005118 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005119 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005120 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005121 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5122 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005123 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005124 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5125 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005126 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005127 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5128 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005129 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005130 }
5131
Douglas Gregorc938c162011-01-26 05:01:58 +00005132 // C++0x [class.dtor]p2:
5133 // A destructor shall not be declared with a ref-qualifier.
5134 if (FTI.hasRefQualifier()) {
5135 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5136 << FTI.RefQualifierIsLValueRef
5137 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5138 D.setInvalidType();
5139 }
5140
Douglas Gregor42a552f2008-11-05 20:51:48 +00005141 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005142 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005143 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5144
5145 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005146 FTI.freeArgs();
5147 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005148 }
5149
Mike Stump1eb44332009-09-09 15:08:12 +00005150 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005151 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005152 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005153 D.setInvalidType();
5154 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005155
5156 // Rebuild the function type "R" without any type qualifiers or
5157 // parameters (in case any of the errors above fired) and with
5158 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005159 // types.
John McCalle23cf432010-12-14 08:05:40 +00005160 if (!D.isInvalidType())
5161 return R;
5162
Douglas Gregord92ec472010-07-01 05:10:53 +00005163 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005164 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5165 EPI.Variadic = false;
5166 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005167 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005168 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005169}
5170
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005171/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5172/// well-formednes of the conversion function declarator @p D with
5173/// type @p R. If there are any errors in the declarator, this routine
5174/// will emit diagnostics and return true. Otherwise, it will return
5175/// false. Either way, the type @p R will be updated to reflect a
5176/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005177void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005178 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005179 // C++ [class.conv.fct]p1:
5180 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005181 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005182 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005183 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005184 if (!D.isInvalidType())
5185 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5186 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5187 << SourceRange(D.getIdentifierLoc());
5188 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005189 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005190 }
John McCalla3f81372010-04-13 00:04:31 +00005191
5192 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5193
Chris Lattner6e475012009-04-25 08:35:12 +00005194 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005195 // Conversion functions don't have return types, but the parser will
5196 // happily parse something like:
5197 //
5198 // class X {
5199 // float operator bool();
5200 // };
5201 //
5202 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005203 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5204 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5205 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005206 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005207 }
5208
John McCalla3f81372010-04-13 00:04:31 +00005209 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5210
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005211 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005212 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005213 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5214
5215 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005216 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005217 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005218 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005219 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005220 D.setInvalidType();
5221 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005222
John McCalla3f81372010-04-13 00:04:31 +00005223 // Diagnose "&operator bool()" and other such nonsense. This
5224 // is actually a gcc extension which we don't support.
5225 if (Proto->getResultType() != ConvType) {
5226 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5227 << Proto->getResultType();
5228 D.setInvalidType();
5229 ConvType = Proto->getResultType();
5230 }
5231
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005232 // C++ [class.conv.fct]p4:
5233 // The conversion-type-id shall not represent a function type nor
5234 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005235 if (ConvType->isArrayType()) {
5236 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5237 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005238 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005239 } else if (ConvType->isFunctionType()) {
5240 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5241 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005242 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005243 }
5244
5245 // Rebuild the function type "R" without any parameters (in case any
5246 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005247 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005248 if (D.isInvalidType())
5249 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005250
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005251 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005252 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005253 Diag(D.getDeclSpec().getExplicitSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005254 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005255 diag::warn_cxx98_compat_explicit_conversion_functions :
5256 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005257 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005258}
5259
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005260/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5261/// the declaration of the given C++ conversion function. This routine
5262/// is responsible for recording the conversion function in the C++
5263/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005264Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005265 assert(Conversion && "Expected to receive a conversion function declaration");
5266
Douglas Gregor9d350972008-12-12 08:25:50 +00005267 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005268
5269 // Make sure we aren't redeclaring the conversion function.
5270 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005271
5272 // C++ [class.conv.fct]p1:
5273 // [...] A conversion function is never used to convert a
5274 // (possibly cv-qualified) object to the (possibly cv-qualified)
5275 // same object type (or a reference to it), to a (possibly
5276 // cv-qualified) base class of that type (or a reference to it),
5277 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005278 // FIXME: Suppress this warning if the conversion function ends up being a
5279 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005280 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005281 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005282 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005283 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005284 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5285 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005286 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005287 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005288 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5289 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005290 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005291 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005292 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005293 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005294 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005295 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005296 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005297 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005298 }
5299
Douglas Gregore80622f2010-09-29 04:25:11 +00005300 if (FunctionTemplateDecl *ConversionTemplate
5301 = Conversion->getDescribedFunctionTemplate())
5302 return ConversionTemplate;
5303
John McCalld226f652010-08-21 09:40:31 +00005304 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005305}
5306
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005307//===----------------------------------------------------------------------===//
5308// Namespace Handling
5309//===----------------------------------------------------------------------===//
5310
John McCallea318642010-08-26 09:15:37 +00005311
5312
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005313/// ActOnStartNamespaceDef - This is called at the start of a namespace
5314/// definition.
John McCalld226f652010-08-21 09:40:31 +00005315Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005316 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005317 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005318 SourceLocation IdentLoc,
5319 IdentifierInfo *II,
5320 SourceLocation LBrace,
5321 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005322 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5323 // For anonymous namespace, take the location of the left brace.
5324 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005325 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005326 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005327 bool IsStd = false;
5328 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005329 Scope *DeclRegionScope = NamespcScope->getParent();
5330
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005331 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005332 if (II) {
5333 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005334 // The identifier in an original-namespace-definition shall not
5335 // have been previously defined in the declarative region in
5336 // which the original-namespace-definition appears. The
5337 // identifier in an original-namespace-definition is the name of
5338 // the namespace. Subsequently in that declarative region, it is
5339 // treated as an original-namespace-name.
5340 //
5341 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005342 // look through using directives, just look for any ordinary names.
5343
5344 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005345 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5346 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005347 NamedDecl *PrevDecl = 0;
5348 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005349 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005350 R.first != R.second; ++R.first) {
5351 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5352 PrevDecl = *R.first;
5353 break;
5354 }
5355 }
5356
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005357 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5358
5359 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005360 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005361 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005362 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005363 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005364 // The user probably just forgot the 'inline', so suggest that it
5365 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005366 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005367 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5368 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005369 Diag(Loc, diag::err_inline_namespace_mismatch)
5370 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005371 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005372 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5373
5374 IsInline = PrevNS->isInline();
5375 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005376 } else if (PrevDecl) {
5377 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005378 Diag(Loc, diag::err_redefinition_different_kind)
5379 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005380 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005381 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005382 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005383 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005384 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005385 // This is the first "real" definition of the namespace "std", so update
5386 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005387 PrevNS = getStdNamespace();
5388 IsStd = true;
5389 AddToKnown = !IsInline;
5390 } else {
5391 // We've seen this namespace for the first time.
5392 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005393 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005394 } else {
John McCall9aeed322009-10-01 00:25:31 +00005395 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005396
5397 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005398 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005399 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005400 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005401 } else {
5402 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005403 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005404 }
5405
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005406 if (PrevNS && IsInline != PrevNS->isInline()) {
5407 // inline-ness must match
5408 Diag(Loc, diag::err_inline_namespace_mismatch)
5409 << IsInline;
5410 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005411
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005412 // Recover by ignoring the new namespace's inline status.
5413 IsInline = PrevNS->isInline();
5414 }
5415 }
5416
5417 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5418 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005419 if (IsInvalid)
5420 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005421
5422 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005423
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005424 // FIXME: Should we be merging attributes?
5425 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005426 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005427
5428 if (IsStd)
5429 StdNamespace = Namespc;
5430 if (AddToKnown)
5431 KnownNamespaces[Namespc] = false;
5432
5433 if (II) {
5434 PushOnScopeChains(Namespc, DeclRegionScope);
5435 } else {
5436 // Link the anonymous namespace into its parent.
5437 DeclContext *Parent = CurContext->getRedeclContext();
5438 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5439 TU->setAnonymousNamespace(Namespc);
5440 } else {
5441 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005442 }
John McCall9aeed322009-10-01 00:25:31 +00005443
Douglas Gregora4181472010-03-24 00:46:35 +00005444 CurContext->addDecl(Namespc);
5445
John McCall9aeed322009-10-01 00:25:31 +00005446 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5447 // behaves as if it were replaced by
5448 // namespace unique { /* empty body */ }
5449 // using namespace unique;
5450 // namespace unique { namespace-body }
5451 // where all occurrences of 'unique' in a translation unit are
5452 // replaced by the same identifier and this identifier differs
5453 // from all other identifiers in the entire program.
5454
5455 // We just create the namespace with an empty name and then add an
5456 // implicit using declaration, just like the standard suggests.
5457 //
5458 // CodeGen enforces the "universally unique" aspect by giving all
5459 // declarations semantically contained within an anonymous
5460 // namespace internal linkage.
5461
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005462 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005463 UsingDirectiveDecl* UD
5464 = UsingDirectiveDecl::Create(Context, CurContext,
5465 /* 'using' */ LBrace,
5466 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005467 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005468 /* identifier */ SourceLocation(),
5469 Namespc,
5470 /* Ancestor */ CurContext);
5471 UD->setImplicit();
5472 CurContext->addDecl(UD);
5473 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005474 }
5475
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00005476 ActOnDocumentableDecl(Namespc);
5477
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005478 // Although we could have an invalid decl (i.e. the namespace name is a
5479 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005480 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5481 // for the namespace has the declarations that showed up in that particular
5482 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005483 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005484 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005485}
5486
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005487/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5488/// is a namespace alias, returns the namespace it points to.
5489static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5490 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5491 return AD->getNamespace();
5492 return dyn_cast_or_null<NamespaceDecl>(D);
5493}
5494
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005495/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5496/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005497void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005498 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5499 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005500 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005501 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005502 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005503 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005504}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005505
John McCall384aff82010-08-25 07:42:41 +00005506CXXRecordDecl *Sema::getStdBadAlloc() const {
5507 return cast_or_null<CXXRecordDecl>(
5508 StdBadAlloc.get(Context.getExternalSource()));
5509}
5510
5511NamespaceDecl *Sema::getStdNamespace() const {
5512 return cast_or_null<NamespaceDecl>(
5513 StdNamespace.get(Context.getExternalSource()));
5514}
5515
Douglas Gregor66992202010-06-29 17:53:46 +00005516/// \brief Retrieve the special "std" namespace, which may require us to
5517/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005518NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005519 if (!StdNamespace) {
5520 // The "std" namespace has not yet been defined, so build one implicitly.
5521 StdNamespace = NamespaceDecl::Create(Context,
5522 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005523 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005524 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005525 &PP.getIdentifierTable().get("std"),
5526 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005527 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005528 }
5529
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005530 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005531}
5532
Sebastian Redl395e04d2012-01-17 22:49:33 +00005533bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005534 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00005535 "Looking for std::initializer_list outside of C++.");
5536
5537 // We're looking for implicit instantiations of
5538 // template <typename E> class std::initializer_list.
5539
5540 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5541 return false;
5542
Sebastian Redl84760e32012-01-17 22:49:58 +00005543 ClassTemplateDecl *Template = 0;
5544 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005545
Sebastian Redl84760e32012-01-17 22:49:58 +00005546 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005547
Sebastian Redl84760e32012-01-17 22:49:58 +00005548 ClassTemplateSpecializationDecl *Specialization =
5549 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5550 if (!Specialization)
5551 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005552
Sebastian Redl84760e32012-01-17 22:49:58 +00005553 Template = Specialization->getSpecializedTemplate();
5554 Arguments = Specialization->getTemplateArgs().data();
5555 } else if (const TemplateSpecializationType *TST =
5556 Ty->getAs<TemplateSpecializationType>()) {
5557 Template = dyn_cast_or_null<ClassTemplateDecl>(
5558 TST->getTemplateName().getAsTemplateDecl());
5559 Arguments = TST->getArgs();
5560 }
5561 if (!Template)
5562 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005563
5564 if (!StdInitializerList) {
5565 // Haven't recognized std::initializer_list yet, maybe this is it.
5566 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5567 if (TemplateClass->getIdentifier() !=
5568 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005569 !getStdNamespace()->InEnclosingNamespaceSetOf(
5570 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005571 return false;
5572 // This is a template called std::initializer_list, but is it the right
5573 // template?
5574 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005575 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005576 return false;
5577 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5578 return false;
5579
5580 // It's the right template.
5581 StdInitializerList = Template;
5582 }
5583
5584 if (Template != StdInitializerList)
5585 return false;
5586
5587 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005588 if (Element)
5589 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005590 return true;
5591}
5592
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005593static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5594 NamespaceDecl *Std = S.getStdNamespace();
5595 if (!Std) {
5596 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5597 return 0;
5598 }
5599
5600 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5601 Loc, Sema::LookupOrdinaryName);
5602 if (!S.LookupQualifiedName(Result, Std)) {
5603 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5604 return 0;
5605 }
5606 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5607 if (!Template) {
5608 Result.suppressDiagnostics();
5609 // We found something weird. Complain about the first thing we found.
5610 NamedDecl *Found = *Result.begin();
5611 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5612 return 0;
5613 }
5614
5615 // We found some template called std::initializer_list. Now verify that it's
5616 // correct.
5617 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005618 if (Params->getMinRequiredArguments() != 1 ||
5619 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005620 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5621 return 0;
5622 }
5623
5624 return Template;
5625}
5626
5627QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5628 if (!StdInitializerList) {
5629 StdInitializerList = LookupStdInitializerList(*this, Loc);
5630 if (!StdInitializerList)
5631 return QualType();
5632 }
5633
5634 TemplateArgumentListInfo Args(Loc, Loc);
5635 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5636 Context.getTrivialTypeSourceInfo(Element,
5637 Loc)));
5638 return Context.getCanonicalType(
5639 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5640}
5641
Sebastian Redl98d36062012-01-17 22:50:14 +00005642bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5643 // C++ [dcl.init.list]p2:
5644 // A constructor is an initializer-list constructor if its first parameter
5645 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5646 // std::initializer_list<E> for some type E, and either there are no other
5647 // parameters or else all other parameters have default arguments.
5648 if (Ctor->getNumParams() < 1 ||
5649 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5650 return false;
5651
5652 QualType ArgType = Ctor->getParamDecl(0)->getType();
5653 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5654 ArgType = RT->getPointeeType().getUnqualifiedType();
5655
5656 return isStdInitializerList(ArgType, 0);
5657}
5658
Douglas Gregor9172aa62011-03-26 22:25:30 +00005659/// \brief Determine whether a using statement is in a context where it will be
5660/// apply in all contexts.
5661static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5662 switch (CurContext->getDeclKind()) {
5663 case Decl::TranslationUnit:
5664 return true;
5665 case Decl::LinkageSpec:
5666 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5667 default:
5668 return false;
5669 }
5670}
5671
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005672namespace {
5673
5674// Callback to only accept typo corrections that are namespaces.
5675class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5676 public:
5677 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5678 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5679 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5680 }
5681 return false;
5682 }
5683};
5684
5685}
5686
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005687static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5688 CXXScopeSpec &SS,
5689 SourceLocation IdentLoc,
5690 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005691 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005692 R.clear();
5693 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005694 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005695 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005696 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5697 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005698 if (DeclContext *DC = S.computeDeclContext(SS, false))
5699 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5700 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5701 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5702 else
5703 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5704 << Ident << CorrectedQuotedStr
5705 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005706
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005707 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5708 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005709
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005710 R.addDecl(Corrected.getCorrectionDecl());
5711 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005712 }
5713 return false;
5714}
5715
John McCalld226f652010-08-21 09:40:31 +00005716Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005717 SourceLocation UsingLoc,
5718 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005719 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005720 SourceLocation IdentLoc,
5721 IdentifierInfo *NamespcName,
5722 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005723 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5724 assert(NamespcName && "Invalid NamespcName.");
5725 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005726
5727 // This can only happen along a recovery path.
5728 while (S->getFlags() & Scope::TemplateParamScope)
5729 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005730 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005731
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005732 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005733 NestedNameSpecifier *Qualifier = 0;
5734 if (SS.isSet())
5735 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5736
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005737 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005738 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5739 LookupParsedName(R, S, &SS);
5740 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005741 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005742
Douglas Gregor66992202010-06-29 17:53:46 +00005743 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005744 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005745 // Allow "using namespace std;" or "using namespace ::std;" even if
5746 // "std" hasn't been defined yet, for GCC compatibility.
5747 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5748 NamespcName->isStr("std")) {
5749 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005750 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005751 R.resolveKind();
5752 }
5753 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005754 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005755 }
5756
John McCallf36e02d2009-10-09 21:13:30 +00005757 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005758 NamedDecl *Named = R.getFoundDecl();
5759 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5760 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005761 // C++ [namespace.udir]p1:
5762 // A using-directive specifies that the names in the nominated
5763 // namespace can be used in the scope in which the
5764 // using-directive appears after the using-directive. During
5765 // unqualified name lookup (3.4.1), the names appear as if they
5766 // were declared in the nearest enclosing namespace which
5767 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005768 // namespace. [Note: in this context, "contains" means "contains
5769 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005770
5771 // Find enclosing context containing both using-directive and
5772 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005773 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005774 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5775 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5776 CommonAncestor = CommonAncestor->getParent();
5777
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005778 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005779 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005780 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005781
Douglas Gregor9172aa62011-03-26 22:25:30 +00005782 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005783 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005784 Diag(IdentLoc, diag::warn_using_directive_in_header);
5785 }
5786
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005787 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005788 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005789 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005790 }
5791
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005792 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005793 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005794}
5795
5796void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005797 // If the scope has an associated entity and the using directive is at
5798 // namespace or translation unit scope, add the UsingDirectiveDecl into
5799 // its lookup structure so qualified name lookup can find it.
5800 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5801 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005802 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005803 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005804 // Otherwise, it is at block sope. The using-directives will affect lookup
5805 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00005806 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005807}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005808
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005809
John McCalld226f652010-08-21 09:40:31 +00005810Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005811 AccessSpecifier AS,
5812 bool HasUsingKeyword,
5813 SourceLocation UsingLoc,
5814 CXXScopeSpec &SS,
5815 UnqualifiedId &Name,
5816 AttributeList *AttrList,
5817 bool IsTypeName,
5818 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005819 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005820
Douglas Gregor12c118a2009-11-04 16:30:06 +00005821 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005822 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005823 case UnqualifiedId::IK_Identifier:
5824 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005825 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005826 case UnqualifiedId::IK_ConversionFunctionId:
5827 break;
5828
5829 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005830 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00005831 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00005832 Diag(Name.getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005833 getLangOpts().CPlusPlus0x ?
Richard Smitha1366cb2012-04-27 19:33:05 +00005834 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
5835 // instead once inheriting constructors work.
5836 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00005837 diag::err_using_decl_constructor)
5838 << SS.getRange();
5839
David Blaikie4e4d0842012-03-11 07:00:24 +00005840 if (getLangOpts().CPlusPlus0x) break;
John McCall604e7f12009-12-08 07:46:18 +00005841
John McCalld226f652010-08-21 09:40:31 +00005842 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005843
5844 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005845 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005846 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005847 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005848
5849 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005850 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005851 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005852 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005853 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005854
5855 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5856 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005857 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005858 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005859
John McCall60fa3cf2009-12-11 02:10:03 +00005860 // Warn about using declarations.
5861 // TODO: store that the declaration was written without 'using' and
5862 // talk about access decls instead of using decls in the
5863 // diagnostics.
5864 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005865 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00005866
5867 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005868 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005869 }
5870
Douglas Gregor56c04582010-12-16 00:46:58 +00005871 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5872 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5873 return 0;
5874
John McCall9488ea12009-11-17 05:59:44 +00005875 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005876 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005877 /* IsInstantiation */ false,
5878 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005879 if (UD)
5880 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005881
John McCalld226f652010-08-21 09:40:31 +00005882 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005883}
5884
Douglas Gregor09acc982010-07-07 23:08:52 +00005885/// \brief Determine whether a using declaration considers the given
5886/// declarations as "equivalent", e.g., if they are redeclarations of
5887/// the same entity or are both typedefs of the same type.
5888static bool
5889IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5890 bool &SuppressRedeclaration) {
5891 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5892 SuppressRedeclaration = false;
5893 return true;
5894 }
5895
Richard Smith162e1c12011-04-15 14:24:37 +00005896 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5897 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005898 SuppressRedeclaration = true;
5899 return Context.hasSameType(TD1->getUnderlyingType(),
5900 TD2->getUnderlyingType());
5901 }
5902
5903 return false;
5904}
5905
5906
John McCall9f54ad42009-12-10 09:41:52 +00005907/// Determines whether to create a using shadow decl for a particular
5908/// decl, given the set of decls existing prior to this using lookup.
5909bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5910 const LookupResult &Previous) {
5911 // Diagnose finding a decl which is not from a base class of the
5912 // current class. We do this now because there are cases where this
5913 // function will silently decide not to build a shadow decl, which
5914 // will pre-empt further diagnostics.
5915 //
5916 // We don't need to do this in C++0x because we do the check once on
5917 // the qualifier.
5918 //
5919 // FIXME: diagnose the following if we care enough:
5920 // struct A { int foo; };
5921 // struct B : A { using A::foo; };
5922 // template <class T> struct C : A {};
5923 // template <class T> struct D : C<T> { using B::foo; } // <---
5924 // This is invalid (during instantiation) in C++03 because B::foo
5925 // resolves to the using decl in B, which is not a base class of D<T>.
5926 // We can't diagnose it immediately because C<T> is an unknown
5927 // specialization. The UsingShadowDecl in D<T> then points directly
5928 // to A::foo, which will look well-formed when we instantiate.
5929 // The right solution is to not collapse the shadow-decl chain.
David Blaikie4e4d0842012-03-11 07:00:24 +00005930 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00005931 DeclContext *OrigDC = Orig->getDeclContext();
5932
5933 // Handle enums and anonymous structs.
5934 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5935 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5936 while (OrigRec->isAnonymousStructOrUnion())
5937 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5938
5939 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5940 if (OrigDC == CurContext) {
5941 Diag(Using->getLocation(),
5942 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005943 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005944 Diag(Orig->getLocation(), diag::note_using_decl_target);
5945 return true;
5946 }
5947
Douglas Gregordc355712011-02-25 00:36:19 +00005948 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005949 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005950 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005951 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005952 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005953 Diag(Orig->getLocation(), diag::note_using_decl_target);
5954 return true;
5955 }
5956 }
5957
5958 if (Previous.empty()) return false;
5959
5960 NamedDecl *Target = Orig;
5961 if (isa<UsingShadowDecl>(Target))
5962 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5963
John McCalld7533ec2009-12-11 02:33:26 +00005964 // If the target happens to be one of the previous declarations, we
5965 // don't have a conflict.
5966 //
5967 // FIXME: but we might be increasing its access, in which case we
5968 // should redeclare it.
5969 NamedDecl *NonTag = 0, *Tag = 0;
5970 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5971 I != E; ++I) {
5972 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005973 bool Result;
5974 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5975 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005976
5977 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5978 }
5979
John McCall9f54ad42009-12-10 09:41:52 +00005980 if (Target->isFunctionOrFunctionTemplate()) {
5981 FunctionDecl *FD;
5982 if (isa<FunctionTemplateDecl>(Target))
5983 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5984 else
5985 FD = cast<FunctionDecl>(Target);
5986
5987 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005988 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005989 case Ovl_Overload:
5990 return false;
5991
5992 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005993 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005994 break;
5995
5996 // We found a decl with the exact signature.
5997 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005998 // If we're in a record, we want to hide the target, so we
5999 // return true (without a diagnostic) to tell the caller not to
6000 // build a shadow decl.
6001 if (CurContext->isRecord())
6002 return true;
6003
6004 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006005 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006006 break;
6007 }
6008
6009 Diag(Target->getLocation(), diag::note_using_decl_target);
6010 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6011 return true;
6012 }
6013
6014 // Target is not a function.
6015
John McCall9f54ad42009-12-10 09:41:52 +00006016 if (isa<TagDecl>(Target)) {
6017 // No conflict between a tag and a non-tag.
6018 if (!Tag) return false;
6019
John McCall41ce66f2009-12-10 19:51:03 +00006020 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006021 Diag(Target->getLocation(), diag::note_using_decl_target);
6022 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6023 return true;
6024 }
6025
6026 // No conflict between a tag and a non-tag.
6027 if (!NonTag) return false;
6028
John McCall41ce66f2009-12-10 19:51:03 +00006029 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006030 Diag(Target->getLocation(), diag::note_using_decl_target);
6031 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6032 return true;
6033}
6034
John McCall9488ea12009-11-17 05:59:44 +00006035/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006036UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006037 UsingDecl *UD,
6038 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006039
6040 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006041 NamedDecl *Target = Orig;
6042 if (isa<UsingShadowDecl>(Target)) {
6043 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6044 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006045 }
6046
6047 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006048 = UsingShadowDecl::Create(Context, CurContext,
6049 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006050 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006051
6052 Shadow->setAccess(UD->getAccess());
6053 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6054 Shadow->setInvalidDecl();
6055
John McCall9488ea12009-11-17 05:59:44 +00006056 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006057 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006058 else
John McCall604e7f12009-12-08 07:46:18 +00006059 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006060
John McCall604e7f12009-12-08 07:46:18 +00006061
John McCall9f54ad42009-12-10 09:41:52 +00006062 return Shadow;
6063}
John McCall604e7f12009-12-08 07:46:18 +00006064
John McCall9f54ad42009-12-10 09:41:52 +00006065/// Hides a using shadow declaration. This is required by the current
6066/// using-decl implementation when a resolvable using declaration in a
6067/// class is followed by a declaration which would hide or override
6068/// one or more of the using decl's targets; for example:
6069///
6070/// struct Base { void foo(int); };
6071/// struct Derived : Base {
6072/// using Base::foo;
6073/// void foo(int);
6074/// };
6075///
6076/// The governing language is C++03 [namespace.udecl]p12:
6077///
6078/// When a using-declaration brings names from a base class into a
6079/// derived class scope, member functions in the derived class
6080/// override and/or hide member functions with the same name and
6081/// parameter types in a base class (rather than conflicting).
6082///
6083/// There are two ways to implement this:
6084/// (1) optimistically create shadow decls when they're not hidden
6085/// by existing declarations, or
6086/// (2) don't create any shadow decls (or at least don't make them
6087/// visible) until we've fully parsed/instantiated the class.
6088/// The problem with (1) is that we might have to retroactively remove
6089/// a shadow decl, which requires several O(n) operations because the
6090/// decl structures are (very reasonably) not designed for removal.
6091/// (2) avoids this but is very fiddly and phase-dependent.
6092void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006093 if (Shadow->getDeclName().getNameKind() ==
6094 DeclarationName::CXXConversionFunctionName)
6095 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6096
John McCall9f54ad42009-12-10 09:41:52 +00006097 // Remove it from the DeclContext...
6098 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006099
John McCall9f54ad42009-12-10 09:41:52 +00006100 // ...and the scope, if applicable...
6101 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006102 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006103 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006104 }
6105
John McCall9f54ad42009-12-10 09:41:52 +00006106 // ...and the using decl.
6107 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6108
6109 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006110 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006111}
6112
John McCall7ba107a2009-11-18 02:36:19 +00006113/// Builds a using declaration.
6114///
6115/// \param IsInstantiation - Whether this call arises from an
6116/// instantiation of an unresolved using declaration. We treat
6117/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006118NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6119 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006120 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006121 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006122 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006123 bool IsInstantiation,
6124 bool IsTypeName,
6125 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006126 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006127 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006128 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006129
Anders Carlsson550b14b2009-08-28 05:49:21 +00006130 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006131
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006132 if (SS.isEmpty()) {
6133 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006134 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006135 }
Mike Stump1eb44332009-09-09 15:08:12 +00006136
John McCall9f54ad42009-12-10 09:41:52 +00006137 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006138 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006139 ForRedeclaration);
6140 Previous.setHideTags(false);
6141 if (S) {
6142 LookupName(Previous, S);
6143
6144 // It is really dumb that we have to do this.
6145 LookupResult::Filter F = Previous.makeFilter();
6146 while (F.hasNext()) {
6147 NamedDecl *D = F.next();
6148 if (!isDeclInScope(D, CurContext, S))
6149 F.erase();
6150 }
6151 F.done();
6152 } else {
6153 assert(IsInstantiation && "no scope in non-instantiation");
6154 assert(CurContext->isRecord() && "scope not record in instantiation");
6155 LookupQualifiedName(Previous, CurContext);
6156 }
6157
John McCall9f54ad42009-12-10 09:41:52 +00006158 // Check for invalid redeclarations.
6159 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6160 return 0;
6161
6162 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006163 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6164 return 0;
6165
John McCallaf8e6ed2009-11-12 03:15:40 +00006166 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006167 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006168 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006169 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006170 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006171 // FIXME: not all declaration name kinds are legal here
6172 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6173 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006174 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006175 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006176 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006177 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6178 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006179 }
John McCalled976492009-12-04 22:46:56 +00006180 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006181 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6182 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006183 }
John McCalled976492009-12-04 22:46:56 +00006184 D->setAccess(AS);
6185 CurContext->addDecl(D);
6186
6187 if (!LookupContext) return D;
6188 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006189
John McCall77bb1aa2010-05-01 00:40:08 +00006190 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006191 UD->setInvalidDecl();
6192 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006193 }
6194
Richard Smithc5a89a12012-04-02 01:30:27 +00006195 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006196 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006197 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006198 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006199 return UD;
6200 }
6201
6202 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006203
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006204 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006205
John McCall604e7f12009-12-08 07:46:18 +00006206 // Unlike most lookups, we don't always want to hide tag
6207 // declarations: tag names are visible through the using declaration
6208 // even if hidden by ordinary names, *except* in a dependent context
6209 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006210 if (!IsInstantiation)
6211 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006212
John McCallb9abd8722012-04-07 03:04:20 +00006213 // For the purposes of this lookup, we have a base object type
6214 // equal to that of the current context.
6215 if (CurContext->isRecord()) {
6216 R.setBaseObjectType(
6217 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6218 }
6219
John McCalla24dc2e2009-11-17 02:14:36 +00006220 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006221
John McCallf36e02d2009-10-09 21:13:30 +00006222 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006223 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006224 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006225 UD->setInvalidDecl();
6226 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006227 }
6228
John McCalled976492009-12-04 22:46:56 +00006229 if (R.isAmbiguous()) {
6230 UD->setInvalidDecl();
6231 return UD;
6232 }
Mike Stump1eb44332009-09-09 15:08:12 +00006233
John McCall7ba107a2009-11-18 02:36:19 +00006234 if (IsTypeName) {
6235 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006236 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006237 Diag(IdentLoc, diag::err_using_typename_non_type);
6238 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6239 Diag((*I)->getUnderlyingDecl()->getLocation(),
6240 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006241 UD->setInvalidDecl();
6242 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006243 }
6244 } else {
6245 // If we asked for a non-typename and we got a type, error out,
6246 // but only if this is an instantiation of an unresolved using
6247 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006248 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006249 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6250 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006251 UD->setInvalidDecl();
6252 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006253 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006254 }
6255
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006256 // C++0x N2914 [namespace.udecl]p6:
6257 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006258 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006259 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6260 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006261 UD->setInvalidDecl();
6262 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006263 }
Mike Stump1eb44332009-09-09 15:08:12 +00006264
John McCall9f54ad42009-12-10 09:41:52 +00006265 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6266 if (!CheckUsingShadowDecl(UD, *I, Previous))
6267 BuildUsingShadowDecl(S, UD, *I);
6268 }
John McCall9488ea12009-11-17 05:59:44 +00006269
6270 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006271}
6272
Sebastian Redlf677ea32011-02-05 19:23:19 +00006273/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006274bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6275 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006276
Douglas Gregordc355712011-02-25 00:36:19 +00006277 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006278 assert(SourceType &&
6279 "Using decl naming constructor doesn't have type in scope spec.");
6280 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6281
6282 // Check whether the named type is a direct base class.
6283 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6284 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6285 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6286 BaseIt != BaseE; ++BaseIt) {
6287 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6288 if (CanonicalSourceType == BaseType)
6289 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006290 if (BaseIt->getType()->isDependentType())
6291 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006292 }
6293
6294 if (BaseIt == BaseE) {
6295 // Did not find SourceType in the bases.
6296 Diag(UD->getUsingLocation(),
6297 diag::err_using_decl_constructor_not_in_direct_base)
6298 << UD->getNameInfo().getSourceRange()
6299 << QualType(SourceType, 0) << TargetClass;
6300 return true;
6301 }
6302
Richard Smithc5a89a12012-04-02 01:30:27 +00006303 if (!CurContext->isDependentContext())
6304 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006305
6306 return false;
6307}
6308
John McCall9f54ad42009-12-10 09:41:52 +00006309/// Checks that the given using declaration is not an invalid
6310/// redeclaration. Note that this is checking only for the using decl
6311/// itself, not for any ill-formedness among the UsingShadowDecls.
6312bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6313 bool isTypeName,
6314 const CXXScopeSpec &SS,
6315 SourceLocation NameLoc,
6316 const LookupResult &Prev) {
6317 // C++03 [namespace.udecl]p8:
6318 // C++0x [namespace.udecl]p10:
6319 // A using-declaration is a declaration and can therefore be used
6320 // repeatedly where (and only where) multiple declarations are
6321 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006322 //
John McCall8a726212010-11-29 18:01:58 +00006323 // That's in non-member contexts.
6324 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006325 return false;
6326
6327 NestedNameSpecifier *Qual
6328 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6329
6330 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6331 NamedDecl *D = *I;
6332
6333 bool DTypename;
6334 NestedNameSpecifier *DQual;
6335 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6336 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006337 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006338 } else if (UnresolvedUsingValueDecl *UD
6339 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6340 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006341 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006342 } else if (UnresolvedUsingTypenameDecl *UD
6343 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6344 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006345 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006346 } else continue;
6347
6348 // using decls differ if one says 'typename' and the other doesn't.
6349 // FIXME: non-dependent using decls?
6350 if (isTypeName != DTypename) continue;
6351
6352 // using decls differ if they name different scopes (but note that
6353 // template instantiation can cause this check to trigger when it
6354 // didn't before instantiation).
6355 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6356 Context.getCanonicalNestedNameSpecifier(DQual))
6357 continue;
6358
6359 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006360 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006361 return true;
6362 }
6363
6364 return false;
6365}
6366
John McCall604e7f12009-12-08 07:46:18 +00006367
John McCalled976492009-12-04 22:46:56 +00006368/// Checks that the given nested-name qualifier used in a using decl
6369/// in the current context is appropriately related to the current
6370/// scope. If an error is found, diagnoses it and returns true.
6371bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6372 const CXXScopeSpec &SS,
6373 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006374 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006375
John McCall604e7f12009-12-08 07:46:18 +00006376 if (!CurContext->isRecord()) {
6377 // C++03 [namespace.udecl]p3:
6378 // C++0x [namespace.udecl]p8:
6379 // A using-declaration for a class member shall be a member-declaration.
6380
6381 // If we weren't able to compute a valid scope, it must be a
6382 // dependent class scope.
6383 if (!NamedContext || NamedContext->isRecord()) {
6384 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6385 << SS.getRange();
6386 return true;
6387 }
6388
6389 // Otherwise, everything is known to be fine.
6390 return false;
6391 }
6392
6393 // The current scope is a record.
6394
6395 // If the named context is dependent, we can't decide much.
6396 if (!NamedContext) {
6397 // FIXME: in C++0x, we can diagnose if we can prove that the
6398 // nested-name-specifier does not refer to a base class, which is
6399 // still possible in some cases.
6400
6401 // Otherwise we have to conservatively report that things might be
6402 // okay.
6403 return false;
6404 }
6405
6406 if (!NamedContext->isRecord()) {
6407 // Ideally this would point at the last name in the specifier,
6408 // but we don't have that level of source info.
6409 Diag(SS.getRange().getBegin(),
6410 diag::err_using_decl_nested_name_specifier_is_not_class)
6411 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6412 return true;
6413 }
6414
Douglas Gregor6fb07292010-12-21 07:41:49 +00006415 if (!NamedContext->isDependentContext() &&
6416 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6417 return true;
6418
David Blaikie4e4d0842012-03-11 07:00:24 +00006419 if (getLangOpts().CPlusPlus0x) {
John McCall604e7f12009-12-08 07:46:18 +00006420 // C++0x [namespace.udecl]p3:
6421 // In a using-declaration used as a member-declaration, the
6422 // nested-name-specifier shall name a base class of the class
6423 // being defined.
6424
6425 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6426 cast<CXXRecordDecl>(NamedContext))) {
6427 if (CurContext == NamedContext) {
6428 Diag(NameLoc,
6429 diag::err_using_decl_nested_name_specifier_is_current_class)
6430 << SS.getRange();
6431 return true;
6432 }
6433
6434 Diag(SS.getRange().getBegin(),
6435 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6436 << (NestedNameSpecifier*) SS.getScopeRep()
6437 << cast<CXXRecordDecl>(CurContext)
6438 << SS.getRange();
6439 return true;
6440 }
6441
6442 return false;
6443 }
6444
6445 // C++03 [namespace.udecl]p4:
6446 // A using-declaration used as a member-declaration shall refer
6447 // to a member of a base class of the class being defined [etc.].
6448
6449 // Salient point: SS doesn't have to name a base class as long as
6450 // lookup only finds members from base classes. Therefore we can
6451 // diagnose here only if we can prove that that can't happen,
6452 // i.e. if the class hierarchies provably don't intersect.
6453
6454 // TODO: it would be nice if "definitely valid" results were cached
6455 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6456 // need to be repeated.
6457
6458 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00006459 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00006460
6461 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6462 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6463 Data->Bases.insert(Base);
6464 return true;
6465 }
6466
6467 bool hasDependentBases(const CXXRecordDecl *Class) {
6468 return !Class->forallBases(collect, this);
6469 }
6470
6471 /// Returns true if the base is dependent or is one of the
6472 /// accumulated base classes.
6473 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6474 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6475 return !Data->Bases.count(Base);
6476 }
6477
6478 bool mightShareBases(const CXXRecordDecl *Class) {
6479 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6480 }
6481 };
6482
6483 UserData Data;
6484
6485 // Returns false if we find a dependent base.
6486 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6487 return false;
6488
6489 // Returns false if the class has a dependent base or if it or one
6490 // of its bases is present in the base set of the current context.
6491 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6492 return false;
6493
6494 Diag(SS.getRange().getBegin(),
6495 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6496 << (NestedNameSpecifier*) SS.getScopeRep()
6497 << cast<CXXRecordDecl>(CurContext)
6498 << SS.getRange();
6499
6500 return true;
John McCalled976492009-12-04 22:46:56 +00006501}
6502
Richard Smith162e1c12011-04-15 14:24:37 +00006503Decl *Sema::ActOnAliasDeclaration(Scope *S,
6504 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006505 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006506 SourceLocation UsingLoc,
6507 UnqualifiedId &Name,
6508 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006509 // Skip up to the relevant declaration scope.
6510 while (S->getFlags() & Scope::TemplateParamScope)
6511 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006512 assert((S->getFlags() & Scope::DeclScope) &&
6513 "got alias-declaration outside of declaration scope");
6514
6515 if (Type.isInvalid())
6516 return 0;
6517
6518 bool Invalid = false;
6519 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6520 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006521 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006522
6523 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6524 return 0;
6525
6526 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006527 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006528 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006529 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6530 TInfo->getTypeLoc().getBeginLoc());
6531 }
Richard Smith162e1c12011-04-15 14:24:37 +00006532
6533 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6534 LookupName(Previous, S);
6535
6536 // Warn about shadowing the name of a template parameter.
6537 if (Previous.isSingleResult() &&
6538 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006539 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006540 Previous.clear();
6541 }
6542
6543 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6544 "name in alias declaration must be an identifier");
6545 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6546 Name.StartLocation,
6547 Name.Identifier, TInfo);
6548
6549 NewTD->setAccess(AS);
6550
6551 if (Invalid)
6552 NewTD->setInvalidDecl();
6553
Richard Smith3e4c6c42011-05-05 21:57:07 +00006554 CheckTypedefForVariablyModifiedType(S, NewTD);
6555 Invalid |= NewTD->isInvalidDecl();
6556
Richard Smith162e1c12011-04-15 14:24:37 +00006557 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006558
6559 NamedDecl *NewND;
6560 if (TemplateParamLists.size()) {
6561 TypeAliasTemplateDecl *OldDecl = 0;
6562 TemplateParameterList *OldTemplateParams = 0;
6563
6564 if (TemplateParamLists.size() != 1) {
6565 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006566 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
6567 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00006568 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006569 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00006570
6571 // Only consider previous declarations in the same scope.
6572 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6573 /*ExplicitInstantiationOrSpecialization*/false);
6574 if (!Previous.empty()) {
6575 Redeclaration = true;
6576
6577 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6578 if (!OldDecl && !Invalid) {
6579 Diag(UsingLoc, diag::err_redefinition_different_kind)
6580 << Name.Identifier;
6581
6582 NamedDecl *OldD = Previous.getRepresentativeDecl();
6583 if (OldD->getLocation().isValid())
6584 Diag(OldD->getLocation(), diag::note_previous_definition);
6585
6586 Invalid = true;
6587 }
6588
6589 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6590 if (TemplateParameterListsAreEqual(TemplateParams,
6591 OldDecl->getTemplateParameters(),
6592 /*Complain=*/true,
6593 TPL_TemplateMatch))
6594 OldTemplateParams = OldDecl->getTemplateParameters();
6595 else
6596 Invalid = true;
6597
6598 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6599 if (!Invalid &&
6600 !Context.hasSameType(OldTD->getUnderlyingType(),
6601 NewTD->getUnderlyingType())) {
6602 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6603 // but we can't reasonably accept it.
6604 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6605 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6606 if (OldTD->getLocation().isValid())
6607 Diag(OldTD->getLocation(), diag::note_previous_definition);
6608 Invalid = true;
6609 }
6610 }
6611 }
6612
6613 // Merge any previous default template arguments into our parameters,
6614 // and check the parameter list.
6615 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6616 TPC_TypeAliasTemplate))
6617 return 0;
6618
6619 TypeAliasTemplateDecl *NewDecl =
6620 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6621 Name.Identifier, TemplateParams,
6622 NewTD);
6623
6624 NewDecl->setAccess(AS);
6625
6626 if (Invalid)
6627 NewDecl->setInvalidDecl();
6628 else if (OldDecl)
6629 NewDecl->setPreviousDeclaration(OldDecl);
6630
6631 NewND = NewDecl;
6632 } else {
6633 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6634 NewND = NewTD;
6635 }
Richard Smith162e1c12011-04-15 14:24:37 +00006636
6637 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006638 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006639
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00006640 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00006641 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006642}
6643
John McCalld226f652010-08-21 09:40:31 +00006644Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006645 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006646 SourceLocation AliasLoc,
6647 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006648 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006649 SourceLocation IdentLoc,
6650 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006651
Anders Carlsson81c85c42009-03-28 23:53:49 +00006652 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006653 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6654 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006655
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006656 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006657 NamedDecl *PrevDecl
6658 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6659 ForRedeclaration);
6660 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6661 PrevDecl = 0;
6662
6663 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006664 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006665 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006666 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006667 // FIXME: At some point, we'll want to create the (redundant)
6668 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006669 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006670 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006671 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006672 }
Mike Stump1eb44332009-09-09 15:08:12 +00006673
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006674 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6675 diag::err_redefinition_different_kind;
6676 Diag(AliasLoc, DiagID) << Alias;
6677 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006678 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006679 }
6680
John McCalla24dc2e2009-11-17 02:14:36 +00006681 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006682 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006683
John McCallf36e02d2009-10-09 21:13:30 +00006684 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006685 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00006686 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006687 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006688 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006689 }
Mike Stump1eb44332009-09-09 15:08:12 +00006690
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006691 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006692 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006693 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006694 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006695
John McCall3dbd3d52010-02-16 06:53:13 +00006696 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006697 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006698}
6699
Douglas Gregor39957dc2010-05-01 15:04:51 +00006700namespace {
6701 /// \brief Scoped object used to handle the state changes required in Sema
6702 /// to implicitly define the body of a C++ member function;
6703 class ImplicitlyDefinedFunctionScope {
6704 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006705 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006706
6707 public:
6708 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006709 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006710 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006711 S.PushFunctionScope();
6712 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6713 }
6714
6715 ~ImplicitlyDefinedFunctionScope() {
6716 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006717 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006718 }
6719 };
6720}
6721
Sean Hunt001cad92011-05-10 00:49:42 +00006722Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00006723Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
6724 CXXMethodDecl *MD) {
6725 CXXRecordDecl *ClassDecl = MD->getParent();
6726
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006727 // C++ [except.spec]p14:
6728 // An implicitly declared special member function (Clause 12) shall have an
6729 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00006730 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006731 if (ClassDecl->isInvalidDecl())
6732 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006733
Sebastian Redl60618fa2011-03-12 11:50:43 +00006734 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006735 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6736 BEnd = ClassDecl->bases_end();
6737 B != BEnd; ++B) {
6738 if (B->isVirtual()) // Handled below.
6739 continue;
6740
Douglas Gregor18274032010-07-03 00:47:00 +00006741 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6742 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006743 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6744 // If this is a deleted function, add it anyway. This might be conformant
6745 // with the standard. This might not. I'm not sure. It might not matter.
6746 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006747 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006748 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006749 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006750
6751 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006752 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6753 BEnd = ClassDecl->vbases_end();
6754 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006755 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6756 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006757 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6758 // If this is a deleted function, add it anyway. This might be conformant
6759 // with the standard. This might not. I'm not sure. It might not matter.
6760 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006761 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006762 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006763 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006764
6765 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006766 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6767 FEnd = ClassDecl->field_end();
6768 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006769 if (F->hasInClassInitializer()) {
6770 if (Expr *E = F->getInClassInitializer())
6771 ExceptSpec.CalledExpr(E);
6772 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00006773 // DR1351:
6774 // If the brace-or-equal-initializer of a non-static data member
6775 // invokes a defaulted default constructor of its class or of an
6776 // enclosing class in a potentially evaluated subexpression, the
6777 // program is ill-formed.
6778 //
6779 // This resolution is unworkable: the exception specification of the
6780 // default constructor can be needed in an unevaluated context, in
6781 // particular, in the operand of a noexcept-expression, and we can be
6782 // unable to compute an exception specification for an enclosed class.
6783 //
6784 // We do not allow an in-class initializer to require the evaluation
6785 // of the exception specification for any in-class initializer whose
6786 // definition is not lexically complete.
6787 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00006788 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006789 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006790 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6791 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6792 // If this is a deleted function, add it anyway. This might be conformant
6793 // with the standard. This might not. I'm not sure. It might not matter.
6794 // In particular, the problem is that this function never gets called. It
6795 // might just be ill-formed because this function attempts to refer to
6796 // a deleted function here.
6797 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006798 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006799 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006800 }
John McCalle23cf432010-12-14 08:05:40 +00006801
Sean Hunt001cad92011-05-10 00:49:42 +00006802 return ExceptSpec;
6803}
6804
6805CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6806 CXXRecordDecl *ClassDecl) {
6807 // C++ [class.ctor]p5:
6808 // A default constructor for a class X is a constructor of class X
6809 // that can be called without an argument. If there is no
6810 // user-declared constructor for class X, a default constructor is
6811 // implicitly declared. An implicitly-declared default constructor
6812 // is an inline public member of its class.
6813 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6814 "Should not build implicit default constructor!");
6815
Richard Smith7756afa2012-06-10 05:43:50 +00006816 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
6817 CXXDefaultConstructor,
6818 false);
6819
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006820 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006821 CanQualType ClassType
6822 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006823 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006824 DeclarationName Name
6825 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006826 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00006827 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00006828 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00006829 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00006830 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006831 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006832 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006833 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006834 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Richard Smithb9d0b762012-07-27 04:22:15 +00006835
6836 // Build an exception specification pointing back at this constructor.
6837 FunctionProtoType::ExtProtoInfo EPI;
6838 EPI.ExceptionSpecType = EST_Unevaluated;
6839 EPI.ExceptionSpecDecl = DefaultCon;
6840 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6841
Douglas Gregor18274032010-07-03 00:47:00 +00006842 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006843 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6844
Douglas Gregor23c94db2010-07-02 17:43:08 +00006845 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006846 PushOnScopeChains(DefaultCon, S, false);
6847 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006848
Sean Hunte16da072011-10-10 06:18:57 +00006849 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00006850 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006851
Douglas Gregor32df23e2010-07-01 22:02:46 +00006852 return DefaultCon;
6853}
6854
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006855void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6856 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006857 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006858 !Constructor->doesThisDeclarationHaveABody() &&
6859 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006860 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006861
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006862 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006863 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006864
Douglas Gregor39957dc2010-05-01 15:04:51 +00006865 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006866 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006867 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006868 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006869 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006870 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006871 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006872 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006873 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006874
6875 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00006876 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006877
6878 Constructor->setUsed();
6879 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006880
6881 if (ASTMutationListener *L = getASTMutationListener()) {
6882 L->CompletedImplicitDefinition(Constructor);
6883 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006884}
6885
Richard Smith7a614d82011-06-11 17:19:42 +00006886void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6887 if (!D) return;
6888 AdjustDeclIfTemplate(D);
6889
6890 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
Richard Smith7a614d82011-06-11 17:19:42 +00006891
Richard Smithb9d0b762012-07-27 04:22:15 +00006892 if (!ClassDecl->isDependentType())
6893 CheckExplicitlyDefaultedMethods(ClassDecl);
Richard Smith7a614d82011-06-11 17:19:42 +00006894}
6895
Sebastian Redlf677ea32011-02-05 19:23:19 +00006896void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6897 // We start with an initial pass over the base classes to collect those that
6898 // inherit constructors from. If there are none, we can forgo all further
6899 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006900 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006901 BasesVector BasesToInheritFrom;
6902 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6903 BaseE = ClassDecl->bases_end();
6904 BaseIt != BaseE; ++BaseIt) {
6905 if (BaseIt->getInheritConstructors()) {
6906 QualType Base = BaseIt->getType();
6907 if (Base->isDependentType()) {
6908 // If we inherit constructors from anything that is dependent, just
6909 // abort processing altogether. We'll get another chance for the
6910 // instantiations.
6911 return;
6912 }
6913 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6914 }
6915 }
6916 if (BasesToInheritFrom.empty())
6917 return;
6918
6919 // Now collect the constructors that we already have in the current class.
6920 // Those take precedence over inherited constructors.
6921 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6922 // unless there is a user-declared constructor with the same signature in
6923 // the class where the using-declaration appears.
6924 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6925 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6926 CtorE = ClassDecl->ctor_end();
6927 CtorIt != CtorE; ++CtorIt) {
6928 ExistingConstructors.insert(
6929 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6930 }
6931
Sebastian Redlf677ea32011-02-05 19:23:19 +00006932 DeclarationName CreatedCtorName =
6933 Context.DeclarationNames.getCXXConstructorName(
6934 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6935
6936 // Now comes the true work.
6937 // First, we keep a map from constructor types to the base that introduced
6938 // them. Needed for finding conflicting constructors. We also keep the
6939 // actually inserted declarations in there, for pretty diagnostics.
6940 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6941 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6942 ConstructorToSourceMap InheritedConstructors;
6943 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6944 BaseE = BasesToInheritFrom.end();
6945 BaseIt != BaseE; ++BaseIt) {
6946 const RecordType *Base = *BaseIt;
6947 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6948 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6949 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6950 CtorE = BaseDecl->ctor_end();
6951 CtorIt != CtorE; ++CtorIt) {
6952 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00006953 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00006954 DeclarationName Name =
6955 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00006956 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
6957 LookupQualifiedName(Result, CurContext);
6958 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006959 SourceLocation UsingLoc = UD ? UD->getLocation() :
6960 ClassDecl->getLocation();
6961
6962 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6963 // from the class X named in the using-declaration consists of actual
6964 // constructors and notional constructors that result from the
6965 // transformation of defaulted parameters as follows:
6966 // - all non-template default constructors of X, and
6967 // - for each non-template constructor of X that has at least one
6968 // parameter with a default argument, the set of constructors that
6969 // results from omitting any ellipsis parameter specification and
6970 // successively omitting parameters with a default argument from the
6971 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00006972 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006973 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6974 const FunctionProtoType *BaseCtorType =
6975 BaseCtor->getType()->getAs<FunctionProtoType>();
6976
6977 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6978 maxParams = BaseCtor->getNumParams();
6979 params <= maxParams; ++params) {
6980 // Skip default constructors. They're never inherited.
6981 if (params == 0)
6982 continue;
6983 // Skip copy and move constructors for the same reason.
6984 if (CanBeCopyOrMove && params == 1)
6985 continue;
6986
6987 // Build up a function type for this particular constructor.
6988 // FIXME: The working paper does not consider that the exception spec
6989 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00006990 // source. This code doesn't yet, either. When it does, this code will
6991 // need to be delayed until after exception specifications and in-class
6992 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006993 const Type *NewCtorType;
6994 if (params == maxParams)
6995 NewCtorType = BaseCtorType;
6996 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006997 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006998 for (unsigned i = 0; i < params; ++i) {
6999 Args.push_back(BaseCtorType->getArgType(i));
7000 }
7001 FunctionProtoType::ExtProtoInfo ExtInfo =
7002 BaseCtorType->getExtProtoInfo();
7003 ExtInfo.Variadic = false;
7004 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7005 Args.data(), params, ExtInfo)
7006 .getTypePtr();
7007 }
7008 const Type *CanonicalNewCtorType =
7009 Context.getCanonicalType(NewCtorType);
7010
7011 // Now that we have the type, first check if the class already has a
7012 // constructor with this signature.
7013 if (ExistingConstructors.count(CanonicalNewCtorType))
7014 continue;
7015
7016 // Then we check if we have already declared an inherited constructor
7017 // with this signature.
7018 std::pair<ConstructorToSourceMap::iterator, bool> result =
7019 InheritedConstructors.insert(std::make_pair(
7020 CanonicalNewCtorType,
7021 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7022 if (!result.second) {
7023 // Already in the map. If it came from a different class, that's an
7024 // error. Not if it's from the same.
7025 CanQualType PreviousBase = result.first->second.first;
7026 if (CanonicalBase != PreviousBase) {
7027 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7028 const CXXConstructorDecl *PrevBaseCtor =
7029 PrevCtor->getInheritedConstructor();
7030 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7031
7032 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7033 Diag(BaseCtor->getLocation(),
7034 diag::note_using_decl_constructor_conflict_current_ctor);
7035 Diag(PrevBaseCtor->getLocation(),
7036 diag::note_using_decl_constructor_conflict_previous_ctor);
7037 Diag(PrevCtor->getLocation(),
7038 diag::note_using_decl_constructor_conflict_previous_using);
7039 }
7040 continue;
7041 }
7042
7043 // OK, we're there, now add the constructor.
7044 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007045 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007046 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7047 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007048 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7049 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007050 /*ImplicitlyDeclared=*/true,
7051 // FIXME: Due to a defect in the standard, we treat inherited
7052 // constructors as constexpr even if that makes them ill-formed.
7053 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007054 NewCtor->setAccess(BaseCtor->getAccess());
7055
7056 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007057 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007058 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007059 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7060 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007061 /*IdentifierInfo=*/0,
7062 BaseCtorType->getArgType(i),
7063 /*TInfo=*/0, SC_None,
7064 SC_None, /*DefaultArg=*/0));
7065 }
David Blaikie4278c652011-09-21 18:16:56 +00007066 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007067 NewCtor->setInheritedConstructor(BaseCtor);
7068
Sebastian Redlf677ea32011-02-05 19:23:19 +00007069 ClassDecl->addDecl(NewCtor);
7070 result.first->second.second = NewCtor;
7071 }
7072 }
7073 }
7074}
7075
Sean Huntcb45a0f2011-05-12 22:46:25 +00007076Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007077Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7078 CXXRecordDecl *ClassDecl = MD->getParent();
7079
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007080 // C++ [except.spec]p14:
7081 // An implicitly declared special member function (Clause 12) shall have
7082 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007083 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007084 if (ClassDecl->isInvalidDecl())
7085 return ExceptSpec;
7086
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007087 // Direct base-class destructors.
7088 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7089 BEnd = ClassDecl->bases_end();
7090 B != BEnd; ++B) {
7091 if (B->isVirtual()) // Handled below.
7092 continue;
7093
7094 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007095 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007096 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007097 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007098
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007099 // Virtual base-class destructors.
7100 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7101 BEnd = ClassDecl->vbases_end();
7102 B != BEnd; ++B) {
7103 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007104 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007105 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007106 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007107
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007108 // Field destructors.
7109 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7110 FEnd = ClassDecl->field_end();
7111 F != FEnd; ++F) {
7112 if (const RecordType *RecordTy
7113 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007114 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007115 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007116 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007117
Sean Huntcb45a0f2011-05-12 22:46:25 +00007118 return ExceptSpec;
7119}
7120
7121CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7122 // C++ [class.dtor]p2:
7123 // If a class has no user-declared destructor, a destructor is
7124 // declared implicitly. An implicitly-declared destructor is an
7125 // inline public member of its class.
Sean Huntcb45a0f2011-05-12 22:46:25 +00007126
Douglas Gregor4923aa22010-07-02 20:37:36 +00007127 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007128 CanQualType ClassType
7129 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007130 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007131 DeclarationName Name
7132 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007133 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007134 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007135 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7136 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007137 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007138 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007139 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007140 Destructor->setImplicit();
7141 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Richard Smithb9d0b762012-07-27 04:22:15 +00007142
7143 // Build an exception specification pointing back at this destructor.
7144 FunctionProtoType::ExtProtoInfo EPI;
7145 EPI.ExceptionSpecType = EST_Unevaluated;
7146 EPI.ExceptionSpecDecl = Destructor;
7147 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7148
Douglas Gregor4923aa22010-07-02 20:37:36 +00007149 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007150 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007151
Douglas Gregor4923aa22010-07-02 20:37:36 +00007152 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007153 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007154 PushOnScopeChains(Destructor, S, false);
7155 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007156
Richard Smith9a561d52012-02-26 09:11:52 +00007157 AddOverriddenMethods(ClassDecl, Destructor);
7158
Richard Smith7d5088a2012-02-18 02:02:13 +00007159 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Sean Huntcb45a0f2011-05-12 22:46:25 +00007160 Destructor->setDeletedAsWritten();
Richard Smith9a561d52012-02-26 09:11:52 +00007161
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007162 return Destructor;
7163}
7164
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007165void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007166 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007167 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007168 !Destructor->doesThisDeclarationHaveABody() &&
7169 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007170 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007171 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007172 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007173
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007174 if (Destructor->isInvalidDecl())
7175 return;
7176
Douglas Gregor39957dc2010-05-01 15:04:51 +00007177 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007178
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007179 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007180 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7181 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007182
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007183 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007184 Diag(CurrentLocation, diag::note_member_synthesized_at)
7185 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7186
7187 Destructor->setInvalidDecl();
7188 return;
7189 }
7190
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007191 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007192 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007193 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007194 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007195 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007196
7197 if (ASTMutationListener *L = getASTMutationListener()) {
7198 L->CompletedImplicitDefinition(Destructor);
7199 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007200}
7201
Richard Smitha4156b82012-04-21 18:42:51 +00007202/// \brief Perform any semantic analysis which needs to be delayed until all
7203/// pending class member declarations have been parsed.
7204void Sema::ActOnFinishCXXMemberDecls() {
Richard Smitha4156b82012-04-21 18:42:51 +00007205 // Perform any deferred checking of exception specifications for virtual
7206 // destructors.
7207 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7208 i != e; ++i) {
7209 const CXXDestructorDecl *Dtor =
7210 DelayedDestructorExceptionSpecChecks[i].first;
7211 assert(!Dtor->getParent()->isDependentType() &&
7212 "Should not ever add destructors of templates into the list.");
7213 CheckOverridingFunctionExceptionSpec(Dtor,
7214 DelayedDestructorExceptionSpecChecks[i].second);
7215 }
7216 DelayedDestructorExceptionSpecChecks.clear();
7217}
7218
Richard Smithb9d0b762012-07-27 04:22:15 +00007219void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7220 CXXDestructorDecl *Destructor) {
7221 assert(getLangOpts().CPlusPlus0x &&
7222 "adjusting dtor exception specs was introduced in c++11");
7223
Sebastian Redl0ee33912011-05-19 05:13:44 +00007224 // C++11 [class.dtor]p3:
7225 // A declaration of a destructor that does not have an exception-
7226 // specification is implicitly considered to have the same exception-
7227 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007228 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007229 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007230 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007231 return;
7232
Chandler Carruth3f224b22011-09-20 04:55:26 +00007233 // Replace the destructor's type, building off the existing one. Fortunately,
7234 // the only thing of interest in the destructor type is its extended info.
7235 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007236 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7237 EPI.ExceptionSpecType = EST_Unevaluated;
7238 EPI.ExceptionSpecDecl = Destructor;
7239 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007240
Sebastian Redl0ee33912011-05-19 05:13:44 +00007241 // FIXME: If the destructor has a body that could throw, and the newly created
7242 // spec doesn't allow exceptions, we should emit a warning, because this
7243 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007244 // However, we don't have a body or an exception specification yet, so it
7245 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007246}
7247
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007248/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007249/// \c To.
7250///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007251/// This routine is used to copy/move the members of a class with an
7252/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007253/// copied are arrays, this routine builds for loops to copy them.
7254///
7255/// \param S The Sema object used for type-checking.
7256///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007257/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007258///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007259/// \param T The type of the expressions being copied/moved. Both expressions
7260/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007261///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007262/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007263///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007264/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007265///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007266/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007267/// Otherwise, it's a non-static member subobject.
7268///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007269/// \param Copying Whether we're copying or moving.
7270///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007271/// \param Depth Internal parameter recording the depth of the recursion.
7272///
7273/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007274static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007275BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007276 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007277 bool CopyingBaseSubobject, bool Copying,
7278 unsigned Depth = 0) {
7279 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007280 // Each subobject is assigned in the manner appropriate to its type:
7281 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007282 // - if the subobject is of class type, as if by a call to operator= with
7283 // the subobject as the object expression and the corresponding
7284 // subobject of x as a single function argument (as if by explicit
7285 // qualification; that is, ignoring any possible virtual overriding
7286 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007287 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7288 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7289
7290 // Look for operator=.
7291 DeclarationName Name
7292 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7293 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7294 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7295
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007296 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007297 LookupResult::Filter F = OpLookup.makeFilter();
7298 while (F.hasNext()) {
7299 NamedDecl *D = F.next();
7300 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Richard Smith1c931be2012-04-02 18:40:40 +00007301 if (Method->isCopyAssignmentOperator() ||
7302 (!Copying && Method->isMoveAssignmentOperator()))
Douglas Gregor06a9f362010-05-01 20:49:11 +00007303 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007304
Douglas Gregor06a9f362010-05-01 20:49:11 +00007305 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007306 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007307 F.done();
7308
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007309 // Suppress the protected check (C++ [class.protected]) for each of the
7310 // assignment operators we found. This strange dance is required when
7311 // we're assigning via a base classes's copy-assignment operator. To
7312 // ensure that we're getting the right base class subobject (without
7313 // ambiguities), we need to cast "this" to that subobject type; to
7314 // ensure that we don't go through the virtual call mechanism, we need
7315 // to qualify the operator= name with the base class (see below). However,
7316 // this means that if the base class has a protected copy assignment
7317 // operator, the protected member access check will fail. So, we
7318 // rewrite "protected" access to "public" access in this case, since we
7319 // know by construction that we're calling from a derived class.
7320 if (CopyingBaseSubobject) {
7321 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7322 L != LEnd; ++L) {
7323 if (L.getAccess() == AS_protected)
7324 L.setAccess(AS_public);
7325 }
7326 }
7327
Douglas Gregor06a9f362010-05-01 20:49:11 +00007328 // Create the nested-name-specifier that will be used to qualify the
7329 // reference to operator=; this is required to suppress the virtual
7330 // call mechanism.
7331 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007332 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007333 SS.MakeTrivial(S.Context,
7334 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007335 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007336 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007337
7338 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007339 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007340 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007341 /*TemplateKWLoc=*/SourceLocation(),
7342 /*FirstQualifierInScope=*/0,
7343 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007344 /*TemplateArgs=*/0,
7345 /*SuppressQualifierCheck=*/true);
7346 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007347 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007348
7349 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007350
John McCall60d7b3a2010-08-24 06:29:42 +00007351 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007352 OpEqualRef.takeAs<Expr>(),
7353 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007354 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007355 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007356
7357 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007358 }
John McCallb0207482010-03-16 06:11:48 +00007359
Douglas Gregor06a9f362010-05-01 20:49:11 +00007360 // - if the subobject is of scalar type, the built-in assignment
7361 // operator is used.
7362 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7363 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007364 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007365 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007366 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007367
7368 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007369 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007370
7371 // - if the subobject is an array, each element is assigned, in the
7372 // manner appropriate to the element type;
7373
7374 // Construct a loop over the array bounds, e.g.,
7375 //
7376 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7377 //
7378 // that will copy each of the array elements.
7379 QualType SizeType = S.Context.getSizeType();
7380
7381 // Create the iteration variable.
7382 IdentifierInfo *IterationVarName = 0;
7383 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007384 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007385 llvm::raw_svector_ostream OS(Str);
7386 OS << "__i" << Depth;
7387 IterationVarName = &S.Context.Idents.get(OS.str());
7388 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007389 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007390 IterationVarName, SizeType,
7391 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007392 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007393
7394 // Initialize the iteration variable to zero.
7395 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007396 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007397
7398 // Create a reference to the iteration variable; we'll use this several
7399 // times throughout.
7400 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007401 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007402 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007403 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7404 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7405
Douglas Gregor06a9f362010-05-01 20:49:11 +00007406 // Create the DeclStmt that holds the iteration variable.
7407 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7408
7409 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007410 llvm::APInt Upper
7411 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007412 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007413 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007414 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7415 BO_NE, S.Context.BoolTy,
7416 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007417
7418 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007419 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007420 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7421 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007422
7423 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007424 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007425 IterationVarRefRVal,
7426 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007427 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007428 IterationVarRefRVal,
7429 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007430 if (!Copying) // Cast to rvalue
7431 From = CastForMoving(S, From);
7432
7433 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007434 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7435 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007436 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007437 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007438 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007439
7440 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007441 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007442 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007443 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007444 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007445}
7446
Richard Smithb9d0b762012-07-27 04:22:15 +00007447/// Determine whether an implicit copy assignment operator for ClassDecl has a
7448/// const argument.
7449/// FIXME: It ought to be possible to store this on the record.
7450static bool isImplicitCopyAssignmentArgConst(Sema &S,
7451 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007452 if (ClassDecl->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007453 return true;
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007454
Douglas Gregord3c35902010-07-01 16:36:15 +00007455 // C++ [class.copy]p10:
7456 // If the class definition does not explicitly declare a copy
7457 // assignment operator, one is declared implicitly.
7458 // The implicitly-defined copy assignment operator for a class X
7459 // will have the form
7460 //
7461 // X& X::operator=(const X&)
7462 //
7463 // if
Douglas Gregord3c35902010-07-01 16:36:15 +00007464 // -- each direct base class B of X has a copy assignment operator
7465 // whose parameter is of type const B&, const volatile B& or B,
7466 // and
7467 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7468 BaseEnd = ClassDecl->bases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00007469 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007470 // We'll handle this below
Richard Smithb9d0b762012-07-27 04:22:15 +00007471 if (S.getLangOpts().CPlusPlus0x && Base->isVirtual())
Sean Hunt661c67a2011-06-21 23:42:56 +00007472 continue;
7473
Douglas Gregord3c35902010-07-01 16:36:15 +00007474 assert(!Base->getType()->isDependentType() &&
7475 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007476 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
Richard Smithb9d0b762012-07-27 04:22:15 +00007477 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0))
7478 return false;
Sean Hunt661c67a2011-06-21 23:42:56 +00007479 }
7480
Richard Smithebaf0e62011-10-18 20:49:44 +00007481 // In C++11, the above citation has "or virtual" added
Richard Smithb9d0b762012-07-27 04:22:15 +00007482 if (S.getLangOpts().CPlusPlus0x) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007483 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7484 BaseEnd = ClassDecl->vbases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00007485 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007486 assert(!Base->getType()->isDependentType() &&
7487 "Cannot generate implicit members for class with dependent bases.");
7488 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
Richard Smithb9d0b762012-07-27 04:22:15 +00007489 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7490 false, 0))
7491 return false;
Sean Hunt661c67a2011-06-21 23:42:56 +00007492 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007493 }
7494
7495 // -- for all the nonstatic data members of X that are of a class
7496 // type M (or array thereof), each such class type has a copy
7497 // assignment operator whose parameter is of type const M&,
7498 // const volatile M& or M.
7499 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7500 FieldEnd = ClassDecl->field_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00007501 Field != FieldEnd; ++Field) {
7502 QualType FieldType = S.Context.getBaseElementType(Field->getType());
7503 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl())
7504 if (!S.LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const,
7505 false, 0))
7506 return false;
Douglas Gregord3c35902010-07-01 16:36:15 +00007507 }
7508
7509 // Otherwise, the implicitly declared copy assignment operator will
7510 // have the form
7511 //
7512 // X& X::operator=(X&)
Richard Smithb9d0b762012-07-27 04:22:15 +00007513
7514 return true;
7515}
7516
7517Sema::ImplicitExceptionSpecification
7518Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
7519 CXXRecordDecl *ClassDecl = MD->getParent();
7520
7521 ImplicitExceptionSpecification ExceptSpec(*this);
7522 if (ClassDecl->isInvalidDecl())
7523 return ExceptSpec;
7524
7525 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
7526 assert(T->getNumArgs() == 1 && "not a copy assignment op");
7527 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
7528
Douglas Gregorb87786f2010-07-01 17:48:08 +00007529 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00007530 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00007531 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007532
7533 // It is unspecified whether or not an implicit copy assignment operator
7534 // attempts to deduplicate calls to assignment operators of virtual bases are
7535 // made. As such, this exception specification is effectively unspecified.
7536 // Based on a similar decision made for constness in C++0x, we're erring on
7537 // the side of assuming such calls to be made regardless of whether they
7538 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007539 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7540 BaseEnd = ClassDecl->bases_end();
7541 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007542 if (Base->isVirtual())
7543 continue;
7544
Douglas Gregora376d102010-07-02 21:50:04 +00007545 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007546 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007547 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7548 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007549 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00007550 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007551
7552 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7553 BaseEnd = ClassDecl->vbases_end();
7554 Base != BaseEnd; ++Base) {
7555 CXXRecordDecl *BaseClassDecl
7556 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7557 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7558 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007559 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00007560 }
7561
Douglas Gregorb87786f2010-07-01 17:48:08 +00007562 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7563 FieldEnd = ClassDecl->field_end();
7564 Field != FieldEnd;
7565 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007566 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007567 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7568 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00007569 LookupCopyingAssignment(FieldClassDecl,
7570 ArgQuals | FieldType.getCVRQualifiers(),
7571 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007572 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007573 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007574 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007575
Richard Smithb9d0b762012-07-27 04:22:15 +00007576 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00007577}
7578
7579CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7580 // Note: The following rules are largely analoguous to the copy
7581 // constructor rules. Note that virtual bases are not taken into account
7582 // for determining the argument type of the operator. Note also that
7583 // operators taking an object instead of a reference are allowed.
7584
Sean Hunt30de05c2011-05-14 05:23:20 +00007585 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7586 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithb9d0b762012-07-27 04:22:15 +00007587 if (isImplicitCopyAssignmentArgConst(*this, ClassDecl))
Sean Hunt30de05c2011-05-14 05:23:20 +00007588 ArgType = ArgType.withConst();
7589 ArgType = Context.getLValueReferenceType(ArgType);
7590
Douglas Gregord3c35902010-07-01 16:36:15 +00007591 // An implicitly-declared copy assignment operator is an inline public
7592 // member of its class.
7593 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007594 SourceLocation ClassLoc = ClassDecl->getLocation();
7595 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007596 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00007597 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00007598 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007599 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007600 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007601 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007602 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007603 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007604 CopyAssignment->setImplicit();
7605 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Richard Smithb9d0b762012-07-27 04:22:15 +00007606
7607 // Build an exception specification pointing back at this member.
7608 FunctionProtoType::ExtProtoInfo EPI;
7609 EPI.ExceptionSpecType = EST_Unevaluated;
7610 EPI.ExceptionSpecDecl = CopyAssignment;
7611 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
7612
Douglas Gregord3c35902010-07-01 16:36:15 +00007613 // Add the parameter to the operator.
7614 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007615 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007616 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007617 SC_None,
7618 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007619 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007620
Douglas Gregora376d102010-07-02 21:50:04 +00007621 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007622 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007623
Douglas Gregor23c94db2010-07-02 17:43:08 +00007624 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007625 PushOnScopeChains(CopyAssignment, S, false);
7626 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007627
Nico Weberafcc96a2012-01-23 03:19:29 +00007628 // C++0x [class.copy]p19:
7629 // .... If the class definition does not explicitly declare a copy
7630 // assignment operator, there is no user-declared move constructor, and
7631 // there is no user-declared move assignment operator, a copy assignment
7632 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00007633 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007634 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00007635
Douglas Gregord3c35902010-07-01 16:36:15 +00007636 AddOverriddenMethods(ClassDecl, CopyAssignment);
7637 return CopyAssignment;
7638}
7639
Douglas Gregor06a9f362010-05-01 20:49:11 +00007640void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7641 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007642 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007643 CopyAssignOperator->isOverloadedOperator() &&
7644 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00007645 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7646 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007647 "DefineImplicitCopyAssignment called for wrong function");
7648
7649 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7650
7651 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7652 CopyAssignOperator->setInvalidDecl();
7653 return;
7654 }
7655
7656 CopyAssignOperator->setUsed();
7657
7658 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007659 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007660
7661 // C++0x [class.copy]p30:
7662 // The implicitly-defined or explicitly-defaulted copy assignment operator
7663 // for a non-union class X performs memberwise copy assignment of its
7664 // subobjects. The direct base classes of X are assigned first, in the
7665 // order of their declaration in the base-specifier-list, and then the
7666 // immediate non-static data members of X are assigned, in the order in
7667 // which they were declared in the class definition.
7668
7669 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00007670 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007671
7672 // The parameter for the "other" object, which we are copying from.
7673 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7674 Qualifiers OtherQuals = Other->getType().getQualifiers();
7675 QualType OtherRefType = Other->getType();
7676 if (const LValueReferenceType *OtherRef
7677 = OtherRefType->getAs<LValueReferenceType>()) {
7678 OtherRefType = OtherRef->getPointeeType();
7679 OtherQuals = OtherRefType.getQualifiers();
7680 }
7681
7682 // Our location for everything implicitly-generated.
7683 SourceLocation Loc = CopyAssignOperator->getLocation();
7684
7685 // Construct a reference to the "other" object. We'll be using this
7686 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007687 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007688 assert(OtherRef && "Reference to parameter cannot fail!");
7689
7690 // Construct the "this" pointer. We'll be using this throughout the generated
7691 // ASTs.
7692 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7693 assert(This && "Reference to this cannot fail!");
7694
7695 // Assign base classes.
7696 bool Invalid = false;
7697 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7698 E = ClassDecl->bases_end(); Base != E; ++Base) {
7699 // Form the assignment:
7700 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7701 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007702 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007703 Invalid = true;
7704 continue;
7705 }
7706
John McCallf871d0c2010-08-07 06:22:56 +00007707 CXXCastPath BasePath;
7708 BasePath.push_back(Base);
7709
Douglas Gregor06a9f362010-05-01 20:49:11 +00007710 // Construct the "from" expression, which is an implicit cast to the
7711 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007712 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007713 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7714 CK_UncheckedDerivedToBase,
7715 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007716
7717 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007718 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007719
7720 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007721 To = ImpCastExprToType(To.take(),
7722 Context.getCVRQualifiedType(BaseType,
7723 CopyAssignOperator->getTypeQualifiers()),
7724 CK_UncheckedDerivedToBase,
7725 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007726
7727 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007728 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007729 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007730 /*CopyingBaseSubobject=*/true,
7731 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007732 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007733 Diag(CurrentLocation, diag::note_member_synthesized_at)
7734 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7735 CopyAssignOperator->setInvalidDecl();
7736 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007737 }
7738
7739 // Success! Record the copy.
7740 Statements.push_back(Copy.takeAs<Expr>());
7741 }
7742
7743 // \brief Reference to the __builtin_memcpy function.
7744 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007745 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007746 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007747
7748 // Assign non-static members.
7749 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7750 FieldEnd = ClassDecl->field_end();
7751 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00007752 if (Field->isUnnamedBitfield())
7753 continue;
7754
Douglas Gregor06a9f362010-05-01 20:49:11 +00007755 // Check for members of reference type; we can't copy those.
7756 if (Field->getType()->isReferenceType()) {
7757 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7758 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7759 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007760 Diag(CurrentLocation, diag::note_member_synthesized_at)
7761 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007762 Invalid = true;
7763 continue;
7764 }
7765
7766 // Check for members of const-qualified, non-class type.
7767 QualType BaseType = Context.getBaseElementType(Field->getType());
7768 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7769 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7770 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7771 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007772 Diag(CurrentLocation, diag::note_member_synthesized_at)
7773 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007774 Invalid = true;
7775 continue;
7776 }
John McCallb77115d2011-06-17 00:18:42 +00007777
7778 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00007779 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7780 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007781
7782 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007783 if (FieldType->isIncompleteArrayType()) {
7784 assert(ClassDecl->hasFlexibleArrayMember() &&
7785 "Incomplete array type is not valid");
7786 continue;
7787 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007788
7789 // Build references to the field in the object we're copying from and to.
7790 CXXScopeSpec SS; // Intentionally empty
7791 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7792 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00007793 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007794 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007795 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007796 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007797 SS, SourceLocation(), 0,
7798 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007799 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007800 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007801 SS, SourceLocation(), 0,
7802 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007803 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7804 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7805
7806 // If the field should be copied with __builtin_memcpy rather than via
7807 // explicit assignments, do so. This optimization only applies for arrays
7808 // of scalars and arrays of class type with trivial copy-assignment
7809 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007810 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007811 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007812 // Compute the size of the memory buffer to be copied.
7813 QualType SizeType = Context.getSizeType();
7814 llvm::APInt Size(Context.getTypeSize(SizeType),
7815 Context.getTypeSizeInChars(BaseType).getQuantity());
7816 for (const ConstantArrayType *Array
7817 = Context.getAsConstantArrayType(FieldType);
7818 Array;
7819 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007820 llvm::APInt ArraySize
7821 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007822 Size *= ArraySize;
7823 }
7824
7825 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007826 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7827 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007828
7829 bool NeedsCollectableMemCpy =
7830 (BaseType->isRecordType() &&
7831 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7832
7833 if (NeedsCollectableMemCpy) {
7834 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007835 // Create a reference to the __builtin_objc_memmove_collectable function.
7836 LookupResult R(*this,
7837 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007838 Loc, LookupOrdinaryName);
7839 LookupName(R, TUScope, true);
7840
7841 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7842 if (!CollectableMemCpy) {
7843 // Something went horribly wrong earlier, and we will have
7844 // complained about it.
7845 Invalid = true;
7846 continue;
7847 }
7848
7849 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7850 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007851 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007852 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7853 }
7854 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007855 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007856 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007857 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7858 LookupOrdinaryName);
7859 LookupName(R, TUScope, true);
7860
7861 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7862 if (!BuiltinMemCpy) {
7863 // Something went horribly wrong earlier, and we will have complained
7864 // about it.
7865 Invalid = true;
7866 continue;
7867 }
7868
7869 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7870 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007871 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007872 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7873 }
7874
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00007875 SmallVector<Expr*, 8> CallArgs;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007876 CallArgs.push_back(To.takeAs<Expr>());
7877 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007878 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007879 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007880 if (NeedsCollectableMemCpy)
7881 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007882 CollectableMemCpyRef,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007883 Loc, CallArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00007884 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007885 else
7886 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007887 BuiltinMemCpyRef,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007888 Loc, CallArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00007889 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007890
Douglas Gregor06a9f362010-05-01 20:49:11 +00007891 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7892 Statements.push_back(Call.takeAs<Expr>());
7893 continue;
7894 }
7895
7896 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007897 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007898 To.get(), From.get(),
7899 /*CopyingBaseSubobject=*/false,
7900 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007901 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007902 Diag(CurrentLocation, diag::note_member_synthesized_at)
7903 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7904 CopyAssignOperator->setInvalidDecl();
7905 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007906 }
7907
7908 // Success! Record the copy.
7909 Statements.push_back(Copy.takeAs<Stmt>());
7910 }
7911
7912 if (!Invalid) {
7913 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007914 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007915
John McCall60d7b3a2010-08-24 06:29:42 +00007916 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007917 if (Return.isInvalid())
7918 Invalid = true;
7919 else {
7920 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007921
7922 if (Trap.hasErrorOccurred()) {
7923 Diag(CurrentLocation, diag::note_member_synthesized_at)
7924 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7925 Invalid = true;
7926 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007927 }
7928 }
7929
7930 if (Invalid) {
7931 CopyAssignOperator->setInvalidDecl();
7932 return;
7933 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00007934
7935 StmtResult Body;
7936 {
7937 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007938 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00007939 /*isStmtExpr=*/false);
7940 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7941 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007942 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007943
7944 if (ASTMutationListener *L = getASTMutationListener()) {
7945 L->CompletedImplicitDefinition(CopyAssignOperator);
7946 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007947}
7948
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007949Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007950Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
7951 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007952
Richard Smithb9d0b762012-07-27 04:22:15 +00007953 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007954 if (ClassDecl->isInvalidDecl())
7955 return ExceptSpec;
7956
7957 // C++0x [except.spec]p14:
7958 // An implicitly declared special member function (Clause 12) shall have an
7959 // exception-specification. [...]
7960
7961 // It is unspecified whether or not an implicit move assignment operator
7962 // attempts to deduplicate calls to assignment operators of virtual bases are
7963 // made. As such, this exception specification is effectively unspecified.
7964 // Based on a similar decision made for constness in C++0x, we're erring on
7965 // the side of assuming such calls to be made regardless of whether they
7966 // actually happen.
7967 // Note that a move constructor is not implicitly declared when there are
7968 // virtual bases, but it can still be user-declared and explicitly defaulted.
7969 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7970 BaseEnd = ClassDecl->bases_end();
7971 Base != BaseEnd; ++Base) {
7972 if (Base->isVirtual())
7973 continue;
7974
7975 CXXRecordDecl *BaseClassDecl
7976 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7977 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00007978 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007979 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007980 }
7981
7982 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7983 BaseEnd = ClassDecl->vbases_end();
7984 Base != BaseEnd; ++Base) {
7985 CXXRecordDecl *BaseClassDecl
7986 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7987 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00007988 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007989 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007990 }
7991
7992 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7993 FieldEnd = ClassDecl->field_end();
7994 Field != FieldEnd;
7995 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007996 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007997 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00007998 if (CXXMethodDecl *MoveAssign =
7999 LookupMovingAssignment(FieldClassDecl,
8000 FieldType.getCVRQualifiers(),
8001 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008002 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008003 }
8004 }
8005
8006 return ExceptSpec;
8007}
8008
Richard Smith1c931be2012-04-02 18:40:40 +00008009/// Determine whether the class type has any direct or indirect virtual base
8010/// classes which have a non-trivial move assignment operator.
8011static bool
8012hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8013 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8014 BaseEnd = ClassDecl->vbases_end();
8015 Base != BaseEnd; ++Base) {
8016 CXXRecordDecl *BaseClass =
8017 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8018
8019 // Try to declare the move assignment. If it would be deleted, then the
8020 // class does not have a non-trivial move assignment.
8021 if (BaseClass->needsImplicitMoveAssignment())
8022 S.DeclareImplicitMoveAssignment(BaseClass);
8023
8024 // If the class has both a trivial move assignment and a non-trivial move
8025 // assignment, hasTrivialMoveAssignment() is false.
8026 if (BaseClass->hasDeclaredMoveAssignment() &&
8027 !BaseClass->hasTrivialMoveAssignment())
8028 return true;
8029 }
8030
8031 return false;
8032}
8033
8034/// Determine whether the given type either has a move constructor or is
8035/// trivially copyable.
8036static bool
8037hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8038 Type = S.Context.getBaseElementType(Type);
8039
8040 // FIXME: Technically, non-trivially-copyable non-class types, such as
8041 // reference types, are supposed to return false here, but that appears
8042 // to be a standard defect.
8043 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Richard Smith5d59b792012-04-25 18:28:49 +00008044 if (!ClassDecl || !ClassDecl->getDefinition())
Richard Smith1c931be2012-04-02 18:40:40 +00008045 return true;
8046
8047 if (Type.isTriviallyCopyableType(S.Context))
8048 return true;
8049
8050 if (IsConstructor) {
8051 if (ClassDecl->needsImplicitMoveConstructor())
8052 S.DeclareImplicitMoveConstructor(ClassDecl);
8053 return ClassDecl->hasDeclaredMoveConstructor();
8054 }
8055
8056 if (ClassDecl->needsImplicitMoveAssignment())
8057 S.DeclareImplicitMoveAssignment(ClassDecl);
8058 return ClassDecl->hasDeclaredMoveAssignment();
8059}
8060
8061/// Determine whether all non-static data members and direct or virtual bases
8062/// of class \p ClassDecl have either a move operation, or are trivially
8063/// copyable.
8064static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8065 bool IsConstructor) {
8066 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8067 BaseEnd = ClassDecl->bases_end();
8068 Base != BaseEnd; ++Base) {
8069 if (Base->isVirtual())
8070 continue;
8071
8072 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8073 return false;
8074 }
8075
8076 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8077 BaseEnd = ClassDecl->vbases_end();
8078 Base != BaseEnd; ++Base) {
8079 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8080 return false;
8081 }
8082
8083 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8084 FieldEnd = ClassDecl->field_end();
8085 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008086 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008087 return false;
8088 }
8089
8090 return true;
8091}
8092
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008093CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008094 // C++11 [class.copy]p20:
8095 // If the definition of a class X does not explicitly declare a move
8096 // assignment operator, one will be implicitly declared as defaulted
8097 // if and only if:
8098 //
8099 // - [first 4 bullets]
8100 assert(ClassDecl->needsImplicitMoveAssignment());
8101
8102 // [Checked after we build the declaration]
8103 // - the move assignment operator would not be implicitly defined as
8104 // deleted,
8105
8106 // [DR1402]:
8107 // - X has no direct or indirect virtual base class with a non-trivial
8108 // move assignment operator, and
8109 // - each of X's non-static data members and direct or virtual base classes
8110 // has a type that either has a move assignment operator or is trivially
8111 // copyable.
8112 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8113 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8114 ClassDecl->setFailedImplicitMoveAssignment();
8115 return 0;
8116 }
8117
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008118 // Note: The following rules are largely analoguous to the move
8119 // constructor rules.
8120
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008121 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8122 QualType RetType = Context.getLValueReferenceType(ArgType);
8123 ArgType = Context.getRValueReferenceType(ArgType);
8124
8125 // An implicitly-declared move assignment operator is an inline public
8126 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008127 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8128 SourceLocation ClassLoc = ClassDecl->getLocation();
8129 DeclarationNameInfo NameInfo(Name, ClassLoc);
8130 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008131 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008132 /*TInfo=*/0, /*isStatic=*/false,
8133 /*StorageClassAsWritten=*/SC_None,
8134 /*isInline=*/true,
8135 /*isConstexpr=*/false,
8136 SourceLocation());
8137 MoveAssignment->setAccess(AS_public);
8138 MoveAssignment->setDefaulted();
8139 MoveAssignment->setImplicit();
8140 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8141
Richard Smithb9d0b762012-07-27 04:22:15 +00008142 // Build an exception specification pointing back at this member.
8143 FunctionProtoType::ExtProtoInfo EPI;
8144 EPI.ExceptionSpecType = EST_Unevaluated;
8145 EPI.ExceptionSpecDecl = MoveAssignment;
8146 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8147
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008148 // Add the parameter to the operator.
8149 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8150 ClassLoc, ClassLoc, /*Id=*/0,
8151 ArgType, /*TInfo=*/0,
8152 SC_None,
8153 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008154 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008155
8156 // Note that we have added this copy-assignment operator.
8157 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8158
8159 // C++0x [class.copy]p9:
8160 // If the definition of a class X does not explicitly declare a move
8161 // assignment operator, one will be implicitly declared as defaulted if and
8162 // only if:
8163 // [...]
8164 // - the move assignment operator would not be implicitly defined as
8165 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008166 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008167 // Cache this result so that we don't try to generate this over and over
8168 // on every lookup, leaking memory and wasting time.
8169 ClassDecl->setFailedImplicitMoveAssignment();
8170 return 0;
8171 }
8172
8173 if (Scope *S = getScopeForContext(ClassDecl))
8174 PushOnScopeChains(MoveAssignment, S, false);
8175 ClassDecl->addDecl(MoveAssignment);
8176
8177 AddOverriddenMethods(ClassDecl, MoveAssignment);
8178 return MoveAssignment;
8179}
8180
8181void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8182 CXXMethodDecl *MoveAssignOperator) {
8183 assert((MoveAssignOperator->isDefaulted() &&
8184 MoveAssignOperator->isOverloadedOperator() &&
8185 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008186 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8187 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008188 "DefineImplicitMoveAssignment called for wrong function");
8189
8190 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8191
8192 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8193 MoveAssignOperator->setInvalidDecl();
8194 return;
8195 }
8196
8197 MoveAssignOperator->setUsed();
8198
8199 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8200 DiagnosticErrorTrap Trap(Diags);
8201
8202 // C++0x [class.copy]p28:
8203 // The implicitly-defined or move assignment operator for a non-union class
8204 // X performs memberwise move assignment of its subobjects. The direct base
8205 // classes of X are assigned first, in the order of their declaration in the
8206 // base-specifier-list, and then the immediate non-static data members of X
8207 // are assigned, in the order in which they were declared in the class
8208 // definition.
8209
8210 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008211 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008212
8213 // The parameter for the "other" object, which we are move from.
8214 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8215 QualType OtherRefType = Other->getType()->
8216 getAs<RValueReferenceType>()->getPointeeType();
8217 assert(OtherRefType.getQualifiers() == 0 &&
8218 "Bad argument type of defaulted move assignment");
8219
8220 // Our location for everything implicitly-generated.
8221 SourceLocation Loc = MoveAssignOperator->getLocation();
8222
8223 // Construct a reference to the "other" object. We'll be using this
8224 // throughout the generated ASTs.
8225 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8226 assert(OtherRef && "Reference to parameter cannot fail!");
8227 // Cast to rvalue.
8228 OtherRef = CastForMoving(*this, OtherRef);
8229
8230 // Construct the "this" pointer. We'll be using this throughout the generated
8231 // ASTs.
8232 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8233 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008234
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008235 // Assign base classes.
8236 bool Invalid = false;
8237 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8238 E = ClassDecl->bases_end(); Base != E; ++Base) {
8239 // Form the assignment:
8240 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8241 QualType BaseType = Base->getType().getUnqualifiedType();
8242 if (!BaseType->isRecordType()) {
8243 Invalid = true;
8244 continue;
8245 }
8246
8247 CXXCastPath BasePath;
8248 BasePath.push_back(Base);
8249
8250 // Construct the "from" expression, which is an implicit cast to the
8251 // appropriately-qualified base type.
8252 Expr *From = OtherRef;
8253 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008254 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008255
8256 // Dereference "this".
8257 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8258
8259 // Implicitly cast "this" to the appropriately-qualified base type.
8260 To = ImpCastExprToType(To.take(),
8261 Context.getCVRQualifiedType(BaseType,
8262 MoveAssignOperator->getTypeQualifiers()),
8263 CK_UncheckedDerivedToBase,
8264 VK_LValue, &BasePath);
8265
8266 // Build the move.
8267 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8268 To.get(), From,
8269 /*CopyingBaseSubobject=*/true,
8270 /*Copying=*/false);
8271 if (Move.isInvalid()) {
8272 Diag(CurrentLocation, diag::note_member_synthesized_at)
8273 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8274 MoveAssignOperator->setInvalidDecl();
8275 return;
8276 }
8277
8278 // Success! Record the move.
8279 Statements.push_back(Move.takeAs<Expr>());
8280 }
8281
8282 // \brief Reference to the __builtin_memcpy function.
8283 Expr *BuiltinMemCpyRef = 0;
8284 // \brief Reference to the __builtin_objc_memmove_collectable function.
8285 Expr *CollectableMemCpyRef = 0;
8286
8287 // Assign non-static members.
8288 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8289 FieldEnd = ClassDecl->field_end();
8290 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008291 if (Field->isUnnamedBitfield())
8292 continue;
8293
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008294 // Check for members of reference type; we can't move those.
8295 if (Field->getType()->isReferenceType()) {
8296 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8297 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8298 Diag(Field->getLocation(), diag::note_declared_at);
8299 Diag(CurrentLocation, diag::note_member_synthesized_at)
8300 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8301 Invalid = true;
8302 continue;
8303 }
8304
8305 // Check for members of const-qualified, non-class type.
8306 QualType BaseType = Context.getBaseElementType(Field->getType());
8307 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8308 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8309 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8310 Diag(Field->getLocation(), diag::note_declared_at);
8311 Diag(CurrentLocation, diag::note_member_synthesized_at)
8312 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8313 Invalid = true;
8314 continue;
8315 }
8316
8317 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008318 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8319 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008320
8321 QualType FieldType = Field->getType().getNonReferenceType();
8322 if (FieldType->isIncompleteArrayType()) {
8323 assert(ClassDecl->hasFlexibleArrayMember() &&
8324 "Incomplete array type is not valid");
8325 continue;
8326 }
8327
8328 // Build references to the field in the object we're copying from and to.
8329 CXXScopeSpec SS; // Intentionally empty
8330 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8331 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008332 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008333 MemberLookup.resolveKind();
8334 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8335 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008336 SS, SourceLocation(), 0,
8337 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008338 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8339 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008340 SS, SourceLocation(), 0,
8341 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008342 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8343 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8344
8345 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8346 "Member reference with rvalue base must be rvalue except for reference "
8347 "members, which aren't allowed for move assignment.");
8348
8349 // If the field should be copied with __builtin_memcpy rather than via
8350 // explicit assignments, do so. This optimization only applies for arrays
8351 // of scalars and arrays of class type with trivial move-assignment
8352 // operators.
8353 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8354 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8355 // Compute the size of the memory buffer to be copied.
8356 QualType SizeType = Context.getSizeType();
8357 llvm::APInt Size(Context.getTypeSize(SizeType),
8358 Context.getTypeSizeInChars(BaseType).getQuantity());
8359 for (const ConstantArrayType *Array
8360 = Context.getAsConstantArrayType(FieldType);
8361 Array;
8362 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8363 llvm::APInt ArraySize
8364 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8365 Size *= ArraySize;
8366 }
8367
Douglas Gregor45d3d712011-09-01 02:09:07 +00008368 // Take the address of the field references for "from" and "to". We
8369 // directly construct UnaryOperators here because semantic analysis
8370 // does not permit us to take the address of an xvalue.
8371 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8372 Context.getPointerType(From.get()->getType()),
8373 VK_RValue, OK_Ordinary, Loc);
8374 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8375 Context.getPointerType(To.get()->getType()),
8376 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008377
8378 bool NeedsCollectableMemCpy =
8379 (BaseType->isRecordType() &&
8380 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8381
8382 if (NeedsCollectableMemCpy) {
8383 if (!CollectableMemCpyRef) {
8384 // Create a reference to the __builtin_objc_memmove_collectable function.
8385 LookupResult R(*this,
8386 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8387 Loc, LookupOrdinaryName);
8388 LookupName(R, TUScope, true);
8389
8390 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8391 if (!CollectableMemCpy) {
8392 // Something went horribly wrong earlier, and we will have
8393 // complained about it.
8394 Invalid = true;
8395 continue;
8396 }
8397
8398 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8399 CollectableMemCpy->getType(),
8400 VK_LValue, Loc, 0).take();
8401 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8402 }
8403 }
8404 // Create a reference to the __builtin_memcpy builtin function.
8405 else if (!BuiltinMemCpyRef) {
8406 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8407 LookupOrdinaryName);
8408 LookupName(R, TUScope, true);
8409
8410 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8411 if (!BuiltinMemCpy) {
8412 // Something went horribly wrong earlier, and we will have complained
8413 // about it.
8414 Invalid = true;
8415 continue;
8416 }
8417
8418 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8419 BuiltinMemCpy->getType(),
8420 VK_LValue, Loc, 0).take();
8421 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8422 }
8423
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008424 SmallVector<Expr*, 8> CallArgs;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008425 CallArgs.push_back(To.takeAs<Expr>());
8426 CallArgs.push_back(From.takeAs<Expr>());
8427 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8428 ExprResult Call = ExprError();
8429 if (NeedsCollectableMemCpy)
8430 Call = ActOnCallExpr(/*Scope=*/0,
8431 CollectableMemCpyRef,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008432 Loc, CallArgs,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008433 Loc);
8434 else
8435 Call = ActOnCallExpr(/*Scope=*/0,
8436 BuiltinMemCpyRef,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008437 Loc, CallArgs,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008438 Loc);
8439
8440 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8441 Statements.push_back(Call.takeAs<Expr>());
8442 continue;
8443 }
8444
8445 // Build the move of this field.
8446 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8447 To.get(), From.get(),
8448 /*CopyingBaseSubobject=*/false,
8449 /*Copying=*/false);
8450 if (Move.isInvalid()) {
8451 Diag(CurrentLocation, diag::note_member_synthesized_at)
8452 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8453 MoveAssignOperator->setInvalidDecl();
8454 return;
8455 }
8456
8457 // Success! Record the copy.
8458 Statements.push_back(Move.takeAs<Stmt>());
8459 }
8460
8461 if (!Invalid) {
8462 // Add a "return *this;"
8463 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8464
8465 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8466 if (Return.isInvalid())
8467 Invalid = true;
8468 else {
8469 Statements.push_back(Return.takeAs<Stmt>());
8470
8471 if (Trap.hasErrorOccurred()) {
8472 Diag(CurrentLocation, diag::note_member_synthesized_at)
8473 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8474 Invalid = true;
8475 }
8476 }
8477 }
8478
8479 if (Invalid) {
8480 MoveAssignOperator->setInvalidDecl();
8481 return;
8482 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008483
8484 StmtResult Body;
8485 {
8486 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008487 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008488 /*isStmtExpr=*/false);
8489 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8490 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008491 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8492
8493 if (ASTMutationListener *L = getASTMutationListener()) {
8494 L->CompletedImplicitDefinition(MoveAssignOperator);
8495 }
8496}
8497
Richard Smithb9d0b762012-07-27 04:22:15 +00008498/// Determine whether an implicit copy constructor for ClassDecl has a const
8499/// argument.
8500/// FIXME: It ought to be possible to store this on the record.
8501static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008502 if (ClassDecl->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00008503 return true;
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008504
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008505 // C++ [class.copy]p5:
8506 // The implicitly-declared copy constructor for a class X will
8507 // have the form
8508 //
8509 // X::X(const X&)
8510 //
8511 // if
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008512 // -- each direct or virtual base class B of X has a copy
8513 // constructor whose first parameter is of type const B& or
8514 // const volatile B&, and
8515 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8516 BaseEnd = ClassDecl->bases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00008517 Base != BaseEnd; ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008518 // Virtual bases are handled below.
8519 if (Base->isVirtual())
8520 continue;
Richard Smithb9d0b762012-07-27 04:22:15 +00008521
Douglas Gregor22584312010-07-02 23:41:54 +00008522 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008523 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Richard Smithb9d0b762012-07-27 04:22:15 +00008524 // FIXME: This lookup is wrong. If the copy ctor for a member or base is
8525 // ambiguous, we should still produce a constructor with a const-qualified
8526 // parameter.
8527 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8528 return false;
Douglas Gregor598a8542010-07-01 18:27:03 +00008529 }
8530
8531 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8532 BaseEnd = ClassDecl->vbases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00008533 Base != BaseEnd; ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008534 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008535 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Richard Smithb9d0b762012-07-27 04:22:15 +00008536 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8537 return false;
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008538 }
Richard Smithb9d0b762012-07-27 04:22:15 +00008539
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008540 // -- for all the nonstatic data members of X that are of a
8541 // class type M (or array thereof), each such class type
8542 // has a copy constructor whose first parameter is of type
8543 // const M& or const volatile M&.
8544 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8545 FieldEnd = ClassDecl->field_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00008546 Field != FieldEnd; ++Field) {
8547 QualType FieldType = S.Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008548 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smithb9d0b762012-07-27 04:22:15 +00008549 if (!S.LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const))
8550 return false;
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008551 }
8552 }
Richard Smithb9d0b762012-07-27 04:22:15 +00008553
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008554 // Otherwise, the implicitly declared copy constructor will have
8555 // the form
8556 //
8557 // X::X(X&)
Richard Smithb9d0b762012-07-27 04:22:15 +00008558
8559 return true;
8560}
8561
8562Sema::ImplicitExceptionSpecification
8563Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
8564 CXXRecordDecl *ClassDecl = MD->getParent();
8565
8566 ImplicitExceptionSpecification ExceptSpec(*this);
8567 if (ClassDecl->isInvalidDecl())
8568 return ExceptSpec;
8569
8570 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8571 assert(T->getNumArgs() >= 1 && "not a copy ctor");
8572 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8573
Douglas Gregor0d405db2010-07-01 20:59:04 +00008574 // C++ [except.spec]p14:
8575 // An implicitly declared special member function (Clause 12) shall have an
8576 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00008577 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8578 BaseEnd = ClassDecl->bases_end();
8579 Base != BaseEnd;
8580 ++Base) {
8581 // Virtual bases are handled below.
8582 if (Base->isVirtual())
8583 continue;
8584
Douglas Gregor22584312010-07-02 23:41:54 +00008585 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008586 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008587 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008588 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008589 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008590 }
8591 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8592 BaseEnd = ClassDecl->vbases_end();
8593 Base != BaseEnd;
8594 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008595 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008596 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008597 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008598 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008599 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008600 }
8601 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8602 FieldEnd = ClassDecl->field_end();
8603 Field != FieldEnd;
8604 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008605 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008606 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8607 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008608 LookupCopyingConstructor(FieldClassDecl,
8609 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00008610 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008611 }
8612 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008613
Richard Smithb9d0b762012-07-27 04:22:15 +00008614 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00008615}
8616
8617CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8618 CXXRecordDecl *ClassDecl) {
8619 // C++ [class.copy]p4:
8620 // If the class definition does not explicitly declare a copy
8621 // constructor, one is declared implicitly.
8622
Sean Hunt49634cf2011-05-13 06:10:58 +00008623 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8624 QualType ArgType = ClassType;
Richard Smithb9d0b762012-07-27 04:22:15 +00008625 bool Const = isImplicitCopyCtorArgConst(*this, ClassDecl);
Sean Hunt49634cf2011-05-13 06:10:58 +00008626 if (Const)
8627 ArgType = ArgType.withConst();
8628 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00008629
Richard Smith7756afa2012-06-10 05:43:50 +00008630 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8631 CXXCopyConstructor,
8632 Const);
8633
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008634 DeclarationName Name
8635 = Context.DeclarationNames.getCXXConstructorName(
8636 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008637 SourceLocation ClassLoc = ClassDecl->getLocation();
8638 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008639
8640 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008641 // member of its class.
8642 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00008643 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00008644 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008645 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008646 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008647 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008648 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008649
Richard Smithb9d0b762012-07-27 04:22:15 +00008650 // Build an exception specification pointing back at this member.
8651 FunctionProtoType::ExtProtoInfo EPI;
8652 EPI.ExceptionSpecType = EST_Unevaluated;
8653 EPI.ExceptionSpecDecl = CopyConstructor;
8654 CopyConstructor->setType(
8655 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8656
Douglas Gregor22584312010-07-02 23:41:54 +00008657 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008658 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8659
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008660 // Add the parameter to the constructor.
8661 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008662 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008663 /*IdentifierInfo=*/0,
8664 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008665 SC_None,
8666 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008667 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008668
Douglas Gregor23c94db2010-07-02 17:43:08 +00008669 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008670 PushOnScopeChains(CopyConstructor, S, false);
8671 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008672
Nico Weberafcc96a2012-01-23 03:19:29 +00008673 // C++11 [class.copy]p8:
8674 // ... If the class definition does not explicitly declare a copy
8675 // constructor, there is no user-declared move constructor, and there is no
8676 // user-declared move assignment operator, a copy constructor is implicitly
8677 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008678 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008679 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008680
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008681 return CopyConstructor;
8682}
8683
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008684void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008685 CXXConstructorDecl *CopyConstructor) {
8686 assert((CopyConstructor->isDefaulted() &&
8687 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008688 !CopyConstructor->doesThisDeclarationHaveABody() &&
8689 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008690 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008691
Anders Carlsson63010a72010-04-23 16:24:12 +00008692 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008693 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008694
Douglas Gregor39957dc2010-05-01 15:04:51 +00008695 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008696 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008697
Sean Huntcbb67482011-01-08 20:30:50 +00008698 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008699 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008700 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008701 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008702 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008703 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008704 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008705 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8706 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00008707 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008708 /*isStmtExpr=*/false)
8709 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008710 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008711 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008712
8713 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008714 if (ASTMutationListener *L = getASTMutationListener()) {
8715 L->CompletedImplicitDefinition(CopyConstructor);
8716 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008717}
8718
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008719Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008720Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
8721 CXXRecordDecl *ClassDecl = MD->getParent();
8722
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008723 // C++ [except.spec]p14:
8724 // An implicitly declared special member function (Clause 12) shall have an
8725 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00008726 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008727 if (ClassDecl->isInvalidDecl())
8728 return ExceptSpec;
8729
8730 // Direct base-class constructors.
8731 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8732 BEnd = ClassDecl->bases_end();
8733 B != BEnd; ++B) {
8734 if (B->isVirtual()) // Handled below.
8735 continue;
8736
8737 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8738 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00008739 CXXConstructorDecl *Constructor =
8740 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008741 // If this is a deleted function, add it anyway. This might be conformant
8742 // with the standard. This might not. I'm not sure. It might not matter.
8743 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008744 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008745 }
8746 }
8747
8748 // Virtual base-class constructors.
8749 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8750 BEnd = ClassDecl->vbases_end();
8751 B != BEnd; ++B) {
8752 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8753 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00008754 CXXConstructorDecl *Constructor =
8755 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008756 // If this is a deleted function, add it anyway. This might be conformant
8757 // with the standard. This might not. I'm not sure. It might not matter.
8758 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008759 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008760 }
8761 }
8762
8763 // Field constructors.
8764 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8765 FEnd = ClassDecl->field_end();
8766 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008767 QualType FieldType = Context.getBaseElementType(F->getType());
8768 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
8769 CXXConstructorDecl *Constructor =
8770 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008771 // If this is a deleted function, add it anyway. This might be conformant
8772 // with the standard. This might not. I'm not sure. It might not matter.
8773 // In particular, the problem is that this function never gets called. It
8774 // might just be ill-formed because this function attempts to refer to
8775 // a deleted function here.
8776 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008777 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008778 }
8779 }
8780
8781 return ExceptSpec;
8782}
8783
8784CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8785 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008786 // C++11 [class.copy]p9:
8787 // If the definition of a class X does not explicitly declare a move
8788 // constructor, one will be implicitly declared as defaulted if and only if:
8789 //
8790 // - [first 4 bullets]
8791 assert(ClassDecl->needsImplicitMoveConstructor());
8792
8793 // [Checked after we build the declaration]
8794 // - the move assignment operator would not be implicitly defined as
8795 // deleted,
8796
8797 // [DR1402]:
8798 // - each of X's non-static data members and direct or virtual base classes
8799 // has a type that either has a move constructor or is trivially copyable.
8800 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
8801 ClassDecl->setFailedImplicitMoveConstructor();
8802 return 0;
8803 }
8804
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008805 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8806 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008807
Richard Smith7756afa2012-06-10 05:43:50 +00008808 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8809 CXXMoveConstructor,
8810 false);
8811
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008812 DeclarationName Name
8813 = Context.DeclarationNames.getCXXConstructorName(
8814 Context.getCanonicalType(ClassType));
8815 SourceLocation ClassLoc = ClassDecl->getLocation();
8816 DeclarationNameInfo NameInfo(Name, ClassLoc);
8817
8818 // C++0x [class.copy]p11:
8819 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008820 // member of its class.
8821 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00008822 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00008823 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008824 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008825 MoveConstructor->setAccess(AS_public);
8826 MoveConstructor->setDefaulted();
8827 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008828
Richard Smithb9d0b762012-07-27 04:22:15 +00008829 // Build an exception specification pointing back at this member.
8830 FunctionProtoType::ExtProtoInfo EPI;
8831 EPI.ExceptionSpecType = EST_Unevaluated;
8832 EPI.ExceptionSpecDecl = MoveConstructor;
8833 MoveConstructor->setType(
8834 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8835
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008836 // Add the parameter to the constructor.
8837 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8838 ClassLoc, ClassLoc,
8839 /*IdentifierInfo=*/0,
8840 ArgType, /*TInfo=*/0,
8841 SC_None,
8842 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008843 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008844
8845 // C++0x [class.copy]p9:
8846 // If the definition of a class X does not explicitly declare a move
8847 // constructor, one will be implicitly declared as defaulted if and only if:
8848 // [...]
8849 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008850 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008851 // Cache this result so that we don't try to generate this over and over
8852 // on every lookup, leaking memory and wasting time.
8853 ClassDecl->setFailedImplicitMoveConstructor();
8854 return 0;
8855 }
8856
8857 // Note that we have declared this constructor.
8858 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8859
8860 if (Scope *S = getScopeForContext(ClassDecl))
8861 PushOnScopeChains(MoveConstructor, S, false);
8862 ClassDecl->addDecl(MoveConstructor);
8863
8864 return MoveConstructor;
8865}
8866
8867void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8868 CXXConstructorDecl *MoveConstructor) {
8869 assert((MoveConstructor->isDefaulted() &&
8870 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008871 !MoveConstructor->doesThisDeclarationHaveABody() &&
8872 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008873 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8874
8875 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8876 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8877
8878 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8879 DiagnosticErrorTrap Trap(Diags);
8880
8881 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8882 Trap.hasErrorOccurred()) {
8883 Diag(CurrentLocation, diag::note_member_synthesized_at)
8884 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8885 MoveConstructor->setInvalidDecl();
8886 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008887 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008888 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8889 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00008890 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008891 /*isStmtExpr=*/false)
8892 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008893 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008894 }
8895
8896 MoveConstructor->setUsed();
8897
8898 if (ASTMutationListener *L = getASTMutationListener()) {
8899 L->CompletedImplicitDefinition(MoveConstructor);
8900 }
8901}
8902
Douglas Gregore4e68d42012-02-15 19:33:52 +00008903bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8904 return FD->isDeleted() &&
8905 (FD->isDefaulted() || FD->isImplicit()) &&
8906 isa<CXXMethodDecl>(FD);
8907}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008908
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008909/// \brief Mark the call operator of the given lambda closure type as "used".
8910static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8911 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00008912 = cast<CXXMethodDecl>(
8913 *Lambda->lookup(
8914 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008915 CallOperator->setReferenced();
8916 CallOperator->setUsed();
8917}
8918
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008919void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8920 SourceLocation CurrentLocation,
8921 CXXConversionDecl *Conv)
8922{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008923 CXXRecordDecl *Lambda = Conv->getParent();
8924
8925 // Make sure that the lambda call operator is marked used.
8926 markLambdaCallOperatorUsed(*this, Lambda);
8927
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008928 Conv->setUsed();
8929
8930 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8931 DiagnosticErrorTrap Trap(Diags);
8932
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008933 // Return the address of the __invoke function.
8934 DeclarationName InvokeName = &Context.Idents.get("__invoke");
8935 CXXMethodDecl *Invoke
8936 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8937 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8938 VK_LValue, Conv->getLocation()).take();
8939 assert(FunctionRef && "Can't refer to __invoke function?");
8940 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8941 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8942 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008943 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008944
8945 // Fill in the __invoke function with a dummy implementation. IR generation
8946 // will fill in the actual details.
8947 Invoke->setUsed();
8948 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008949 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008950
8951 if (ASTMutationListener *L = getASTMutationListener()) {
8952 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008953 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008954 }
8955}
8956
8957void Sema::DefineImplicitLambdaToBlockPointerConversion(
8958 SourceLocation CurrentLocation,
8959 CXXConversionDecl *Conv)
8960{
8961 Conv->setUsed();
8962
8963 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8964 DiagnosticErrorTrap Trap(Diags);
8965
Douglas Gregorac1303e2012-02-22 05:02:47 +00008966 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008967 Expr *This = ActOnCXXThis(CurrentLocation).take();
8968 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008969
Eli Friedman23f02672012-03-01 04:01:32 +00008970 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
8971 Conv->getLocation(),
8972 Conv, DerefThis);
8973
8974 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
8975 // behavior. Note that only the general conversion function does this
8976 // (since it's unusable otherwise); in the case where we inline the
8977 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00008978 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00008979 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
8980 CK_CopyAndAutoreleaseBlockObject,
8981 BuildBlock.get(), 0, VK_RValue);
8982
8983 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008984 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00008985 Conv->setInvalidDecl();
8986 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008987 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00008988
Douglas Gregorac1303e2012-02-22 05:02:47 +00008989 // Create the return statement that returns the block from the conversion
8990 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00008991 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00008992 if (Return.isInvalid()) {
8993 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
8994 Conv->setInvalidDecl();
8995 return;
8996 }
8997
8998 // Set the body of the conversion function.
8999 Stmt *ReturnS = Return.take();
9000 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
9001 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009002 Conv->getLocation()));
9003
Douglas Gregorac1303e2012-02-22 05:02:47 +00009004 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009005 if (ASTMutationListener *L = getASTMutationListener()) {
9006 L->CompletedImplicitDefinition(Conv);
9007 }
9008}
9009
Douglas Gregorf52757d2012-03-10 06:53:13 +00009010/// \brief Determine whether the given list arguments contains exactly one
9011/// "real" (non-default) argument.
9012static bool hasOneRealArgument(MultiExprArg Args) {
9013 switch (Args.size()) {
9014 case 0:
9015 return false;
9016
9017 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009018 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009019 return false;
9020
9021 // fall through
9022 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009023 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009024 }
9025
9026 return false;
9027}
9028
John McCall60d7b3a2010-08-24 06:29:42 +00009029ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009030Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009031 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009032 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009033 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009034 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009035 unsigned ConstructKind,
9036 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009037 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009038
Douglas Gregor2f599792010-04-02 18:24:57 +00009039 // C++0x [class.copy]p34:
9040 // When certain criteria are met, an implementation is allowed to
9041 // omit the copy/move construction of a class object, even if the
9042 // copy/move constructor and/or destructor for the object have
9043 // side effects. [...]
9044 // - when a temporary class object that has not been bound to a
9045 // reference (12.2) would be copied/moved to a class object
9046 // with the same cv-unqualified type, the copy/move operation
9047 // can be omitted by constructing the temporary object
9048 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009049 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009050 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009051 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009052 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009053 }
Mike Stump1eb44332009-09-09 15:08:12 +00009054
9055 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009056 Elidable, ExprArgs, HadMultipleCandidates,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009057 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009058}
9059
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009060/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9061/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009062ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009063Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9064 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009065 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009066 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009067 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009068 unsigned ConstructKind,
9069 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009070 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009071 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009072 Constructor, Elidable, ExprArgs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00009073 HadMultipleCandidates, /*FIXME*/false,
9074 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009075 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9076 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009077}
9078
Mike Stump1eb44332009-09-09 15:08:12 +00009079bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009080 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009081 MultiExprArg Exprs,
9082 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009083 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009084 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009085 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009086 Exprs, HadMultipleCandidates, false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009087 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009088 if (TempResult.isInvalid())
9089 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009090
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009091 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009092 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009093 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009094 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009095 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009096
Anders Carlssonfe2de492009-08-25 05:18:00 +00009097 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009098}
9099
John McCall68c6c9a2010-02-02 09:10:11 +00009100void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009101 if (VD->isInvalidDecl()) return;
9102
John McCall68c6c9a2010-02-02 09:10:11 +00009103 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009104 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009105 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009106 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009107
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009108 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009109 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009110 CheckDestructorAccess(VD->getLocation(), Destructor,
9111 PDiag(diag::err_access_dtor_var)
9112 << VD->getDeclName()
9113 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009114 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009115
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009116 if (!VD->hasGlobalStorage()) return;
9117
9118 // Emit warning for non-trivial dtor in global scope (a real global,
9119 // class-static, function-static).
9120 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9121
9122 // TODO: this should be re-enabled for static locals by !CXAAtExit
9123 if (!VD->isStaticLocal())
9124 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009125}
9126
Douglas Gregor39da0b82009-09-09 23:08:42 +00009127/// \brief Given a constructor and the set of arguments provided for the
9128/// constructor, convert the arguments and add any required default arguments
9129/// to form a proper call to this constructor.
9130///
9131/// \returns true if an error occurred, false otherwise.
9132bool
9133Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9134 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009135 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009136 SmallVectorImpl<Expr*> &ConvertedArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009137 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009138 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9139 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009140 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009141
9142 const FunctionProtoType *Proto
9143 = Constructor->getType()->getAs<FunctionProtoType>();
9144 assert(Proto && "Constructor without a prototype?");
9145 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009146
9147 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009148 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009149 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009150 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009151 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009152
9153 VariadicCallType CallType =
9154 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009155 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009156 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9157 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009158 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009159 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009160
9161 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9162
Richard Smith831421f2012-06-25 20:30:08 +00009163 CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9164 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009165
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009166 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009167}
9168
Anders Carlsson20d45d22009-12-12 00:32:00 +00009169static inline bool
9170CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9171 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009172 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009173 if (isa<NamespaceDecl>(DC)) {
9174 return SemaRef.Diag(FnDecl->getLocation(),
9175 diag::err_operator_new_delete_declared_in_namespace)
9176 << FnDecl->getDeclName();
9177 }
9178
9179 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009180 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009181 return SemaRef.Diag(FnDecl->getLocation(),
9182 diag::err_operator_new_delete_declared_static)
9183 << FnDecl->getDeclName();
9184 }
9185
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009186 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009187}
9188
Anders Carlsson156c78e2009-12-13 17:53:43 +00009189static inline bool
9190CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9191 CanQualType ExpectedResultType,
9192 CanQualType ExpectedFirstParamType,
9193 unsigned DependentParamTypeDiag,
9194 unsigned InvalidParamTypeDiag) {
9195 QualType ResultType =
9196 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9197
9198 // Check that the result type is not dependent.
9199 if (ResultType->isDependentType())
9200 return SemaRef.Diag(FnDecl->getLocation(),
9201 diag::err_operator_new_delete_dependent_result_type)
9202 << FnDecl->getDeclName() << ExpectedResultType;
9203
9204 // Check that the result type is what we expect.
9205 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9206 return SemaRef.Diag(FnDecl->getLocation(),
9207 diag::err_operator_new_delete_invalid_result_type)
9208 << FnDecl->getDeclName() << ExpectedResultType;
9209
9210 // A function template must have at least 2 parameters.
9211 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9212 return SemaRef.Diag(FnDecl->getLocation(),
9213 diag::err_operator_new_delete_template_too_few_parameters)
9214 << FnDecl->getDeclName();
9215
9216 // The function decl must have at least 1 parameter.
9217 if (FnDecl->getNumParams() == 0)
9218 return SemaRef.Diag(FnDecl->getLocation(),
9219 diag::err_operator_new_delete_too_few_parameters)
9220 << FnDecl->getDeclName();
9221
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009222 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009223 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9224 if (FirstParamType->isDependentType())
9225 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9226 << FnDecl->getDeclName() << ExpectedFirstParamType;
9227
9228 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009229 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009230 ExpectedFirstParamType)
9231 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9232 << FnDecl->getDeclName() << ExpectedFirstParamType;
9233
9234 return false;
9235}
9236
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009237static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009238CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009239 // C++ [basic.stc.dynamic.allocation]p1:
9240 // A program is ill-formed if an allocation function is declared in a
9241 // namespace scope other than global scope or declared static in global
9242 // scope.
9243 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9244 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009245
9246 CanQualType SizeTy =
9247 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9248
9249 // C++ [basic.stc.dynamic.allocation]p1:
9250 // The return type shall be void*. The first parameter shall have type
9251 // std::size_t.
9252 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9253 SizeTy,
9254 diag::err_operator_new_dependent_param_type,
9255 diag::err_operator_new_param_type))
9256 return true;
9257
9258 // C++ [basic.stc.dynamic.allocation]p1:
9259 // The first parameter shall not have an associated default argument.
9260 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009261 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009262 diag::err_operator_new_default_arg)
9263 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9264
9265 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009266}
9267
9268static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009269CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9270 // C++ [basic.stc.dynamic.deallocation]p1:
9271 // A program is ill-formed if deallocation functions are declared in a
9272 // namespace scope other than global scope or declared static in global
9273 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009274 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9275 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009276
9277 // C++ [basic.stc.dynamic.deallocation]p2:
9278 // Each deallocation function shall return void and its first parameter
9279 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009280 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9281 SemaRef.Context.VoidPtrTy,
9282 diag::err_operator_delete_dependent_param_type,
9283 diag::err_operator_delete_param_type))
9284 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009285
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009286 return false;
9287}
9288
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009289/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9290/// of this overloaded operator is well-formed. If so, returns false;
9291/// otherwise, emits appropriate diagnostics and returns true.
9292bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009293 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009294 "Expected an overloaded operator declaration");
9295
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009296 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9297
Mike Stump1eb44332009-09-09 15:08:12 +00009298 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009299 // The allocation and deallocation functions, operator new,
9300 // operator new[], operator delete and operator delete[], are
9301 // described completely in 3.7.3. The attributes and restrictions
9302 // found in the rest of this subclause do not apply to them unless
9303 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009304 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009305 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009306
Anders Carlssona3ccda52009-12-12 00:26:23 +00009307 if (Op == OO_New || Op == OO_Array_New)
9308 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009309
9310 // C++ [over.oper]p6:
9311 // An operator function shall either be a non-static member
9312 // function or be a non-member function and have at least one
9313 // parameter whose type is a class, a reference to a class, an
9314 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009315 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9316 if (MethodDecl->isStatic())
9317 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009318 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009319 } else {
9320 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009321 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9322 ParamEnd = FnDecl->param_end();
9323 Param != ParamEnd; ++Param) {
9324 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009325 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9326 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009327 ClassOrEnumParam = true;
9328 break;
9329 }
9330 }
9331
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009332 if (!ClassOrEnumParam)
9333 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009334 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009335 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009336 }
9337
9338 // C++ [over.oper]p8:
9339 // An operator function cannot have default arguments (8.3.6),
9340 // except where explicitly stated below.
9341 //
Mike Stump1eb44332009-09-09 15:08:12 +00009342 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009343 // (C++ [over.call]p1).
9344 if (Op != OO_Call) {
9345 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9346 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009347 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009348 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009349 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009350 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009351 }
9352 }
9353
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009354 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9355 { false, false, false }
9356#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9357 , { Unary, Binary, MemberOnly }
9358#include "clang/Basic/OperatorKinds.def"
9359 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009360
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009361 bool CanBeUnaryOperator = OperatorUses[Op][0];
9362 bool CanBeBinaryOperator = OperatorUses[Op][1];
9363 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009364
9365 // C++ [over.oper]p8:
9366 // [...] Operator functions cannot have more or fewer parameters
9367 // than the number required for the corresponding operator, as
9368 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009369 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009370 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009371 if (Op != OO_Call &&
9372 ((NumParams == 1 && !CanBeUnaryOperator) ||
9373 (NumParams == 2 && !CanBeBinaryOperator) ||
9374 (NumParams < 1) || (NumParams > 2))) {
9375 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009376 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009377 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009378 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009379 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009380 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009381 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009382 assert(CanBeBinaryOperator &&
9383 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009384 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009385 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009386
Chris Lattner416e46f2008-11-21 07:57:12 +00009387 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009388 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009389 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009390
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009391 // Overloaded operators other than operator() cannot be variadic.
9392 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009393 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009394 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009395 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009396 }
9397
9398 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009399 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9400 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009401 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009402 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009403 }
9404
9405 // C++ [over.inc]p1:
9406 // The user-defined function called operator++ implements the
9407 // prefix and postfix ++ operator. If this function is a member
9408 // function with no parameters, or a non-member function with one
9409 // parameter of class or enumeration type, it defines the prefix
9410 // increment operator ++ for objects of that type. If the function
9411 // is a member function with one parameter (which shall be of type
9412 // int) or a non-member function with two parameters (the second
9413 // of which shall be of type int), it defines the postfix
9414 // increment operator ++ for objects of that type.
9415 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9416 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9417 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009418 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009419 ParamIsInt = BT->getKind() == BuiltinType::Int;
9420
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009421 if (!ParamIsInt)
9422 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009423 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009424 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009425 }
9426
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009427 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009428}
Chris Lattner5a003a42008-12-17 07:09:26 +00009429
Sean Hunta6c058d2010-01-13 09:01:02 +00009430/// CheckLiteralOperatorDeclaration - Check whether the declaration
9431/// of this literal operator function is well-formed. If so, returns
9432/// false; otherwise, emits appropriate diagnostics and returns true.
9433bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009434 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009435 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9436 << FnDecl->getDeclName();
9437 return true;
9438 }
9439
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009440 if (FnDecl->isExternC()) {
9441 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9442 return true;
9443 }
9444
Sean Hunta6c058d2010-01-13 09:01:02 +00009445 bool Valid = false;
9446
Richard Smith36f5cfe2012-03-09 08:00:36 +00009447 // This might be the definition of a literal operator template.
9448 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9449 // This might be a specialization of a literal operator template.
9450 if (!TpDecl)
9451 TpDecl = FnDecl->getPrimaryTemplate();
9452
Sean Hunt216c2782010-04-07 23:11:06 +00009453 // template <char...> type operator "" name() is the only valid template
9454 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009455 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009456 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009457 // Must have only one template parameter
9458 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9459 if (Params->size() == 1) {
9460 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009461 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009462
Sean Hunt216c2782010-04-07 23:11:06 +00009463 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009464 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9465 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9466 Valid = true;
9467 }
9468 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009469 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009470 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009471 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9472
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009473 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009474
Sean Hunt30019c02010-04-07 22:57:35 +00009475 // unsigned long long int, long double, and any character type are allowed
9476 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009477 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9478 Context.hasSameType(T, Context.LongDoubleTy) ||
9479 Context.hasSameType(T, Context.CharTy) ||
9480 Context.hasSameType(T, Context.WCharTy) ||
9481 Context.hasSameType(T, Context.Char16Ty) ||
9482 Context.hasSameType(T, Context.Char32Ty)) {
9483 if (++Param == FnDecl->param_end())
9484 Valid = true;
9485 goto FinishedParams;
9486 }
9487
Sean Hunt30019c02010-04-07 22:57:35 +00009488 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009489 const PointerType *PT = T->getAs<PointerType>();
9490 if (!PT)
9491 goto FinishedParams;
9492 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009493 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009494 goto FinishedParams;
9495 T = T.getUnqualifiedType();
9496
9497 // Move on to the second parameter;
9498 ++Param;
9499
9500 // If there is no second parameter, the first must be a const char *
9501 if (Param == FnDecl->param_end()) {
9502 if (Context.hasSameType(T, Context.CharTy))
9503 Valid = true;
9504 goto FinishedParams;
9505 }
9506
9507 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9508 // are allowed as the first parameter to a two-parameter function
9509 if (!(Context.hasSameType(T, Context.CharTy) ||
9510 Context.hasSameType(T, Context.WCharTy) ||
9511 Context.hasSameType(T, Context.Char16Ty) ||
9512 Context.hasSameType(T, Context.Char32Ty)))
9513 goto FinishedParams;
9514
9515 // The second and final parameter must be an std::size_t
9516 T = (*Param)->getType().getUnqualifiedType();
9517 if (Context.hasSameType(T, Context.getSizeType()) &&
9518 ++Param == FnDecl->param_end())
9519 Valid = true;
9520 }
9521
9522 // FIXME: This diagnostic is absolutely terrible.
9523FinishedParams:
9524 if (!Valid) {
9525 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9526 << FnDecl->getDeclName();
9527 return true;
9528 }
9529
Richard Smitha9e88b22012-03-09 08:16:22 +00009530 // A parameter-declaration-clause containing a default argument is not
9531 // equivalent to any of the permitted forms.
9532 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9533 ParamEnd = FnDecl->param_end();
9534 Param != ParamEnd; ++Param) {
9535 if ((*Param)->hasDefaultArg()) {
9536 Diag((*Param)->getDefaultArgRange().getBegin(),
9537 diag::err_literal_operator_default_argument)
9538 << (*Param)->getDefaultArgRange();
9539 break;
9540 }
9541 }
9542
Richard Smith2fb4ae32012-03-08 02:39:21 +00009543 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +00009544 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9545 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +00009546 // C++11 [usrlit.suffix]p1:
9547 // Literal suffix identifiers that do not start with an underscore
9548 // are reserved for future standardization.
9549 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +00009550 }
Richard Smith2fb4ae32012-03-08 02:39:21 +00009551
Sean Hunta6c058d2010-01-13 09:01:02 +00009552 return false;
9553}
9554
Douglas Gregor074149e2009-01-05 19:45:36 +00009555/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9556/// linkage specification, including the language and (if present)
9557/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9558/// the location of the language string literal, which is provided
9559/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9560/// the '{' brace. Otherwise, this linkage specification does not
9561/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009562Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9563 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009564 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009565 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009566 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009567 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009568 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009569 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009570 Language = LinkageSpecDecl::lang_cxx;
9571 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009572 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009573 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009574 }
Mike Stump1eb44332009-09-09 15:08:12 +00009575
Chris Lattnercc98eac2008-12-17 07:13:27 +00009576 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009577
Douglas Gregor074149e2009-01-05 19:45:36 +00009578 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009579 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009580 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009581 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009582 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009583}
9584
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009585/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009586/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9587/// valid, it's the position of the closing '}' brace in a linkage
9588/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009589Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009590 Decl *LinkageSpec,
9591 SourceLocation RBraceLoc) {
9592 if (LinkageSpec) {
9593 if (RBraceLoc.isValid()) {
9594 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9595 LSDecl->setRBraceLoc(RBraceLoc);
9596 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009597 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009598 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009599 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009600}
9601
Douglas Gregord308e622009-05-18 20:51:54 +00009602/// \brief Perform semantic analysis for the variable declaration that
9603/// occurs within a C++ catch clause, returning the newly-created
9604/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009605VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009606 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009607 SourceLocation StartLoc,
9608 SourceLocation Loc,
9609 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009610 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009611 QualType ExDeclType = TInfo->getType();
9612
Sebastian Redl4b07b292008-12-22 19:15:10 +00009613 // Arrays and functions decay.
9614 if (ExDeclType->isArrayType())
9615 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9616 else if (ExDeclType->isFunctionType())
9617 ExDeclType = Context.getPointerType(ExDeclType);
9618
9619 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9620 // The exception-declaration shall not denote a pointer or reference to an
9621 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009622 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009623 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009624 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009625 Invalid = true;
9626 }
Douglas Gregord308e622009-05-18 20:51:54 +00009627
Sebastian Redl4b07b292008-12-22 19:15:10 +00009628 QualType BaseType = ExDeclType;
9629 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009630 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009631 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009632 BaseType = Ptr->getPointeeType();
9633 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009634 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009635 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009636 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009637 BaseType = Ref->getPointeeType();
9638 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009639 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009640 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009641 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009642 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009643 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009644
Mike Stump1eb44332009-09-09 15:08:12 +00009645 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009646 RequireNonAbstractType(Loc, ExDeclType,
9647 diag::err_abstract_type_in_decl,
9648 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009649 Invalid = true;
9650
John McCall5a180392010-07-24 00:37:23 +00009651 // Only the non-fragile NeXT runtime currently supports C++ catches
9652 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +00009653 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +00009654 QualType T = ExDeclType;
9655 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9656 T = RT->getPointeeType();
9657
9658 if (T->isObjCObjectType()) {
9659 Diag(Loc, diag::err_objc_object_catch);
9660 Invalid = true;
9661 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +00009662 // FIXME: should this be a test for macosx-fragile specifically?
9663 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009664 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009665 }
9666 }
9667
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009668 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9669 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009670 ExDecl->setExceptionVariable(true);
9671
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009672 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00009673 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009674 Invalid = true;
9675
Douglas Gregorc41b8782011-07-06 18:14:43 +00009676 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009677 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009678 // C++ [except.handle]p16:
9679 // The object declared in an exception-declaration or, if the
9680 // exception-declaration does not specify a name, a temporary (12.2) is
9681 // copy-initialized (8.5) from the exception object. [...]
9682 // The object is destroyed when the handler exits, after the destruction
9683 // of any automatic objects initialized within the handler.
9684 //
9685 // We just pretend to initialize the object with itself, then make sure
9686 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009687 QualType initType = ExDeclType;
9688
9689 InitializedEntity entity =
9690 InitializedEntity::InitializeVariable(ExDecl);
9691 InitializationKind initKind =
9692 InitializationKind::CreateCopy(Loc, SourceLocation());
9693
9694 Expr *opaqueValue =
9695 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9696 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9697 ExprResult result = sequence.Perform(*this, entity, initKind,
9698 MultiExprArg(&opaqueValue, 1));
9699 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009700 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009701 else {
9702 // If the constructor used was non-trivial, set this as the
9703 // "initializer".
9704 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9705 if (!construct->getConstructor()->isTrivial()) {
9706 Expr *init = MaybeCreateExprWithCleanups(construct);
9707 ExDecl->setInit(init);
9708 }
9709
9710 // And make sure it's destructable.
9711 FinalizeVarWithDestructor(ExDecl, recordType);
9712 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009713 }
9714 }
9715
Douglas Gregord308e622009-05-18 20:51:54 +00009716 if (Invalid)
9717 ExDecl->setInvalidDecl();
9718
9719 return ExDecl;
9720}
9721
9722/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9723/// handler.
John McCalld226f652010-08-21 09:40:31 +00009724Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009725 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009726 bool Invalid = D.isInvalidType();
9727
9728 // Check for unexpanded parameter packs.
9729 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9730 UPPC_ExceptionType)) {
9731 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9732 D.getIdentifierLoc());
9733 Invalid = true;
9734 }
9735
Sebastian Redl4b07b292008-12-22 19:15:10 +00009736 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009737 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009738 LookupOrdinaryName,
9739 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009740 // The scope should be freshly made just for us. There is just no way
9741 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009742 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009743 if (PrevDecl->isTemplateParameter()) {
9744 // Maybe we will complain about the shadowed template parameter.
9745 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009746 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009747 }
9748 }
9749
Chris Lattnereaaebc72009-04-25 08:06:05 +00009750 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009751 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9752 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009753 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009754 }
9755
Douglas Gregor83cb9422010-09-09 17:09:21 +00009756 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009757 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009758 D.getIdentifierLoc(),
9759 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009760 if (Invalid)
9761 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009762
Sebastian Redl4b07b292008-12-22 19:15:10 +00009763 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009764 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009765 PushOnScopeChains(ExDecl, S);
9766 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009767 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009768
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009769 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009770 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009771}
Anders Carlssonfb311762009-03-14 00:25:26 +00009772
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009773Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009774 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +00009775 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009776 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +00009777 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +00009778
Richard Smithe3f470a2012-07-11 22:37:56 +00009779 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9780 return 0;
9781
9782 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
9783 AssertMessage, RParenLoc, false);
9784}
9785
9786Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9787 Expr *AssertExpr,
9788 StringLiteral *AssertMessage,
9789 SourceLocation RParenLoc,
9790 bool Failed) {
9791 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
9792 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +00009793 // In a static_assert-declaration, the constant-expression shall be a
9794 // constant expression that can be contextually converted to bool.
9795 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9796 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +00009797 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +00009798
Richard Smithdaaefc52011-12-14 23:32:26 +00009799 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +00009800 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009801 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +00009802 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +00009803 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +00009804
Richard Smithe3f470a2012-07-11 22:37:56 +00009805 if (!Failed && !Cond) {
Richard Smith0cc323c2012-03-05 23:20:05 +00009806 llvm::SmallString<256> MsgBuffer;
9807 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +00009808 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009809 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +00009810 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +00009811 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +00009812 }
Anders Carlssonc3082412009-03-14 00:33:21 +00009813 }
Mike Stump1eb44332009-09-09 15:08:12 +00009814
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009815 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +00009816 AssertExpr, AssertMessage, RParenLoc,
9817 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +00009818
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009819 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009820 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009821}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009822
Douglas Gregor1d869352010-04-07 16:53:43 +00009823/// \brief Perform semantic analysis of the given friend type declaration.
9824///
9825/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009826FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9827 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009828 TypeSourceInfo *TSInfo) {
9829 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9830
9831 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009832 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009833
Richard Smith6b130222011-10-18 21:39:00 +00009834 // C++03 [class.friend]p2:
9835 // An elaborated-type-specifier shall be used in a friend declaration
9836 // for a class.*
9837 //
9838 // * The class-key of the elaborated-type-specifier is required.
9839 if (!ActiveTemplateInstantiations.empty()) {
9840 // Do not complain about the form of friend template types during
9841 // template instantiation; we will already have complained when the
9842 // template was declared.
9843 } else if (!T->isElaboratedTypeSpecifier()) {
9844 // If we evaluated the type to a record type, suggest putting
9845 // a tag in front.
9846 if (const RecordType *RT = T->getAs<RecordType>()) {
9847 RecordDecl *RD = RT->getDecl();
9848
9849 std::string InsertionText = std::string(" ") + RD->getKindName();
9850
9851 Diag(TypeRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +00009852 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009853 diag::warn_cxx98_compat_unelaborated_friend_type :
9854 diag::ext_unelaborated_friend_type)
9855 << (unsigned) RD->getTagKind()
9856 << T
9857 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9858 InsertionText);
9859 } else {
9860 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009861 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009862 diag::warn_cxx98_compat_nonclass_type_friend :
9863 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009864 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009865 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009866 }
Richard Smith6b130222011-10-18 21:39:00 +00009867 } else if (T->getAs<EnumType>()) {
9868 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009869 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009870 diag::warn_cxx98_compat_enum_friend :
9871 diag::ext_enum_friend)
9872 << T
9873 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009874 }
9875
Douglas Gregor06245bf2010-04-07 17:57:12 +00009876 // C++0x [class.friend]p3:
9877 // If the type specifier in a friend declaration designates a (possibly
9878 // cv-qualified) class type, that class is declared as a friend; otherwise,
9879 // the friend declaration is ignored.
9880
9881 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9882 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009883
Abramo Bagnara0216df82011-10-29 20:52:52 +00009884 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009885}
9886
John McCall9a34edb2010-10-19 01:40:49 +00009887/// Handle a friend tag declaration where the scope specifier was
9888/// templated.
9889Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9890 unsigned TagSpec, SourceLocation TagLoc,
9891 CXXScopeSpec &SS,
9892 IdentifierInfo *Name, SourceLocation NameLoc,
9893 AttributeList *Attr,
9894 MultiTemplateParamsArg TempParamLists) {
9895 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9896
9897 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009898 bool Invalid = false;
9899
9900 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009901 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +00009902 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +00009903 TempParamLists.size(),
9904 /*friend*/ true,
9905 isExplicitSpecialization,
9906 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009907 if (TemplateParams->size() > 0) {
9908 // This is a declaration of a class template.
9909 if (Invalid)
9910 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009911
Eric Christopher4110e132011-07-21 05:34:24 +00009912 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9913 SS, Name, NameLoc, Attr,
9914 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009915 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009916 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +00009917 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009918 } else {
9919 // The "template<>" header is extraneous.
9920 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9921 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9922 isExplicitSpecialization = true;
9923 }
9924 }
9925
9926 if (Invalid) return 0;
9927
John McCall9a34edb2010-10-19 01:40:49 +00009928 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009929 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009930 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +00009931 isAllExplicitSpecializations = false;
9932 break;
9933 }
9934 }
9935
9936 // FIXME: don't ignore attributes.
9937
9938 // If it's explicit specializations all the way down, just forget
9939 // about the template header and build an appropriate non-templated
9940 // friend. TODO: for source fidelity, remember the headers.
9941 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009942 if (SS.isEmpty()) {
9943 bool Owned = false;
9944 bool IsDependent = false;
9945 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9946 Attr, AS_public,
9947 /*ModulePrivateLoc=*/SourceLocation(),
9948 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00009949 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009950 /*ScopedEnumUsesClassTag=*/false,
9951 /*UnderlyingType=*/TypeResult());
9952 }
9953
Douglas Gregor2494dd02011-03-01 01:34:45 +00009954 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009955 ElaboratedTypeKeyword Keyword
9956 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009957 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009958 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009959 if (T.isNull())
9960 return 0;
9961
9962 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9963 if (isa<DependentNameType>(T)) {
9964 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009965 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009966 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009967 TL.setNameLoc(NameLoc);
9968 } else {
9969 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009970 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009971 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009972 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9973 }
9974
9975 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9976 TSI, FriendLoc);
9977 Friend->setAccess(AS_public);
9978 CurContext->addDecl(Friend);
9979 return Friend;
9980 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009981
9982 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9983
9984
John McCall9a34edb2010-10-19 01:40:49 +00009985
9986 // Handle the case of a templated-scope friend class. e.g.
9987 // template <class T> class A<T>::B;
9988 // FIXME: we don't support these right now.
9989 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9990 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9991 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9992 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009993 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009994 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009995 TL.setNameLoc(NameLoc);
9996
9997 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9998 TSI, FriendLoc);
9999 Friend->setAccess(AS_public);
10000 Friend->setUnsupportedFriend(true);
10001 CurContext->addDecl(Friend);
10002 return Friend;
10003}
10004
10005
John McCalldd4a3b02009-09-16 22:47:08 +000010006/// Handle a friend type declaration. This works in tandem with
10007/// ActOnTag.
10008///
10009/// Notes on friend class templates:
10010///
10011/// We generally treat friend class declarations as if they were
10012/// declaring a class. So, for example, the elaborated type specifier
10013/// in a friend declaration is required to obey the restrictions of a
10014/// class-head (i.e. no typedefs in the scope chain), template
10015/// parameters are required to match up with simple template-ids, &c.
10016/// However, unlike when declaring a template specialization, it's
10017/// okay to refer to a template specialization without an empty
10018/// template parameter declaration, e.g.
10019/// friend class A<T>::B<unsigned>;
10020/// We permit this as a special case; if there are any template
10021/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010022/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010023Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010024 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010025 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010026
10027 assert(DS.isFriendSpecified());
10028 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10029
John McCalldd4a3b02009-09-16 22:47:08 +000010030 // Try to convert the decl specifier to a type. This works for
10031 // friend templates because ActOnTag never produces a ClassTemplateDecl
10032 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010033 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010034 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10035 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010036 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010037 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010038
Douglas Gregor6ccab972010-12-16 01:14:37 +000010039 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10040 return 0;
10041
John McCalldd4a3b02009-09-16 22:47:08 +000010042 // This is definitely an error in C++98. It's probably meant to
10043 // be forbidden in C++0x, too, but the specification is just
10044 // poorly written.
10045 //
10046 // The problem is with declarations like the following:
10047 // template <T> friend A<T>::foo;
10048 // where deciding whether a class C is a friend or not now hinges
10049 // on whether there exists an instantiation of A that causes
10050 // 'foo' to equal C. There are restrictions on class-heads
10051 // (which we declare (by fiat) elaborated friend declarations to
10052 // be) that makes this tractable.
10053 //
10054 // FIXME: handle "template <> friend class A<T>;", which
10055 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010056 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010057 Diag(Loc, diag::err_tagless_friend_type_template)
10058 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010059 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010060 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010061
John McCall02cace72009-08-28 07:59:38 +000010062 // C++98 [class.friend]p1: A friend of a class is a function
10063 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010064 // This is fixed in DR77, which just barely didn't make the C++03
10065 // deadline. It's also a very silly restriction that seriously
10066 // affects inner classes and which nobody else seems to implement;
10067 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010068 //
10069 // But note that we could warn about it: it's always useless to
10070 // friend one of your own members (it's not, however, worthless to
10071 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010072
John McCalldd4a3b02009-09-16 22:47:08 +000010073 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010074 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010075 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010076 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010077 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010078 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010079 DS.getFriendSpecLoc());
10080 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010081 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010082
10083 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010084 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010085
John McCalldd4a3b02009-09-16 22:47:08 +000010086 D->setAccess(AS_public);
10087 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010088
John McCalld226f652010-08-21 09:40:31 +000010089 return D;
John McCall02cace72009-08-28 07:59:38 +000010090}
10091
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010092Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010093 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010094 const DeclSpec &DS = D.getDeclSpec();
10095
10096 assert(DS.isFriendSpecified());
10097 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10098
10099 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010100 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010101
10102 // C++ [class.friend]p1
10103 // A friend of a class is a function or class....
10104 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010105 // It *doesn't* see through dependent types, which is correct
10106 // according to [temp.arg.type]p3:
10107 // If a declaration acquires a function type through a
10108 // type dependent on a template-parameter and this causes
10109 // a declaration that does not use the syntactic form of a
10110 // function declarator to have a function type, the program
10111 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010112 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010113 Diag(Loc, diag::err_unexpected_friend);
10114
10115 // It might be worthwhile to try to recover by creating an
10116 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010117 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010118 }
10119
10120 // C++ [namespace.memdef]p3
10121 // - If a friend declaration in a non-local class first declares a
10122 // class or function, the friend class or function is a member
10123 // of the innermost enclosing namespace.
10124 // - The name of the friend is not found by simple name lookup
10125 // until a matching declaration is provided in that namespace
10126 // scope (either before or after the class declaration granting
10127 // friendship).
10128 // - If a friend function is called, its name may be found by the
10129 // name lookup that considers functions from namespaces and
10130 // classes associated with the types of the function arguments.
10131 // - When looking for a prior declaration of a class or a function
10132 // declared as a friend, scopes outside the innermost enclosing
10133 // namespace scope are not considered.
10134
John McCall337ec3d2010-10-12 23:13:28 +000010135 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010136 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10137 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010138 assert(Name);
10139
Douglas Gregor6ccab972010-12-16 01:14:37 +000010140 // Check for unexpanded parameter packs.
10141 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10142 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10143 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10144 return 0;
10145
John McCall67d1a672009-08-06 02:15:43 +000010146 // The context we found the declaration in, or in which we should
10147 // create the declaration.
10148 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010149 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010150 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010151 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010152
John McCall337ec3d2010-10-12 23:13:28 +000010153 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010154
John McCall337ec3d2010-10-12 23:13:28 +000010155 // There are four cases here.
10156 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010157 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010158 // there as appropriate.
10159 // Recover from invalid scope qualifiers as if they just weren't there.
10160 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010161 // C++0x [namespace.memdef]p3:
10162 // If the name in a friend declaration is neither qualified nor
10163 // a template-id and the declaration is a function or an
10164 // elaborated-type-specifier, the lookup to determine whether
10165 // the entity has been previously declared shall not consider
10166 // any scopes outside the innermost enclosing namespace.
10167 // C++0x [class.friend]p11:
10168 // If a friend declaration appears in a local class and the name
10169 // specified is an unqualified name, a prior declaration is
10170 // looked up without considering scopes that are outside the
10171 // innermost enclosing non-class scope. For a friend function
10172 // declaration, if there is no prior declaration, the program is
10173 // ill-formed.
10174 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010175 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010176
John McCall29ae6e52010-10-13 05:45:15 +000010177 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010178 DC = CurContext;
10179 while (true) {
10180 // Skip class contexts. If someone can cite chapter and verse
10181 // for this behavior, that would be nice --- it's what GCC and
10182 // EDG do, and it seems like a reasonable intent, but the spec
10183 // really only says that checks for unqualified existing
10184 // declarations should stop at the nearest enclosing namespace,
10185 // not that they should only consider the nearest enclosing
10186 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010187 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010188 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010189
John McCall68263142009-11-18 22:49:29 +000010190 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010191
10192 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010193 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010194 break;
John McCall29ae6e52010-10-13 05:45:15 +000010195
John McCall8a407372010-10-14 22:22:28 +000010196 if (isTemplateId) {
10197 if (isa<TranslationUnitDecl>(DC)) break;
10198 } else {
10199 if (DC->isFileContext()) break;
10200 }
John McCall67d1a672009-08-06 02:15:43 +000010201 DC = DC->getParent();
10202 }
10203
10204 // C++ [class.friend]p1: A friend of a class is a function or
10205 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010206 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010207 // Most C++ 98 compilers do seem to give an error here, so
10208 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010209 if (!Previous.empty() && DC->Equals(CurContext))
10210 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010211 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010212 diag::warn_cxx98_compat_friend_is_member :
10213 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010214
John McCall380aaa42010-10-13 06:22:15 +000010215 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010216
Douglas Gregor883af832011-10-10 01:11:59 +000010217 // C++ [class.friend]p6:
10218 // A function can be defined in a friend declaration of a class if and
10219 // only if the class is a non-local class (9.8), the function name is
10220 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010221 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010222 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10223 }
10224
John McCall337ec3d2010-10-12 23:13:28 +000010225 // - There's a non-dependent scope specifier, in which case we
10226 // compute it and do a previous lookup there for a function
10227 // or function template.
10228 } else if (!SS.getScopeRep()->isDependent()) {
10229 DC = computeDeclContext(SS);
10230 if (!DC) return 0;
10231
10232 if (RequireCompleteDeclContext(SS, DC)) return 0;
10233
10234 LookupQualifiedName(Previous, DC);
10235
10236 // Ignore things found implicitly in the wrong scope.
10237 // TODO: better diagnostics for this case. Suggesting the right
10238 // qualified scope would be nice...
10239 LookupResult::Filter F = Previous.makeFilter();
10240 while (F.hasNext()) {
10241 NamedDecl *D = F.next();
10242 if (!DC->InEnclosingNamespaceSetOf(
10243 D->getDeclContext()->getRedeclContext()))
10244 F.erase();
10245 }
10246 F.done();
10247
10248 if (Previous.empty()) {
10249 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010250 Diag(Loc, diag::err_qualified_friend_not_found)
10251 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010252 return 0;
10253 }
10254
10255 // C++ [class.friend]p1: A friend of a class is a function or
10256 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010257 if (DC->Equals(CurContext))
10258 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010259 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010260 diag::warn_cxx98_compat_friend_is_member :
10261 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010262
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010263 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010264 // C++ [class.friend]p6:
10265 // A function can be defined in a friend declaration of a class if and
10266 // only if the class is a non-local class (9.8), the function name is
10267 // unqualified, and the function has namespace scope.
10268 SemaDiagnosticBuilder DB
10269 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10270
10271 DB << SS.getScopeRep();
10272 if (DC->isFileContext())
10273 DB << FixItHint::CreateRemoval(SS.getRange());
10274 SS.clear();
10275 }
John McCall337ec3d2010-10-12 23:13:28 +000010276
10277 // - There's a scope specifier that does not match any template
10278 // parameter lists, in which case we use some arbitrary context,
10279 // create a method or method template, and wait for instantiation.
10280 // - There's a scope specifier that does match some template
10281 // parameter lists, which we don't handle right now.
10282 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010283 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010284 // C++ [class.friend]p6:
10285 // A function can be defined in a friend declaration of a class if and
10286 // only if the class is a non-local class (9.8), the function name is
10287 // unqualified, and the function has namespace scope.
10288 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10289 << SS.getScopeRep();
10290 }
10291
John McCall337ec3d2010-10-12 23:13:28 +000010292 DC = CurContext;
10293 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010294 }
Douglas Gregor883af832011-10-10 01:11:59 +000010295
John McCall29ae6e52010-10-13 05:45:15 +000010296 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010297 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010298 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10299 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10300 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010301 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010302 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10303 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010304 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010305 }
John McCall67d1a672009-08-06 02:15:43 +000010306 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010307
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010308 // FIXME: This is an egregious hack to cope with cases where the scope stack
10309 // does not contain the declaration context, i.e., in an out-of-line
10310 // definition of a class.
10311 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10312 if (!DCScope) {
10313 FakeDCScope.setEntity(DC);
10314 DCScope = &FakeDCScope;
10315 }
10316
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010317 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010318 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010319 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010320 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010321
Douglas Gregor182ddf02009-09-28 00:08:27 +000010322 assert(ND->getDeclContext() == DC);
10323 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010324
John McCallab88d972009-08-31 22:39:49 +000010325 // Add the function declaration to the appropriate lookup tables,
10326 // adjusting the redeclarations list as necessary. We don't
10327 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010328 //
John McCallab88d972009-08-31 22:39:49 +000010329 // Also update the scope-based lookup if the target context's
10330 // lookup context is in lexical scope.
10331 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010332 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010333 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010334 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010335 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010336 }
John McCall02cace72009-08-28 07:59:38 +000010337
10338 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010339 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010340 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010341 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010342 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010343
John McCall1f2e1a92012-08-10 03:15:35 +000010344 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010345 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010346 } else {
10347 if (DC->isRecord()) CheckFriendAccess(ND);
10348
John McCall6102ca12010-10-16 06:59:13 +000010349 FunctionDecl *FD;
10350 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10351 FD = FTD->getTemplatedDecl();
10352 else
10353 FD = cast<FunctionDecl>(ND);
10354
10355 // Mark templated-scope function declarations as unsupported.
10356 if (FD->getNumTemplateParameterLists())
10357 FrD->setUnsupportedFriend(true);
10358 }
John McCall337ec3d2010-10-12 23:13:28 +000010359
John McCalld226f652010-08-21 09:40:31 +000010360 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010361}
10362
John McCalld226f652010-08-21 09:40:31 +000010363void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10364 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010365
Sebastian Redl50de12f2009-03-24 22:27:57 +000010366 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10367 if (!Fn) {
10368 Diag(DelLoc, diag::err_deleted_non_function);
10369 return;
10370 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010371 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010372 // Don't consider the implicit declaration we generate for explicit
10373 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010374 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10375 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010376 Diag(DelLoc, diag::err_deleted_decl_not_first);
10377 Diag(Prev->getLocation(), diag::note_previous_declaration);
10378 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010379 // If the declaration wasn't the first, we delete the function anyway for
10380 // recovery.
10381 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010382 Fn->setDeletedAsWritten();
Richard Smithe653ba22012-02-26 00:31:33 +000010383
10384 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10385 if (!MD)
10386 return;
10387
10388 // A deleted special member function is trivial if the corresponding
10389 // implicitly-declared function would have been.
10390 switch (getSpecialMember(MD)) {
10391 case CXXInvalid:
10392 break;
10393 case CXXDefaultConstructor:
10394 MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10395 break;
10396 case CXXCopyConstructor:
10397 MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10398 break;
10399 case CXXMoveConstructor:
10400 MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10401 break;
10402 case CXXCopyAssignment:
10403 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10404 break;
10405 case CXXMoveAssignment:
10406 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10407 break;
10408 case CXXDestructor:
10409 MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10410 break;
10411 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010412}
Sebastian Redl13e88542009-04-27 21:33:24 +000010413
Sean Hunte4246a62011-05-12 06:15:49 +000010414void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10415 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10416
10417 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010418 if (MD->getParent()->isDependentType()) {
10419 MD->setDefaulted();
10420 MD->setExplicitlyDefaulted();
10421 return;
10422 }
10423
Sean Hunte4246a62011-05-12 06:15:49 +000010424 CXXSpecialMember Member = getSpecialMember(MD);
10425 if (Member == CXXInvalid) {
10426 Diag(DefaultLoc, diag::err_default_special_members);
10427 return;
10428 }
10429
10430 MD->setDefaulted();
10431 MD->setExplicitlyDefaulted();
10432
Sean Huntcd10dec2011-05-23 23:14:04 +000010433 // If this definition appears within the record, do the checking when
10434 // the record is complete.
10435 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000010436 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000010437 // Find the uninstantiated declaration that actually had the '= default'
10438 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000010439 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000010440
10441 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010442 return;
10443
Richard Smithb9d0b762012-07-27 04:22:15 +000010444 CheckExplicitlyDefaultedSpecialMember(MD);
10445
Sean Hunte4246a62011-05-12 06:15:49 +000010446 switch (Member) {
10447 case CXXDefaultConstructor: {
10448 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010449 if (!CD->isInvalidDecl())
10450 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10451 break;
10452 }
10453
10454 case CXXCopyConstructor: {
10455 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010456 if (!CD->isInvalidDecl())
10457 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010458 break;
10459 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010460
Sean Hunt2b188082011-05-14 05:23:28 +000010461 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010462 if (!MD->isInvalidDecl())
10463 DefineImplicitCopyAssignment(DefaultLoc, MD);
10464 break;
10465 }
10466
Sean Huntcb45a0f2011-05-12 22:46:25 +000010467 case CXXDestructor: {
10468 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010469 if (!DD->isInvalidDecl())
10470 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010471 break;
10472 }
10473
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010474 case CXXMoveConstructor: {
10475 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010476 if (!CD->isInvalidDecl())
10477 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010478 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010479 }
Sean Hunt82713172011-05-25 23:16:36 +000010480
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010481 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010482 if (!MD->isInvalidDecl())
10483 DefineImplicitMoveAssignment(DefaultLoc, MD);
10484 break;
10485 }
10486
10487 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010488 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010489 }
10490 } else {
10491 Diag(DefaultLoc, diag::err_default_special_members);
10492 }
10493}
10494
Sebastian Redl13e88542009-04-27 21:33:24 +000010495static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010496 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010497 Stmt *SubStmt = *CI;
10498 if (!SubStmt)
10499 continue;
10500 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010501 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010502 diag::err_return_in_constructor_handler);
10503 if (!isa<Expr>(SubStmt))
10504 SearchForReturnInStmt(Self, SubStmt);
10505 }
10506}
10507
10508void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10509 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10510 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10511 SearchForReturnInStmt(*this, Handler);
10512 }
10513}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010514
Mike Stump1eb44332009-09-09 15:08:12 +000010515bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010516 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010517 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10518 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010519
Chandler Carruth73857792010-02-15 11:53:20 +000010520 if (Context.hasSameType(NewTy, OldTy) ||
10521 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010522 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010523
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010524 // Check if the return types are covariant
10525 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010526
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010527 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010528 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10529 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010530 NewClassTy = NewPT->getPointeeType();
10531 OldClassTy = OldPT->getPointeeType();
10532 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010533 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10534 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10535 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10536 NewClassTy = NewRT->getPointeeType();
10537 OldClassTy = OldRT->getPointeeType();
10538 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010539 }
10540 }
Mike Stump1eb44332009-09-09 15:08:12 +000010541
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010542 // The return types aren't either both pointers or references to a class type.
10543 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010544 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010545 diag::err_different_return_type_for_overriding_virtual_function)
10546 << New->getDeclName() << NewTy << OldTy;
10547 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010548
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010549 return true;
10550 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010551
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010552 // C++ [class.virtual]p6:
10553 // If the return type of D::f differs from the return type of B::f, the
10554 // class type in the return type of D::f shall be complete at the point of
10555 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010556 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10557 if (!RT->isBeingDefined() &&
10558 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000010559 diag::err_covariant_return_incomplete,
10560 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010561 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010562 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010563
Douglas Gregora4923eb2009-11-16 21:35:15 +000010564 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010565 // Check if the new class derives from the old class.
10566 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10567 Diag(New->getLocation(),
10568 diag::err_covariant_return_not_derived)
10569 << New->getDeclName() << NewTy << OldTy;
10570 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10571 return true;
10572 }
Mike Stump1eb44332009-09-09 15:08:12 +000010573
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010574 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010575 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010576 diag::err_covariant_return_inaccessible_base,
10577 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10578 // FIXME: Should this point to the return type?
10579 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010580 // FIXME: this note won't trigger for delayed access control
10581 // diagnostics, and it's impossible to get an undelayed error
10582 // here from access control during the original parse because
10583 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010584 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10585 return true;
10586 }
10587 }
Mike Stump1eb44332009-09-09 15:08:12 +000010588
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010589 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010590 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010591 Diag(New->getLocation(),
10592 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010593 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010594 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10595 return true;
10596 };
Mike Stump1eb44332009-09-09 15:08:12 +000010597
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010598
10599 // The new class type must have the same or less qualifiers as the old type.
10600 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10601 Diag(New->getLocation(),
10602 diag::err_covariant_return_type_class_type_more_qualified)
10603 << New->getDeclName() << NewTy << OldTy;
10604 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10605 return true;
10606 };
Mike Stump1eb44332009-09-09 15:08:12 +000010607
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010608 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010609}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010610
Douglas Gregor4ba31362009-12-01 17:24:26 +000010611/// \brief Mark the given method pure.
10612///
10613/// \param Method the method to be marked pure.
10614///
10615/// \param InitRange the source range that covers the "0" initializer.
10616bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010617 SourceLocation EndLoc = InitRange.getEnd();
10618 if (EndLoc.isValid())
10619 Method->setRangeEnd(EndLoc);
10620
Douglas Gregor4ba31362009-12-01 17:24:26 +000010621 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10622 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010623 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010624 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010625
10626 if (!Method->isInvalidDecl())
10627 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10628 << Method->getDeclName() << InitRange;
10629 return true;
10630}
10631
Douglas Gregor552e2992012-02-21 02:22:07 +000010632/// \brief Determine whether the given declaration is a static data member.
10633static bool isStaticDataMember(Decl *D) {
10634 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10635 if (!Var)
10636 return false;
10637
10638 return Var->isStaticDataMember();
10639}
John McCall731ad842009-12-19 09:28:58 +000010640/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10641/// an initializer for the out-of-line declaration 'Dcl'. The scope
10642/// is a fresh scope pushed for just this purpose.
10643///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010644/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10645/// static data member of class X, names should be looked up in the scope of
10646/// class X.
John McCalld226f652010-08-21 09:40:31 +000010647void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010648 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010649 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010650
John McCall731ad842009-12-19 09:28:58 +000010651 // We should only get called for declarations with scope specifiers, like:
10652 // int foo::bar;
10653 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010654 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000010655
10656 // If we are parsing the initializer for a static data member, push a
10657 // new expression evaluation context that is associated with this static
10658 // data member.
10659 if (isStaticDataMember(D))
10660 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010661}
10662
10663/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010664/// initializer for the out-of-line declaration 'D'.
10665void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010666 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010667 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010668
Douglas Gregor552e2992012-02-21 02:22:07 +000010669 if (isStaticDataMember(D))
10670 PopExpressionEvaluationContext();
10671
John McCall731ad842009-12-19 09:28:58 +000010672 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010673 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010674}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010675
10676/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10677/// C++ if/switch/while/for statement.
10678/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010679DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010680 // C++ 6.4p2:
10681 // The declarator shall not specify a function or an array.
10682 // The type-specifier-seq shall not contain typedef and shall not declare a
10683 // new class or enumeration.
10684 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10685 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010686
10687 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010688 if (!Dcl)
10689 return true;
10690
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010691 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10692 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010693 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010694 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010695 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010696
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010697 return Dcl;
10698}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010699
Douglas Gregordfe65432011-07-28 19:11:31 +000010700void Sema::LoadExternalVTableUses() {
10701 if (!ExternalSource)
10702 return;
10703
10704 SmallVector<ExternalVTableUse, 4> VTables;
10705 ExternalSource->ReadUsedVTables(VTables);
10706 SmallVector<VTableUse, 4> NewUses;
10707 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10708 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10709 = VTablesUsed.find(VTables[I].Record);
10710 // Even if a definition wasn't required before, it may be required now.
10711 if (Pos != VTablesUsed.end()) {
10712 if (!Pos->second && VTables[I].DefinitionRequired)
10713 Pos->second = true;
10714 continue;
10715 }
10716
10717 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10718 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10719 }
10720
10721 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10722}
10723
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010724void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10725 bool DefinitionRequired) {
10726 // Ignore any vtable uses in unevaluated operands or for classes that do
10727 // not have a vtable.
10728 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10729 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010730 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010731 return;
10732
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010733 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010734 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010735 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10736 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10737 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10738 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010739 // If we already had an entry, check to see if we are promoting this vtable
10740 // to required a definition. If so, we need to reappend to the VTableUses
10741 // list, since we may have already processed the first entry.
10742 if (DefinitionRequired && !Pos.first->second) {
10743 Pos.first->second = true;
10744 } else {
10745 // Otherwise, we can early exit.
10746 return;
10747 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010748 }
10749
10750 // Local classes need to have their virtual members marked
10751 // immediately. For all other classes, we mark their virtual members
10752 // at the end of the translation unit.
10753 if (Class->isLocalClass())
10754 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010755 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010756 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010757}
10758
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010759bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010760 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010761 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010762 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010763
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010764 // Note: The VTableUses vector could grow as a result of marking
10765 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000010766 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010767 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010768 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010769 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010770 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010771 if (!Class)
10772 continue;
10773
10774 SourceLocation Loc = VTableUses[I].second;
10775
Richard Smithb9d0b762012-07-27 04:22:15 +000010776 bool DefineVTable = true;
10777
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010778 // If this class has a key function, but that key function is
10779 // defined in another translation unit, we don't need to emit the
10780 // vtable even though we're using it.
10781 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010782 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010783 switch (KeyFunction->getTemplateSpecializationKind()) {
10784 case TSK_Undeclared:
10785 case TSK_ExplicitSpecialization:
10786 case TSK_ExplicitInstantiationDeclaration:
10787 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000010788 DefineVTable = false;
10789 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010790
10791 case TSK_ExplicitInstantiationDefinition:
10792 case TSK_ImplicitInstantiation:
10793 // We will be instantiating the key function.
10794 break;
10795 }
10796 } else if (!KeyFunction) {
10797 // If we have a class with no key function that is the subject
10798 // of an explicit instantiation declaration, suppress the
10799 // vtable; it will live with the explicit instantiation
10800 // definition.
10801 bool IsExplicitInstantiationDeclaration
10802 = Class->getTemplateSpecializationKind()
10803 == TSK_ExplicitInstantiationDeclaration;
10804 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10805 REnd = Class->redecls_end();
10806 R != REnd; ++R) {
10807 TemplateSpecializationKind TSK
10808 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10809 if (TSK == TSK_ExplicitInstantiationDeclaration)
10810 IsExplicitInstantiationDeclaration = true;
10811 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10812 IsExplicitInstantiationDeclaration = false;
10813 break;
10814 }
10815 }
10816
10817 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000010818 DefineVTable = false;
10819 }
10820
10821 // The exception specifications for all virtual members may be needed even
10822 // if we are not providing an authoritative form of the vtable in this TU.
10823 // We may choose to emit it available_externally anyway.
10824 if (!DefineVTable) {
10825 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
10826 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010827 }
10828
10829 // Mark all of the virtual members of this class as referenced, so
10830 // that we can build a vtable. Then, tell the AST consumer that a
10831 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010832 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010833 MarkVirtualMembersReferenced(Loc, Class);
10834 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10835 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10836
10837 // Optionally warn if we're emitting a weak vtable.
10838 if (Class->getLinkage() == ExternalLinkage &&
10839 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010840 const FunctionDecl *KeyFunctionDef = 0;
10841 if (!KeyFunction ||
10842 (KeyFunction->hasBody(KeyFunctionDef) &&
10843 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010844 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10845 TSK_ExplicitInstantiationDefinition
10846 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10847 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010848 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010849 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010850 VTableUses.clear();
10851
Douglas Gregor78844032011-04-22 22:25:37 +000010852 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010853}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010854
Richard Smithb9d0b762012-07-27 04:22:15 +000010855void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
10856 const CXXRecordDecl *RD) {
10857 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
10858 E = RD->method_end(); I != E; ++I)
10859 if ((*I)->isVirtual() && !(*I)->isPure())
10860 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
10861}
10862
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010863void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10864 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000010865 // Mark all functions which will appear in RD's vtable as used.
10866 CXXFinalOverriderMap FinalOverriders;
10867 RD->getFinalOverriders(FinalOverriders);
10868 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
10869 E = FinalOverriders.end();
10870 I != E; ++I) {
10871 for (OverridingMethods::const_iterator OI = I->second.begin(),
10872 OE = I->second.end();
10873 OI != OE; ++OI) {
10874 assert(OI->second.size() > 0 && "no final overrider");
10875 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000010876
Richard Smithff817f72012-07-07 06:59:51 +000010877 // C++ [basic.def.odr]p2:
10878 // [...] A virtual member function is used if it is not pure. [...]
10879 if (!Overrider->isPure())
10880 MarkFunctionReferenced(Loc, Overrider);
10881 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010882 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010883
10884 // Only classes that have virtual bases need a VTT.
10885 if (RD->getNumVBases() == 0)
10886 return;
10887
10888 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10889 e = RD->bases_end(); i != e; ++i) {
10890 const CXXRecordDecl *Base =
10891 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010892 if (Base->getNumVBases() == 0)
10893 continue;
10894 MarkVirtualMembersReferenced(Loc, Base);
10895 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010896}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010897
10898/// SetIvarInitializers - This routine builds initialization ASTs for the
10899/// Objective-C implementation whose ivars need be initialized.
10900void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000010901 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010902 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010903 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010904 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010905 CollectIvarsToConstructOrDestruct(OID, ivars);
10906 if (ivars.empty())
10907 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010908 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010909 for (unsigned i = 0; i < ivars.size(); i++) {
10910 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010911 if (Field->isInvalidDecl())
10912 continue;
10913
Sean Huntcbb67482011-01-08 20:30:50 +000010914 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010915 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10916 InitializationKind InitKind =
10917 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10918
10919 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010920 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010921 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010922 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010923 // Note, MemberInit could actually come back empty if no initialization
10924 // is required (e.g., because it would call a trivial default constructor)
10925 if (!MemberInit.get() || MemberInit.isInvalid())
10926 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010927
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010928 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010929 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10930 SourceLocation(),
10931 MemberInit.takeAs<Expr>(),
10932 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010933 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010934
10935 // Be sure that the destructor is accessible and is marked as referenced.
10936 if (const RecordType *RecordTy
10937 = Context.getBaseElementType(Field->getType())
10938 ->getAs<RecordType>()) {
10939 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010940 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010941 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010942 CheckDestructorAccess(Field->getLocation(), Destructor,
10943 PDiag(diag::err_access_dtor_ivar)
10944 << Context.getBaseElementType(Field->getType()));
10945 }
10946 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010947 }
10948 ObjCImplementation->setIvarInitializers(Context,
10949 AllToInit.data(), AllToInit.size());
10950 }
10951}
Sean Huntfe57eef2011-05-04 05:57:24 +000010952
Sean Huntebcbe1d2011-05-04 23:29:54 +000010953static
10954void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10955 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10956 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10957 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10958 Sema &S) {
10959 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10960 CE = Current.end();
10961 if (Ctor->isInvalidDecl())
10962 return;
10963
Richard Smitha8eaf002012-08-23 06:16:52 +000010964 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
10965
10966 // Target may not be determinable yet, for instance if this is a dependent
10967 // call in an uninstantiated template.
10968 if (Target) {
10969 const FunctionDecl *FNTarget = 0;
10970 (void)Target->hasBody(FNTarget);
10971 Target = const_cast<CXXConstructorDecl*>(
10972 cast_or_null<CXXConstructorDecl>(FNTarget));
10973 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010974
10975 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10976 // Avoid dereferencing a null pointer here.
10977 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10978
10979 if (!Current.insert(Canonical))
10980 return;
10981
10982 // We know that beyond here, we aren't chaining into a cycle.
10983 if (!Target || !Target->isDelegatingConstructor() ||
10984 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10985 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10986 Valid.insert(*CI);
10987 Current.clear();
10988 // We've hit a cycle.
10989 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10990 Current.count(TCanonical)) {
10991 // If we haven't diagnosed this cycle yet, do so now.
10992 if (!Invalid.count(TCanonical)) {
10993 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010994 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010995 << Ctor;
10996
Richard Smitha8eaf002012-08-23 06:16:52 +000010997 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000010998 if (TCanonical != Canonical)
10999 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11000
11001 CXXConstructorDecl *C = Target;
11002 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011003 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011004 (void)C->getTargetConstructor()->hasBody(FNTarget);
11005 assert(FNTarget && "Ctor cycle through bodiless function");
11006
Richard Smitha8eaf002012-08-23 06:16:52 +000011007 C = const_cast<CXXConstructorDecl*>(
11008 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011009 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11010 }
11011 }
11012
11013 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11014 Invalid.insert(*CI);
11015 Current.clear();
11016 } else {
11017 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11018 }
11019}
11020
11021
Sean Huntfe57eef2011-05-04 05:57:24 +000011022void Sema::CheckDelegatingCtorCycles() {
11023 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11024
Sean Huntebcbe1d2011-05-04 23:29:54 +000011025 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11026 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011027
Douglas Gregor0129b562011-07-27 21:57:17 +000011028 for (DelegatingCtorDeclsType::iterator
11029 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011030 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011031 I != E; ++I)
11032 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011033
11034 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11035 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011036}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011037
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011038namespace {
11039 /// \brief AST visitor that finds references to the 'this' expression.
11040 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11041 Sema &S;
11042
11043 public:
11044 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11045
11046 bool VisitCXXThisExpr(CXXThisExpr *E) {
11047 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11048 << E->isImplicit();
11049 return false;
11050 }
11051 };
11052}
11053
11054bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11055 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11056 if (!TSInfo)
11057 return false;
11058
11059 TypeLoc TL = TSInfo->getTypeLoc();
11060 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11061 if (!ProtoTL)
11062 return false;
11063
11064 // C++11 [expr.prim.general]p3:
11065 // [The expression this] shall not appear before the optional
11066 // cv-qualifier-seq and it shall not appear within the declaration of a
11067 // static member function (although its type and value category are defined
11068 // within a static member function as they are within a non-static member
11069 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011070 // until the complete declarator is known. - end note ]
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011071 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11072 FindCXXThisExpr Finder(*this);
11073
11074 // If the return type came after the cv-qualifier-seq, check it now.
11075 if (Proto->hasTrailingReturn() &&
11076 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11077 return true;
11078
11079 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011080 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11081 return true;
11082
11083 return checkThisInStaticMemberFunctionAttributes(Method);
11084}
11085
11086bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11087 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11088 if (!TSInfo)
11089 return false;
11090
11091 TypeLoc TL = TSInfo->getTypeLoc();
11092 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11093 if (!ProtoTL)
11094 return false;
11095
11096 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11097 FindCXXThisExpr Finder(*this);
11098
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011099 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011100 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011101 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011102 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011103 case EST_DynamicNone:
11104 case EST_MSAny:
11105 case EST_None:
11106 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011107
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011108 case EST_ComputedNoexcept:
11109 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11110 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011111
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011112 case EST_Dynamic:
11113 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011114 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011115 E != EEnd; ++E) {
11116 if (!Finder.TraverseType(*E))
11117 return true;
11118 }
11119 break;
11120 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011121
11122 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011123}
11124
11125bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11126 FindCXXThisExpr Finder(*this);
11127
11128 // Check attributes.
11129 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11130 A != AEnd; ++A) {
11131 // FIXME: This should be emitted by tblgen.
11132 Expr *Arg = 0;
11133 ArrayRef<Expr *> Args;
11134 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11135 Arg = G->getArg();
11136 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11137 Arg = G->getArg();
11138 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11139 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11140 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11141 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11142 else if (ExclusiveLockFunctionAttr *ELF
11143 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11144 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11145 else if (SharedLockFunctionAttr *SLF
11146 = dyn_cast<SharedLockFunctionAttr>(*A))
11147 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11148 else if (ExclusiveTrylockFunctionAttr *ETLF
11149 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11150 Arg = ETLF->getSuccessValue();
11151 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11152 } else if (SharedTrylockFunctionAttr *STLF
11153 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11154 Arg = STLF->getSuccessValue();
11155 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11156 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11157 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11158 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11159 Arg = LR->getArg();
11160 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11161 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11162 else if (ExclusiveLocksRequiredAttr *ELR
11163 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11164 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11165 else if (SharedLocksRequiredAttr *SLR
11166 = dyn_cast<SharedLocksRequiredAttr>(*A))
11167 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11168
11169 if (Arg && !Finder.TraverseStmt(Arg))
11170 return true;
11171
11172 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11173 if (!Finder.TraverseStmt(Args[I]))
11174 return true;
11175 }
11176 }
11177
11178 return false;
11179}
11180
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011181void
11182Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11183 ArrayRef<ParsedType> DynamicExceptions,
11184 ArrayRef<SourceRange> DynamicExceptionRanges,
11185 Expr *NoexceptExpr,
11186 llvm::SmallVectorImpl<QualType> &Exceptions,
11187 FunctionProtoType::ExtProtoInfo &EPI) {
11188 Exceptions.clear();
11189 EPI.ExceptionSpecType = EST;
11190 if (EST == EST_Dynamic) {
11191 Exceptions.reserve(DynamicExceptions.size());
11192 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11193 // FIXME: Preserve type source info.
11194 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11195
11196 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11197 collectUnexpandedParameterPacks(ET, Unexpanded);
11198 if (!Unexpanded.empty()) {
11199 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11200 UPPC_ExceptionType,
11201 Unexpanded);
11202 continue;
11203 }
11204
11205 // Check that the type is valid for an exception spec, and
11206 // drop it if not.
11207 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11208 Exceptions.push_back(ET);
11209 }
11210 EPI.NumExceptions = Exceptions.size();
11211 EPI.Exceptions = Exceptions.data();
11212 return;
11213 }
11214
11215 if (EST == EST_ComputedNoexcept) {
11216 // If an error occurred, there's no expression here.
11217 if (NoexceptExpr) {
11218 assert((NoexceptExpr->isTypeDependent() ||
11219 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11220 Context.BoolTy) &&
11221 "Parser should have made sure that the expression is boolean");
11222 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11223 EPI.ExceptionSpecType = EST_BasicNoexcept;
11224 return;
11225 }
11226
11227 if (!NoexceptExpr->isValueDependent())
11228 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011229 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011230 /*AllowFold*/ false).take();
11231 EPI.NoexceptExpr = NoexceptExpr;
11232 }
11233 return;
11234 }
11235}
11236
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011237/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11238Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11239 // Implicitly declared functions (e.g. copy constructors) are
11240 // __host__ __device__
11241 if (D->isImplicit())
11242 return CFT_HostDevice;
11243
11244 if (D->hasAttr<CUDAGlobalAttr>())
11245 return CFT_Global;
11246
11247 if (D->hasAttr<CUDADeviceAttr>()) {
11248 if (D->hasAttr<CUDAHostAttr>())
11249 return CFT_HostDevice;
11250 else
11251 return CFT_Device;
11252 }
11253
11254 return CFT_Host;
11255}
11256
11257bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11258 CUDAFunctionTarget CalleeTarget) {
11259 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11260 // Callable from the device only."
11261 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11262 return true;
11263
11264 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11265 // Callable from the host only."
11266 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11267 // Callable from the host only."
11268 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11269 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11270 return true;
11271
11272 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11273 return true;
11274
11275 return false;
11276}