blob: 71b32e570b41a8204fde6407ecc15931c89d9895 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Richard Smith4ac537b2013-07-23 08:14:48 +000030#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000040#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000041#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000042#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000043
44using namespace clang;
45
Chris Lattner8123a952008-04-10 02:22:51 +000046//===----------------------------------------------------------------------===//
47// CheckDefaultArgumentVisitor
48//===----------------------------------------------------------------------===//
49
Chris Lattner9e979552008-04-12 23:52:44 +000050namespace {
51 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
52 /// the default argument of a parameter to determine whether it
53 /// contains any ill-formed subexpressions. For example, this will
54 /// diagnose the use of local variables or parameters within the
55 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000056 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000057 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000058 Expr *DefaultArg;
59 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000060
Chris Lattner9e979552008-04-12 23:52:44 +000061 public:
Mike Stump1eb44332009-09-09 15:08:12 +000062 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000063 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000064
Chris Lattner9e979552008-04-12 23:52:44 +000065 bool VisitExpr(Expr *Node);
66 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000067 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000068 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000069 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000070 };
Chris Lattner8123a952008-04-10 02:22:51 +000071
Chris Lattner9e979552008-04-12 23:52:44 +000072 /// VisitExpr - Visit all of the children of this expression.
73 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
74 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000075 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000076 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000077 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000078 }
79
Chris Lattner9e979552008-04-12 23:52:44 +000080 /// VisitDeclRefExpr - Visit a reference to a declaration, to
81 /// determine whether this declaration can be used in the default
82 /// argument expression.
83 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000084 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000085 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
86 // C++ [dcl.fct.default]p9
87 // Default arguments are evaluated each time the function is
88 // called. The order of evaluation of function arguments is
89 // unspecified. Consequently, parameters of a function shall not
90 // be used in default argument expressions, even if they are not
91 // evaluated. Parameters of a function declared before a default
92 // argument expression are in scope and can hide namespace and
93 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000094 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000096 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000097 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000098 // C++ [dcl.fct.default]p7
99 // Local variables shall not be used in default argument
100 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000101 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000102 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000103 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000104 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000105 }
Chris Lattner8123a952008-04-10 02:22:51 +0000106
Douglas Gregor3996f232008-11-04 13:41:56 +0000107 return false;
108 }
Chris Lattner9e979552008-04-12 23:52:44 +0000109
Douglas Gregor796da182008-11-04 14:32:21 +0000110 /// VisitCXXThisExpr - Visit a C++ "this" expression.
111 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
112 // C++ [dcl.fct.default]p8:
113 // The keyword this shall not be used in a default argument of a
114 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000115 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000116 diag::err_param_default_argument_references_this)
117 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000118 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000119
John McCall045d2522013-04-09 01:56:28 +0000120 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
121 bool Invalid = false;
122 for (PseudoObjectExpr::semantics_iterator
123 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
124 Expr *E = *i;
125
126 // Look through bindings.
127 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
128 E = OVE->getSourceExpr();
129 assert(E && "pseudo-object binding without source expression?");
130 }
131
132 Invalid |= Visit(E);
133 }
134 return Invalid;
135 }
136
Douglas Gregorf0459f82012-02-10 23:30:22 +0000137 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
138 // C++11 [expr.lambda.prim]p13:
139 // A lambda-expression appearing in a default argument shall not
140 // implicitly or explicitly capture any entity.
141 if (Lambda->capture_begin() == Lambda->capture_end())
142 return false;
143
144 return S->Diag(Lambda->getLocStart(),
145 diag::err_lambda_capture_default_arg);
146 }
Chris Lattner8123a952008-04-10 02:22:51 +0000147}
148
Richard Smith0b0ca472013-04-10 06:11:48 +0000149void
150Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
151 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000152 // If we have an MSAny spec already, don't bother.
153 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000154 return;
155
156 const FunctionProtoType *Proto
157 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000158 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
159 if (!Proto)
160 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000161
162 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
163
164 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000165 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000166 ClearExceptions();
167 ComputedEST = EST;
168 return;
169 }
170
Richard Smith7a614d82011-06-11 17:19:42 +0000171 // FIXME: If the call to this decl is using any of its default arguments, we
172 // need to search them for potentially-throwing calls.
173
Sean Hunt001cad92011-05-10 00:49:42 +0000174 // If this function has a basic noexcept, it doesn't affect the outcome.
175 if (EST == EST_BasicNoexcept)
176 return;
177
178 // If we have a throw-all spec at this point, ignore the function.
179 if (ComputedEST == EST_None)
180 return;
181
182 // If we're still at noexcept(true) and there's a nothrow() callee,
183 // change to that specification.
184 if (EST == EST_DynamicNone) {
185 if (ComputedEST == EST_BasicNoexcept)
186 ComputedEST = EST_DynamicNone;
187 return;
188 }
189
190 // Check out noexcept specs.
191 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000192 FunctionProtoType::NoexceptResult NR =
193 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000194 assert(NR != FunctionProtoType::NR_NoNoexcept &&
195 "Must have noexcept result for EST_ComputedNoexcept.");
196 assert(NR != FunctionProtoType::NR_Dependent &&
197 "Should not generate implicit declarations for dependent cases, "
198 "and don't know how to handle them anyway.");
199
200 // noexcept(false) -> no spec on the new function
201 if (NR == FunctionProtoType::NR_Throw) {
202 ClearExceptions();
203 ComputedEST = EST_None;
204 }
205 // noexcept(true) won't change anything either.
206 return;
207 }
208
209 assert(EST == EST_Dynamic && "EST case not considered earlier.");
210 assert(ComputedEST != EST_None &&
211 "Shouldn't collect exceptions when throw-all is guaranteed.");
212 ComputedEST = EST_Dynamic;
213 // Record the exceptions in this function's exception specification.
214 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
215 EEnd = Proto->exception_end();
216 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000217 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000218 Exceptions.push_back(*E);
219}
220
Richard Smith7a614d82011-06-11 17:19:42 +0000221void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000222 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000223 return;
224
225 // FIXME:
226 //
227 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000228 // [An] implicit exception-specification specifies the type-id T if and
229 // only if T is allowed by the exception-specification of a function directly
230 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000231 // function it directly invokes allows all exceptions, and f shall allow no
232 // exceptions if every function it directly invokes allows no exceptions.
233 //
234 // Note in particular that if an implicit exception-specification is generated
235 // for a function containing a throw-expression, that specification can still
236 // be noexcept(true).
237 //
238 // Note also that 'directly invoked' is not defined in the standard, and there
239 // is no indication that we should only consider potentially-evaluated calls.
240 //
241 // Ultimately we should implement the intent of the standard: the exception
242 // specification should be the set of exceptions which can be thrown by the
243 // implicit definition. For now, we assume that any non-nothrow expression can
244 // throw any exception.
245
Richard Smithe6975e92012-04-17 00:58:00 +0000246 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000247 ComputedEST = EST_None;
248}
249
Anders Carlssoned961f92009-08-25 02:29:20 +0000250bool
John McCall9ae2f072010-08-23 23:25:46 +0000251Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000252 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000253 if (RequireCompleteType(Param->getLocation(), Param->getType(),
254 diag::err_typecheck_decl_incomplete_type)) {
255 Param->setInvalidDecl();
256 return true;
257 }
258
Anders Carlssoned961f92009-08-25 02:29:20 +0000259 // C++ [dcl.fct.default]p5
260 // A default argument expression is implicitly converted (clause
261 // 4) to the parameter type. The default argument expression has
262 // the same semantic constraints as the initializer expression in
263 // a declaration of a variable of the parameter type, using the
264 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000265 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
266 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000267 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
268 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000269 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000270 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000271 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000272 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000273 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000274
Richard Smith6c3af3d2013-01-17 01:17:56 +0000275 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000276 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Anders Carlssoned961f92009-08-25 02:29:20 +0000278 // Okay: add the default argument to the parameter
279 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000281 // We have already instantiated this parameter; provide each of the
282 // instantiations with the uninstantiated default argument.
283 UnparsedDefaultArgInstantiationsMap::iterator InstPos
284 = UnparsedDefaultArgInstantiations.find(Param);
285 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
286 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
287 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
288
289 // We're done tracking this parameter's instantiations.
290 UnparsedDefaultArgInstantiations.erase(InstPos);
291 }
292
Anders Carlsson9351c172009-08-25 03:18:48 +0000293 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000294}
295
Chris Lattner8123a952008-04-10 02:22:51 +0000296/// ActOnParamDefaultArgument - Check whether the default argument
297/// provided for a function parameter is well-formed. If so, attach it
298/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000299void
John McCalld226f652010-08-21 09:40:31 +0000300Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000301 Expr *DefaultArg) {
302 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000303 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000304
John McCalld226f652010-08-21 09:40:31 +0000305 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000306 UnparsedDefaultArgLocs.erase(Param);
307
Chris Lattner3d1cee32008-04-08 05:04:30 +0000308 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000309 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000310 Diag(EqualLoc, diag::err_param_default_argument)
311 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000312 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000313 return;
314 }
315
Douglas Gregor6f526752010-12-16 08:48:57 +0000316 // Check for unexpanded parameter packs.
317 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
318 Param->setInvalidDecl();
319 return;
320 }
321
Anders Carlsson66e30672009-08-25 01:02:06 +0000322 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000323 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
324 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000325 Param->setInvalidDecl();
326 return;
327 }
Mike Stump1eb44332009-09-09 15:08:12 +0000328
John McCall9ae2f072010-08-23 23:25:46 +0000329 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000330}
331
Douglas Gregor61366e92008-12-24 00:01:03 +0000332/// ActOnParamUnparsedDefaultArgument - We've seen a default
333/// argument for a function parameter, but we can't parse it yet
334/// because we're inside a class definition. Note that this default
335/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000336void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000337 SourceLocation EqualLoc,
338 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000339 if (!param)
340 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000341
John McCalld226f652010-08-21 09:40:31 +0000342 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000343 if (Param)
344 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Anders Carlsson5e300d12009-06-12 16:51:40 +0000346 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000347}
348
Douglas Gregor72b505b2008-12-16 21:30:33 +0000349/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
350/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000351void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000352 if (!param)
353 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000354
John McCalld226f652010-08-21 09:40:31 +0000355 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Anders Carlsson5e300d12009-06-12 16:51:40 +0000357 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Anders Carlsson5e300d12009-06-12 16:51:40 +0000359 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000360}
361
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000362/// CheckExtraCXXDefaultArguments - Check for any extra default
363/// arguments in the declarator, which is not a function declaration
364/// or definition and therefore is not permitted to have default
365/// arguments. This routine should be invoked for every declarator
366/// that is not a function declaration or definition.
367void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
368 // C++ [dcl.fct.default]p3
369 // A default argument expression shall be specified only in the
370 // parameter-declaration-clause of a function declaration or in a
371 // template-parameter (14.1). It shall not be specified for a
372 // parameter pack. If it is specified in a
373 // parameter-declaration-clause, it shall not occur within a
374 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000375 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000376 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000377 DeclaratorChunk &chunk = D.getTypeObject(i);
378 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000379 if (MightBeFunction) {
380 // This is a function declaration. It can have default arguments, but
381 // keep looking in case its return type is a function type with default
382 // arguments.
383 MightBeFunction = false;
384 continue;
385 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000386 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
387 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000388 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000389 if (Param->hasUnparsedDefaultArg()) {
390 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000391 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000392 << SourceRange((*Toks)[1].getLocation(),
393 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000394 delete Toks;
395 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000396 } else if (Param->getDefaultArg()) {
397 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
398 << Param->getDefaultArg()->getSourceRange();
399 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000400 }
401 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000402 } else if (chunk.Kind != DeclaratorChunk::Paren) {
403 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000404 }
405 }
406}
407
David Majnemerf6a144f2013-06-25 23:09:30 +0000408static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
409 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
410 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
411 if (!PVD->hasDefaultArg())
412 return false;
413 if (!PVD->hasInheritedDefaultArg())
414 return true;
415 }
416 return false;
417}
418
Craig Topper1a6eac82012-09-21 04:33:26 +0000419/// MergeCXXFunctionDecl - Merge two declarations of the same C++
420/// function, once we already know that they have the same
421/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
422/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000423bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
424 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000425 bool Invalid = false;
426
Chris Lattner3d1cee32008-04-08 05:04:30 +0000427 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000428 // For non-template functions, default arguments can be added in
429 // later declarations of a function in the same
430 // scope. Declarations in different scopes have completely
431 // distinct sets of default arguments. That is, declarations in
432 // inner scopes do not acquire default arguments from
433 // declarations in outer scopes, and vice versa. In a given
434 // function declaration, all parameters subsequent to a
435 // parameter with a default argument shall have default
436 // arguments supplied in this or previous declarations. A
437 // default argument shall not be redefined by a later
438 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000439 //
440 // C++ [dcl.fct.default]p6:
441 // Except for member functions of class templates, the default arguments
442 // in a member function definition that appears outside of the class
443 // definition are added to the set of default arguments provided by the
444 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000445 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
446 ParmVarDecl *OldParam = Old->getParamDecl(p);
447 ParmVarDecl *NewParam = New->getParamDecl(p);
448
James Molloy9cda03f2012-03-13 08:55:35 +0000449 bool OldParamHasDfl = OldParam->hasDefaultArg();
450 bool NewParamHasDfl = NewParam->hasDefaultArg();
451
452 NamedDecl *ND = Old;
453 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
454 // Ignore default parameters of old decl if they are not in
455 // the same scope.
456 OldParamHasDfl = false;
457
458 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000459
Francois Pichet8d051e02011-04-10 03:03:52 +0000460 unsigned DiagDefaultParamID =
461 diag::err_param_default_argument_redefinition;
462
463 // MSVC accepts that default parameters be redefined for member functions
464 // of template class. The new default parameter's value is ignored.
465 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000466 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000467 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
468 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000469 // Merge the old default argument into the new parameter.
470 NewParam->setHasInheritedDefaultArg();
471 if (OldParam->hasUninstantiatedDefaultArg())
472 NewParam->setUninstantiatedDefaultArg(
473 OldParam->getUninstantiatedDefaultArg());
474 else
475 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000476 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000477 Invalid = false;
478 }
479 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000480
Francois Pichet8cf90492011-04-10 04:58:30 +0000481 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
482 // hint here. Alternatively, we could walk the type-source information
483 // for NewParam to find the last source location in the type... but it
484 // isn't worth the effort right now. This is the kind of test case that
485 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000486 // int f(int);
487 // void g(int (*fp)(int) = f);
488 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000489 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000490 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000491
492 // Look for the function declaration where the default argument was
493 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000494 for (FunctionDecl *Older = Old->getPreviousDecl();
495 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000496 if (!Older->getParamDecl(p)->hasDefaultArg())
497 break;
498
499 OldParam = Older->getParamDecl(p);
500 }
501
502 Diag(OldParam->getLocation(), diag::note_previous_definition)
503 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000504 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000505 // Merge the old default argument into the new parameter.
506 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000507 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000508 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000509 if (OldParam->hasUninstantiatedDefaultArg())
510 NewParam->setUninstantiatedDefaultArg(
511 OldParam->getUninstantiatedDefaultArg());
512 else
John McCall3d6c1782010-05-04 01:53:42 +0000513 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000514 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000515 if (New->getDescribedFunctionTemplate()) {
516 // Paragraph 4, quoted above, only applies to non-template functions.
517 Diag(NewParam->getLocation(),
518 diag::err_param_default_argument_template_redecl)
519 << NewParam->getDefaultArgRange();
520 Diag(Old->getLocation(), diag::note_template_prev_declaration)
521 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000522 } else if (New->getTemplateSpecializationKind()
523 != TSK_ImplicitInstantiation &&
524 New->getTemplateSpecializationKind() != TSK_Undeclared) {
525 // C++ [temp.expr.spec]p21:
526 // Default function arguments shall not be specified in a declaration
527 // or a definition for one of the following explicit specializations:
528 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000529 // - the explicit specialization of a member function template;
530 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000531 // template where the class template specialization to which the
532 // member function specialization belongs is implicitly
533 // instantiated.
534 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
535 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
536 << New->getDeclName()
537 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000538 } else if (New->getDeclContext()->isDependentContext()) {
539 // C++ [dcl.fct.default]p6 (DR217):
540 // Default arguments for a member function of a class template shall
541 // be specified on the initial declaration of the member function
542 // within the class template.
543 //
544 // Reading the tea leaves a bit in DR217 and its reference to DR205
545 // leads me to the conclusion that one cannot add default function
546 // arguments for an out-of-line definition of a member function of a
547 // dependent type.
548 int WhichKind = 2;
549 if (CXXRecordDecl *Record
550 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
551 if (Record->getDescribedClassTemplate())
552 WhichKind = 0;
553 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
554 WhichKind = 1;
555 else
556 WhichKind = 2;
557 }
558
559 Diag(NewParam->getLocation(),
560 diag::err_param_default_argument_member_template_redecl)
561 << WhichKind
562 << NewParam->getDefaultArgRange();
563 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000564 }
565 }
566
Richard Smithb8abff62012-11-28 03:45:24 +0000567 // DR1344: If a default argument is added outside a class definition and that
568 // default argument makes the function a special member function, the program
569 // is ill-formed. This can only happen for constructors.
570 if (isa<CXXConstructorDecl>(New) &&
571 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
572 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
573 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
574 if (NewSM != OldSM) {
575 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
576 assert(NewParam->hasDefaultArg());
577 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
578 << NewParam->getDefaultArgRange() << NewSM;
579 Diag(Old->getLocation(), diag::note_previous_declaration);
580 }
581 }
582
Richard Smithff234882012-02-20 23:28:05 +0000583 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000584 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000585 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000586 if (New->isConstexpr() != Old->isConstexpr()) {
587 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
588 << New << New->isConstexpr();
589 Diag(Old->getLocation(), diag::note_previous_declaration);
590 Invalid = true;
591 }
592
David Majnemerf6a144f2013-06-25 23:09:30 +0000593 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumifd527a42013-07-17 17:57:52 +0000594 // argument expression, that declaration shall be a definition and shall be
David Majnemerf6a144f2013-06-25 23:09:30 +0000595 // the only declaration of the function or function template in the
596 // translation unit.
597 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
598 functionDeclHasDefaultArgument(Old)) {
599 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
600 Diag(Old->getLocation(), diag::note_previous_declaration);
601 Invalid = true;
602 }
603
Douglas Gregore13ad832010-02-12 07:32:17 +0000604 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000605 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000606
Douglas Gregorcda9c672009-02-16 17:45:42 +0000607 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000608}
609
Sebastian Redl60618fa2011-03-12 11:50:43 +0000610/// \brief Merge the exception specifications of two variable declarations.
611///
612/// This is called when there's a redeclaration of a VarDecl. The function
613/// checks if the redeclaration might have an exception specification and
614/// validates compatibility and merges the specs if necessary.
615void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
616 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000617 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000618 return;
619
620 assert(Context.hasSameType(New->getType(), Old->getType()) &&
621 "Should only be called if types are otherwise the same.");
622
623 QualType NewType = New->getType();
624 QualType OldType = Old->getType();
625
626 // We're only interested in pointers and references to functions, as well
627 // as pointers to member functions.
628 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
629 NewType = R->getPointeeType();
630 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
631 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
632 NewType = P->getPointeeType();
633 OldType = OldType->getAs<PointerType>()->getPointeeType();
634 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
635 NewType = M->getPointeeType();
636 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
637 }
638
639 if (!NewType->isFunctionProtoType())
640 return;
641
642 // There's lots of special cases for functions. For function pointers, system
643 // libraries are hopefully not as broken so that we don't need these
644 // workarounds.
645 if (CheckEquivalentExceptionSpec(
646 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
647 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
648 New->setInvalidDecl();
649 }
650}
651
Chris Lattner3d1cee32008-04-08 05:04:30 +0000652/// CheckCXXDefaultArguments - Verify that the default arguments for a
653/// function declaration are well-formed according to C++
654/// [dcl.fct.default].
655void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
656 unsigned NumParams = FD->getNumParams();
657 unsigned p;
658
659 // Find first parameter with a default argument
660 for (p = 0; p < NumParams; ++p) {
661 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000662 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000663 break;
664 }
665
666 // C++ [dcl.fct.default]p4:
667 // In a given function declaration, all parameters
668 // subsequent to a parameter with a default argument shall
669 // have default arguments supplied in this or previous
670 // declarations. A default argument shall not be redefined
671 // by a later declaration (not even to the same value).
672 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000673 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000674 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000675 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000676 if (Param->isInvalidDecl())
677 /* We already complained about this parameter. */;
678 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000679 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000680 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000681 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000682 else
Mike Stump1eb44332009-09-09 15:08:12 +0000683 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000684 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Chris Lattner3d1cee32008-04-08 05:04:30 +0000686 LastMissingDefaultArg = p;
687 }
688 }
689
690 if (LastMissingDefaultArg > 0) {
691 // Some default arguments were missing. Clear out all of the
692 // default arguments up to (and including) the last missing
693 // default argument, so that we leave the function parameters
694 // in a semantically valid state.
695 for (p = 0; p <= LastMissingDefaultArg; ++p) {
696 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000697 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000698 Param->setDefaultArg(0);
699 }
700 }
701 }
702}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000703
Richard Smith9f569cc2011-10-01 02:31:28 +0000704// CheckConstexprParameterTypes - Check whether a function's parameter types
705// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000706// diagnostic and return false.
707static bool CheckConstexprParameterTypes(Sema &SemaRef,
708 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000709 unsigned ArgIndex = 0;
710 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
711 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
712 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
713 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
714 SourceLocation ParamLoc = PD->getLocation();
715 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000716 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000717 diag::err_constexpr_non_literal_param,
718 ArgIndex+1, PD->getSourceRange(),
719 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000720 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000721 }
Joao Matos17d35c32012-08-31 22:18:20 +0000722 return true;
723}
724
725/// \brief Get diagnostic %select index for tag kind for
726/// record diagnostic message.
727/// WARNING: Indexes apply to particular diagnostics only!
728///
729/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000730static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000731 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000732 case TTK_Struct: return 0;
733 case TTK_Interface: return 1;
734 case TTK_Class: return 2;
735 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000736 }
Joao Matos17d35c32012-08-31 22:18:20 +0000737}
738
739// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
740// the requirements of a constexpr function definition or a constexpr
741// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000742// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000743//
Richard Smith86c3ae42012-02-13 03:54:03 +0000744// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
745bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000746 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
747 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000748 // C++11 [dcl.constexpr]p4:
749 // The definition of a constexpr constructor shall satisfy the following
750 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000751 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000752 const CXXRecordDecl *RD = MD->getParent();
753 if (RD->getNumVBases()) {
754 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
755 << isa<CXXConstructorDecl>(NewFD)
756 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
757 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
758 E = RD->vbases_end(); I != E; ++I)
759 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000760 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000761 return false;
762 }
Richard Smith35340502012-01-13 04:54:00 +0000763 }
764
765 if (!isa<CXXConstructorDecl>(NewFD)) {
766 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000767 // The definition of a constexpr function shall satisfy the following
768 // constraints:
769 // - it shall not be virtual;
770 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
771 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000772 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000773
Richard Smith86c3ae42012-02-13 03:54:03 +0000774 // If it's not obvious why this function is virtual, find an overridden
775 // function which uses the 'virtual' keyword.
776 const CXXMethodDecl *WrittenVirtual = Method;
777 while (!WrittenVirtual->isVirtualAsWritten())
778 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
779 if (WrittenVirtual != Method)
780 Diag(WrittenVirtual->getLocation(),
781 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000782 return false;
783 }
784
785 // - its return type shall be a literal type;
786 QualType RT = NewFD->getResultType();
787 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000788 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000789 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000790 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000791 }
792
Richard Smith35340502012-01-13 04:54:00 +0000793 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000794 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000795 return false;
796
Richard Smith9f569cc2011-10-01 02:31:28 +0000797 return true;
798}
799
800/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000801/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000802///
Richard Smitha10b9782013-04-22 15:31:51 +0000803/// \return true if the body is OK (maybe only as an extension), false if we
804/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000805static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000806 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
807 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000808 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
809 // contain only
810 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
811 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
812 switch ((*DclIt)->getKind()) {
813 case Decl::StaticAssert:
814 case Decl::Using:
815 case Decl::UsingShadow:
816 case Decl::UsingDirective:
817 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000818 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000819 // - static_assert-declarations
820 // - using-declarations,
821 // - using-directives,
822 continue;
823
824 case Decl::Typedef:
825 case Decl::TypeAlias: {
826 // - typedef declarations and alias-declarations that do not define
827 // classes or enumerations,
828 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
829 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
830 // Don't allow variably-modified types in constexpr functions.
831 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
832 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
833 << TL.getSourceRange() << TL.getType()
834 << isa<CXXConstructorDecl>(Dcl);
835 return false;
836 }
837 continue;
838 }
839
840 case Decl::Enum:
841 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000842 // C++1y allows types to be defined, not just declared.
843 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
844 SemaRef.Diag(DS->getLocStart(),
845 SemaRef.getLangOpts().CPlusPlus1y
846 ? diag::warn_cxx11_compat_constexpr_type_definition
847 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000848 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000849 continue;
850
Richard Smitha10b9782013-04-22 15:31:51 +0000851 case Decl::EnumConstant:
852 case Decl::IndirectField:
853 case Decl::ParmVar:
854 // These can only appear with other declarations which are banned in
855 // C++11 and permitted in C++1y, so ignore them.
856 continue;
857
858 case Decl::Var: {
859 // C++1y [dcl.constexpr]p3 allows anything except:
860 // a definition of a variable of non-literal type or of static or
861 // thread storage duration or for which no initialization is performed.
862 VarDecl *VD = cast<VarDecl>(*DclIt);
863 if (VD->isThisDeclarationADefinition()) {
864 if (VD->isStaticLocal()) {
865 SemaRef.Diag(VD->getLocation(),
866 diag::err_constexpr_local_var_static)
867 << isa<CXXConstructorDecl>(Dcl)
868 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
869 return false;
870 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000871 if (!VD->getType()->isDependentType() &&
872 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000873 VD->getLocation(), VD->getType(),
874 diag::err_constexpr_local_var_non_literal_type,
875 isa<CXXConstructorDecl>(Dcl)))
876 return false;
877 if (!VD->hasInit()) {
878 SemaRef.Diag(VD->getLocation(),
879 diag::err_constexpr_local_var_no_init)
880 << isa<CXXConstructorDecl>(Dcl);
881 return false;
882 }
883 }
884 SemaRef.Diag(VD->getLocation(),
885 SemaRef.getLangOpts().CPlusPlus1y
886 ? diag::warn_cxx11_compat_constexpr_local_var
887 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000888 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000889 continue;
890 }
891
892 case Decl::NamespaceAlias:
893 case Decl::Function:
894 // These are disallowed in C++11 and permitted in C++1y. Allow them
895 // everywhere as an extension.
896 if (!Cxx1yLoc.isValid())
897 Cxx1yLoc = DS->getLocStart();
898 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000899
900 default:
901 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
902 << isa<CXXConstructorDecl>(Dcl);
903 return false;
904 }
905 }
906
907 return true;
908}
909
910/// Check that the given field is initialized within a constexpr constructor.
911///
912/// \param Dcl The constexpr constructor being checked.
913/// \param Field The field being checked. This may be a member of an anonymous
914/// struct or union nested within the class being checked.
915/// \param Inits All declarations, including anonymous struct/union members and
916/// indirect members, for which any initialization was provided.
917/// \param Diagnosed Set to true if an error is produced.
918static void CheckConstexprCtorInitializer(Sema &SemaRef,
919 const FunctionDecl *Dcl,
920 FieldDecl *Field,
921 llvm::SmallSet<Decl*, 16> &Inits,
922 bool &Diagnosed) {
Eli Friedman5fb478b2013-06-28 21:07:41 +0000923 if (Field->isInvalidDecl())
924 return;
925
Douglas Gregord61db332011-10-10 17:22:13 +0000926 if (Field->isUnnamedBitfield())
927 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000928
929 if (Field->isAnonymousStructOrUnion() &&
930 Field->getType()->getAsCXXRecordDecl()->isEmpty())
931 return;
932
Richard Smith9f569cc2011-10-01 02:31:28 +0000933 if (!Inits.count(Field)) {
934 if (!Diagnosed) {
935 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
936 Diagnosed = true;
937 }
938 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
939 } else if (Field->isAnonymousStructOrUnion()) {
940 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
941 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
942 I != E; ++I)
943 // If an anonymous union contains an anonymous struct of which any member
944 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000945 if (!RD->isUnion() || Inits.count(*I))
946 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000947 }
948}
949
Richard Smitha10b9782013-04-22 15:31:51 +0000950/// Check the provided statement is allowed in a constexpr function
951/// definition.
952static bool
953CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelme7205c02013-08-10 12:33:24 +0000954 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smitha10b9782013-04-22 15:31:51 +0000955 SourceLocation &Cxx1yLoc) {
956 // - its function-body shall be [...] a compound-statement that contains only
957 switch (S->getStmtClass()) {
958 case Stmt::NullStmtClass:
959 // - null statements,
960 return true;
961
962 case Stmt::DeclStmtClass:
963 // - static_assert-declarations
964 // - using-declarations,
965 // - using-directives,
966 // - typedef declarations and alias-declarations that do not define
967 // classes or enumerations,
968 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
969 return false;
970 return true;
971
972 case Stmt::ReturnStmtClass:
973 // - and exactly one return statement;
974 if (isa<CXXConstructorDecl>(Dcl)) {
975 // C++1y allows return statements in constexpr constructors.
976 if (!Cxx1yLoc.isValid())
977 Cxx1yLoc = S->getLocStart();
978 return true;
979 }
980
981 ReturnStmts.push_back(S->getLocStart());
982 return true;
983
984 case Stmt::CompoundStmtClass: {
985 // C++1y allows compound-statements.
986 if (!Cxx1yLoc.isValid())
987 Cxx1yLoc = S->getLocStart();
988
989 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
990 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
991 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
992 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
993 Cxx1yLoc))
994 return false;
995 }
996 return true;
997 }
998
999 case Stmt::AttributedStmtClass:
1000 if (!Cxx1yLoc.isValid())
1001 Cxx1yLoc = S->getLocStart();
1002 return true;
1003
1004 case Stmt::IfStmtClass: {
1005 // C++1y allows if-statements.
1006 if (!Cxx1yLoc.isValid())
1007 Cxx1yLoc = S->getLocStart();
1008
1009 IfStmt *If = cast<IfStmt>(S);
1010 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1011 Cxx1yLoc))
1012 return false;
1013 if (If->getElse() &&
1014 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1015 Cxx1yLoc))
1016 return false;
1017 return true;
1018 }
1019
1020 case Stmt::WhileStmtClass:
1021 case Stmt::DoStmtClass:
1022 case Stmt::ForStmtClass:
1023 case Stmt::CXXForRangeStmtClass:
1024 case Stmt::ContinueStmtClass:
1025 // C++1y allows all of these. We don't allow them as extensions in C++11,
1026 // because they don't make sense without variable mutation.
1027 if (!SemaRef.getLangOpts().CPlusPlus1y)
1028 break;
1029 if (!Cxx1yLoc.isValid())
1030 Cxx1yLoc = S->getLocStart();
1031 for (Stmt::child_range Children = S->children(); Children; ++Children)
1032 if (*Children &&
1033 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1034 Cxx1yLoc))
1035 return false;
1036 return true;
1037
1038 case Stmt::SwitchStmtClass:
1039 case Stmt::CaseStmtClass:
1040 case Stmt::DefaultStmtClass:
1041 case Stmt::BreakStmtClass:
1042 // C++1y allows switch-statements, and since they don't need variable
1043 // mutation, we can reasonably allow them in C++11 as an extension.
1044 if (!Cxx1yLoc.isValid())
1045 Cxx1yLoc = S->getLocStart();
1046 for (Stmt::child_range Children = S->children(); Children; ++Children)
1047 if (*Children &&
1048 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1049 Cxx1yLoc))
1050 return false;
1051 return true;
1052
1053 default:
1054 if (!isa<Expr>(S))
1055 break;
1056
1057 // C++1y allows expression-statements.
1058 if (!Cxx1yLoc.isValid())
1059 Cxx1yLoc = S->getLocStart();
1060 return true;
1061 }
1062
1063 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1064 << isa<CXXConstructorDecl>(Dcl);
1065 return false;
1066}
1067
Richard Smith9f569cc2011-10-01 02:31:28 +00001068/// Check the body for the given constexpr function declaration only contains
1069/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1070///
1071/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001072bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001073 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001074 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001075 // The definition of a constexpr function shall satisfy the following
1076 // constraints: [...]
1077 // - its function-body shall be = delete, = default, or a
1078 // compound-statement
1079 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001080 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001081 // In the definition of a constexpr constructor, [...]
1082 // - its function-body shall not be a function-try-block;
1083 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1084 << isa<CXXConstructorDecl>(Dcl);
1085 return false;
1086 }
1087
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001088 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001089
1090 // - its function-body shall be [...] a compound-statement that contains only
1091 // [... list of cases ...]
1092 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1093 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001094 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1095 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001096 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1097 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001098 }
1099
Richard Smitha10b9782013-04-22 15:31:51 +00001100 if (Cxx1yLoc.isValid())
1101 Diag(Cxx1yLoc,
1102 getLangOpts().CPlusPlus1y
1103 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1104 : diag::ext_constexpr_body_invalid_stmt)
1105 << isa<CXXConstructorDecl>(Dcl);
1106
Richard Smith9f569cc2011-10-01 02:31:28 +00001107 if (const CXXConstructorDecl *Constructor
1108 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1109 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001110 // DR1359:
1111 // - every non-variant non-static data member and base class sub-object
1112 // shall be initialized;
1113 // - if the class is a non-empty union, or for each non-empty anonymous
1114 // union member of a non-union class, exactly one non-static data member
1115 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001116 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001117 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001118 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1119 return false;
1120 }
Richard Smith6e433752011-10-10 16:38:04 +00001121 } else if (!Constructor->isDependentContext() &&
1122 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001123 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1124
1125 // Skip detailed checking if we have enough initializers, and we would
1126 // allow at most one initializer per member.
1127 bool AnyAnonStructUnionMembers = false;
1128 unsigned Fields = 0;
1129 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1130 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001131 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001132 AnyAnonStructUnionMembers = true;
1133 break;
1134 }
1135 }
1136 if (AnyAnonStructUnionMembers ||
1137 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1138 // Check initialization of non-static data members. Base classes are
1139 // always initialized so do not need to be checked. Dependent bases
1140 // might not have initializers in the member initializer list.
1141 llvm::SmallSet<Decl*, 16> Inits;
1142 for (CXXConstructorDecl::init_const_iterator
1143 I = Constructor->init_begin(), E = Constructor->init_end();
1144 I != E; ++I) {
1145 if (FieldDecl *FD = (*I)->getMember())
1146 Inits.insert(FD);
1147 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1148 Inits.insert(ID->chain_begin(), ID->chain_end());
1149 }
1150
1151 bool Diagnosed = false;
1152 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1153 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001154 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001155 if (Diagnosed)
1156 return false;
1157 }
1158 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001159 } else {
1160 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001161 // C++1y doesn't require constexpr functions to contain a 'return'
1162 // statement. We still do, unless the return type is void, because
1163 // otherwise if there's no return statement, the function cannot
1164 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001165 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001166 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001167 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1168 : diag::err_constexpr_body_no_return);
1169 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001170 }
1171 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001172 Diag(ReturnStmts.back(),
1173 getLangOpts().CPlusPlus1y
1174 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1175 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001176 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1177 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001178 }
1179 }
1180
Richard Smith5ba73e12012-02-04 00:33:54 +00001181 // C++11 [dcl.constexpr]p5:
1182 // if no function argument values exist such that the function invocation
1183 // substitution would produce a constant expression, the program is
1184 // ill-formed; no diagnostic required.
1185 // C++11 [dcl.constexpr]p3:
1186 // - every constructor call and implicit conversion used in initializing the
1187 // return value shall be one of those allowed in a constant expression.
1188 // C++11 [dcl.constexpr]p4:
1189 // - every constructor involved in initializing non-static data members and
1190 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001191 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001192 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001193 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001194 << isa<CXXConstructorDecl>(Dcl);
1195 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1196 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001197 // Don't return false here: we allow this for compatibility in
1198 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001199 }
1200
Richard Smith9f569cc2011-10-01 02:31:28 +00001201 return true;
1202}
1203
Douglas Gregorb48fe382008-10-31 09:07:45 +00001204/// isCurrentClassName - Determine whether the identifier II is the
1205/// name of the class type currently being defined. In the case of
1206/// nested classes, this will only return true if II is the name of
1207/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001208bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1209 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001210 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001211
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001212 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001213 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001214 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001215 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1216 } else
1217 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1218
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001219 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001220 return &II == CurDecl->getIdentifier();
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00001221 return false;
Douglas Gregorb48fe382008-10-31 09:07:45 +00001222}
1223
Douglas Gregor229d47a2012-11-10 07:24:09 +00001224/// \brief Determine whether the given class is a base class of the given
1225/// class, including looking at dependent bases.
1226static bool findCircularInheritance(const CXXRecordDecl *Class,
1227 const CXXRecordDecl *Current) {
1228 SmallVector<const CXXRecordDecl*, 8> Queue;
1229
1230 Class = Class->getCanonicalDecl();
1231 while (true) {
1232 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1233 E = Current->bases_end();
1234 I != E; ++I) {
1235 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1236 if (!Base)
1237 continue;
1238
1239 Base = Base->getDefinition();
1240 if (!Base)
1241 continue;
1242
1243 if (Base->getCanonicalDecl() == Class)
1244 return true;
1245
1246 Queue.push_back(Base);
1247 }
1248
1249 if (Queue.empty())
1250 return false;
1251
Robert Wilhelm344472e2013-08-23 16:11:15 +00001252 Current = Queue.pop_back_val();
Douglas Gregor229d47a2012-11-10 07:24:09 +00001253 }
1254
1255 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001256}
1257
Mike Stump1eb44332009-09-09 15:08:12 +00001258/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001259///
1260/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1261/// and returns NULL otherwise.
1262CXXBaseSpecifier *
1263Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1264 SourceRange SpecifierRange,
1265 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001266 TypeSourceInfo *TInfo,
1267 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001268 QualType BaseType = TInfo->getType();
1269
Douglas Gregor2943aed2009-03-03 04:44:36 +00001270 // C++ [class.union]p1:
1271 // A union shall not have base classes.
1272 if (Class->isUnion()) {
1273 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1274 << SpecifierRange;
1275 return 0;
1276 }
1277
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001278 if (EllipsisLoc.isValid() &&
1279 !TInfo->getType()->containsUnexpandedParameterPack()) {
1280 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1281 << TInfo->getTypeLoc().getSourceRange();
1282 EllipsisLoc = SourceLocation();
1283 }
Douglas Gregord777e282012-11-10 01:18:17 +00001284
1285 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1286
1287 if (BaseType->isDependentType()) {
1288 // Make sure that we don't have circular inheritance among our dependent
1289 // bases. For non-dependent bases, the check for completeness below handles
1290 // this.
1291 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1292 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1293 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001294 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001295 Diag(BaseLoc, diag::err_circular_inheritance)
1296 << BaseType << Context.getTypeDeclType(Class);
1297
1298 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1299 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1300 << BaseType;
1301
1302 return 0;
1303 }
1304 }
1305
Mike Stump1eb44332009-09-09 15:08:12 +00001306 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001307 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001308 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001309 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001310
1311 // Base specifiers must be record types.
1312 if (!BaseType->isRecordType()) {
1313 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1314 return 0;
1315 }
1316
1317 // C++ [class.union]p1:
1318 // A union shall not be used as a base class.
1319 if (BaseType->isUnionType()) {
1320 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1321 return 0;
1322 }
1323
1324 // C++ [class.derived]p2:
1325 // The class-name in a base-specifier shall not be an incompletely
1326 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001327 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001328 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001329 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001330 return 0;
John McCall572fc622010-08-17 07:23:57 +00001331 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001332
Eli Friedman1d954f62009-08-15 21:55:26 +00001333 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001334 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001335 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001336 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001337 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer2f686692013-06-22 06:43:58 +00001338 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001339 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001340
Anders Carlsson1d209272011-03-25 14:55:14 +00001341 // C++ [class]p3:
1342 // If a class is marked final and it appears as a base-type-specifier in
1343 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001344 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001345 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1346 << CXXBaseDecl->getDeclName();
1347 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1348 << CXXBaseDecl->getDeclName();
1349 return 0;
1350 }
1351
John McCall572fc622010-08-17 07:23:57 +00001352 if (BaseDecl->isInvalidDecl())
1353 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001354
1355 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001356 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001357 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001358 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001359}
1360
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001361/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1362/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001363/// example:
1364/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001365/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001366BaseResult
John McCalld226f652010-08-21 09:40:31 +00001367Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001368 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001369 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001370 ParsedType basetype, SourceLocation BaseLoc,
1371 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001372 if (!classdecl)
1373 return true;
1374
Douglas Gregor40808ce2009-03-09 23:48:35 +00001375 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001376 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001377 if (!Class)
1378 return true;
1379
Richard Smith05321402013-02-19 23:47:15 +00001380 // We do not support any C++11 attributes on base-specifiers yet.
1381 // Diagnose any attributes we see.
1382 if (!Attributes.empty()) {
1383 for (AttributeList *Attr = Attributes.getList(); Attr;
1384 Attr = Attr->getNext()) {
1385 if (Attr->isInvalid() ||
1386 Attr->getKind() == AttributeList::IgnoredAttribute)
1387 continue;
1388 Diag(Attr->getLoc(),
1389 Attr->getKind() == AttributeList::UnknownAttribute
1390 ? diag::warn_unknown_attribute_ignored
1391 : diag::err_base_specifier_attribute)
1392 << Attr->getName();
1393 }
1394 }
1395
Nick Lewycky56062202010-07-26 16:56:01 +00001396 TypeSourceInfo *TInfo = 0;
1397 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001398
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001399 if (EllipsisLoc.isInvalid() &&
1400 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001401 UPPC_BaseType))
1402 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001403
Douglas Gregor2943aed2009-03-03 04:44:36 +00001404 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001405 Virtual, Access, TInfo,
1406 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001407 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001408 else
1409 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Douglas Gregor2943aed2009-03-03 04:44:36 +00001411 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001412}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001413
Douglas Gregor2943aed2009-03-03 04:44:36 +00001414/// \brief Performs the actual work of attaching the given base class
1415/// specifiers to a C++ class.
1416bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1417 unsigned NumBases) {
1418 if (NumBases == 0)
1419 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001420
1421 // Used to keep track of which base types we have already seen, so
1422 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001423 // that the key is always the unqualified canonical type of the base
1424 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001425 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1426
1427 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001428 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001429 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001430 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001431 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001432 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001433 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001434
1435 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1436 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001437 // C++ [class.mi]p3:
1438 // A class shall not be specified as a direct base class of a
1439 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001440 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001441 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001442 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001443 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001444
1445 // Delete the duplicate base class specifier; we're going to
1446 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001447 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001448
1449 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001450 } else {
1451 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001452 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001453 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001454 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1455 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1456 if (Class->isInterface() &&
1457 (!RD->isInterface() ||
1458 KnownBase->getAccessSpecifier() != AS_public)) {
1459 // The Microsoft extension __interface does not permit bases that
1460 // are not themselves public interfaces.
1461 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1462 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1463 << RD->getSourceRange();
1464 Invalid = true;
1465 }
1466 if (RD->hasAttr<WeakAttr>())
1467 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1468 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001469 }
1470 }
1471
1472 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001473 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001474
1475 // Delete the remaining (good) base class specifiers, since their
1476 // data has been copied into the CXXRecordDecl.
1477 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001478 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001479
1480 return Invalid;
1481}
1482
1483/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1484/// class, after checking whether there are any duplicate base
1485/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001486void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001487 unsigned NumBases) {
1488 if (!ClassDecl || !Bases || !NumBases)
1489 return;
1490
1491 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelm0d317a02013-07-22 05:04:01 +00001492 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001493}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001494
Douglas Gregora8f32e02009-10-06 17:59:45 +00001495/// \brief Determine whether the type \p Derived is a C++ class that is
1496/// derived from the type \p Base.
1497bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001498 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001499 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001500
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001501 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001502 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001503 return false;
1504
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001505 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001506 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001507 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001508
1509 // If either the base or the derived type is invalid, don't try to
1510 // check whether one is derived from the other.
1511 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1512 return false;
1513
John McCall86ff3082010-02-04 22:26:26 +00001514 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1515 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001516}
1517
1518/// \brief Determine whether the type \p Derived is a C++ class that is
1519/// derived from the type \p Base.
1520bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001521 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001522 return false;
1523
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001524 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001525 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001526 return false;
1527
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001528 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001529 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001530 return false;
1531
Douglas Gregora8f32e02009-10-06 17:59:45 +00001532 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1533}
1534
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001535void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001536 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001537 assert(BasePathArray.empty() && "Base path array must be empty!");
1538 assert(Paths.isRecordingPaths() && "Must record paths!");
1539
1540 const CXXBasePath &Path = Paths.front();
1541
1542 // We first go backward and check if we have a virtual base.
1543 // FIXME: It would be better if CXXBasePath had the base specifier for
1544 // the nearest virtual base.
1545 unsigned Start = 0;
1546 for (unsigned I = Path.size(); I != 0; --I) {
1547 if (Path[I - 1].Base->isVirtual()) {
1548 Start = I - 1;
1549 break;
1550 }
1551 }
1552
1553 // Now add all bases.
1554 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001555 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001556}
1557
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001558/// \brief Determine whether the given base path includes a virtual
1559/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001560bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1561 for (CXXCastPath::const_iterator B = BasePath.begin(),
1562 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001563 B != BEnd; ++B)
1564 if ((*B)->isVirtual())
1565 return true;
1566
1567 return false;
1568}
1569
Douglas Gregora8f32e02009-10-06 17:59:45 +00001570/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1571/// conversion (where Derived and Base are class types) is
1572/// well-formed, meaning that the conversion is unambiguous (and
1573/// that all of the base classes are accessible). Returns true
1574/// and emits a diagnostic if the code is ill-formed, returns false
1575/// otherwise. Loc is the location where this routine should point to
1576/// if there is an error, and Range is the source range to highlight
1577/// if there is an error.
1578bool
1579Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001580 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001581 unsigned AmbigiousBaseConvID,
1582 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001583 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001584 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001585 // First, determine whether the path from Derived to Base is
1586 // ambiguous. This is slightly more expensive than checking whether
1587 // the Derived to Base conversion exists, because here we need to
1588 // explore multiple paths to determine if there is an ambiguity.
1589 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1590 /*DetectVirtual=*/false);
1591 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1592 assert(DerivationOkay &&
1593 "Can only be used with a derived-to-base conversion");
1594 (void)DerivationOkay;
1595
1596 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001597 if (InaccessibleBaseID) {
1598 // Check that the base class can be accessed.
1599 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1600 InaccessibleBaseID)) {
1601 case AR_inaccessible:
1602 return true;
1603 case AR_accessible:
1604 case AR_dependent:
1605 case AR_delayed:
1606 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001607 }
John McCall6b2accb2010-02-10 09:31:12 +00001608 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001609
1610 // Build a base path if necessary.
1611 if (BasePath)
1612 BuildBasePathArray(Paths, *BasePath);
1613 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001614 }
1615
David Majnemer2f686692013-06-22 06:43:58 +00001616 if (AmbigiousBaseConvID) {
1617 // We know that the derived-to-base conversion is ambiguous, and
1618 // we're going to produce a diagnostic. Perform the derived-to-base
1619 // search just one more time to compute all of the possible paths so
1620 // that we can print them out. This is more expensive than any of
1621 // the previous derived-to-base checks we've done, but at this point
1622 // performance isn't as much of an issue.
1623 Paths.clear();
1624 Paths.setRecordingPaths(true);
1625 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1626 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1627 (void)StillOkay;
1628
1629 // Build up a textual representation of the ambiguous paths, e.g.,
1630 // D -> B -> A, that will be used to illustrate the ambiguous
1631 // conversions in the diagnostic. We only print one of the paths
1632 // to each base class subobject.
1633 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1634
1635 Diag(Loc, AmbigiousBaseConvID)
1636 << Derived << Base << PathDisplayStr << Range << Name;
1637 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001638 return true;
1639}
1640
1641bool
1642Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001643 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001644 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001645 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001646 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001647 IgnoreAccess ? 0
1648 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001649 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001650 Loc, Range, DeclarationName(),
1651 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001652}
1653
1654
1655/// @brief Builds a string representing ambiguous paths from a
1656/// specific derived class to different subobjects of the same base
1657/// class.
1658///
1659/// This function builds a string that can be used in error messages
1660/// to show the different paths that one can take through the
1661/// inheritance hierarchy to go from the derived class to different
1662/// subobjects of a base class. The result looks something like this:
1663/// @code
1664/// struct D -> struct B -> struct A
1665/// struct D -> struct C -> struct A
1666/// @endcode
1667std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1668 std::string PathDisplayStr;
1669 std::set<unsigned> DisplayedPaths;
1670 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1671 Path != Paths.end(); ++Path) {
1672 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1673 // We haven't displayed a path to this particular base
1674 // class subobject yet.
1675 PathDisplayStr += "\n ";
1676 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1677 for (CXXBasePath::const_iterator Element = Path->begin();
1678 Element != Path->end(); ++Element)
1679 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1680 }
1681 }
1682
1683 return PathDisplayStr;
1684}
1685
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001686//===----------------------------------------------------------------------===//
1687// C++ class member Handling
1688//===----------------------------------------------------------------------===//
1689
Abramo Bagnara6206d532010-06-05 05:09:32 +00001690/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001691bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1692 SourceLocation ASLoc,
1693 SourceLocation ColonLoc,
1694 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001695 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001696 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001697 ASLoc, ColonLoc);
1698 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001699 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001700}
1701
Richard Smitha4b39652012-08-06 03:25:17 +00001702/// CheckOverrideControl - Check C++11 override control semantics.
1703void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001704 if (D->isInvalidDecl())
1705 return;
1706
Chris Lattner5f9e2722011-07-23 10:55:15 +00001707 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001708
Richard Smitha4b39652012-08-06 03:25:17 +00001709 // Do we know which functions this declaration might be overriding?
1710 bool OverridesAreKnown = !MD ||
1711 (!MD->getParent()->hasAnyDependentBases() &&
1712 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001713
Richard Smitha4b39652012-08-06 03:25:17 +00001714 if (!MD || !MD->isVirtual()) {
1715 if (OverridesAreKnown) {
1716 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1717 Diag(OA->getLocation(),
1718 diag::override_keyword_only_allowed_on_virtual_member_functions)
1719 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1720 D->dropAttr<OverrideAttr>();
1721 }
1722 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1723 Diag(FA->getLocation(),
1724 diag::override_keyword_only_allowed_on_virtual_member_functions)
1725 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1726 D->dropAttr<FinalAttr>();
1727 }
1728 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001729 return;
1730 }
Richard Smitha4b39652012-08-06 03:25:17 +00001731
1732 if (!OverridesAreKnown)
1733 return;
1734
1735 // C++11 [class.virtual]p5:
1736 // If a virtual function is marked with the virt-specifier override and
1737 // does not override a member function of a base class, the program is
1738 // ill-formed.
1739 bool HasOverriddenMethods =
1740 MD->begin_overridden_methods() != MD->end_overridden_methods();
1741 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1742 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1743 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001744}
1745
Richard Smitha4b39652012-08-06 03:25:17 +00001746/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001747/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001748/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001749bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1750 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001751 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001752 return false;
1753
1754 Diag(New->getLocation(), diag::err_final_function_overridden)
1755 << New->getDeclName();
1756 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1757 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001758}
1759
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001760static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001761 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1762 // FIXME: Destruction of ObjC lifetime types has side-effects.
1763 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1764 return !RD->isCompleteDefinition() ||
1765 !RD->hasTrivialDefaultConstructor() ||
1766 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001767 return false;
1768}
1769
John McCall76da55d2013-04-16 07:28:30 +00001770static AttributeList *getMSPropertyAttr(AttributeList *list) {
1771 for (AttributeList* it = list; it != 0; it = it->getNext())
1772 if (it->isDeclspecPropertyAttribute())
1773 return it;
1774 return 0;
1775}
1776
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001777/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1778/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001779/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001780/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1781/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001782NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001783Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001784 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001785 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001786 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001787 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001788 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1789 DeclarationName Name = NameInfo.getName();
1790 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001791
1792 // For anonymous bitfields, the location should point to the type.
1793 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001794 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001795
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001796 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001797
John McCall4bde1e12010-06-04 08:34:12 +00001798 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001799 assert(!DS.isFriendSpecified());
1800
Richard Smith1ab0d902011-06-25 02:28:38 +00001801 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001802
John McCalle402e722012-09-25 07:32:39 +00001803 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1804 // The Microsoft extension __interface only permits public member functions
1805 // and prohibits constructors, destructors, operators, non-public member
1806 // functions, static methods and data members.
1807 unsigned InvalidDecl;
1808 bool ShowDeclName = true;
1809 if (!isFunc)
1810 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1811 else if (AS != AS_public)
1812 InvalidDecl = 2;
1813 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1814 InvalidDecl = 3;
1815 else switch (Name.getNameKind()) {
1816 case DeclarationName::CXXConstructorName:
1817 InvalidDecl = 4;
1818 ShowDeclName = false;
1819 break;
1820
1821 case DeclarationName::CXXDestructorName:
1822 InvalidDecl = 5;
1823 ShowDeclName = false;
1824 break;
1825
1826 case DeclarationName::CXXOperatorName:
1827 case DeclarationName::CXXConversionFunctionName:
1828 InvalidDecl = 6;
1829 break;
1830
1831 default:
1832 InvalidDecl = 0;
1833 break;
1834 }
1835
1836 if (InvalidDecl) {
1837 if (ShowDeclName)
1838 Diag(Loc, diag::err_invalid_member_in_interface)
1839 << (InvalidDecl-1) << Name;
1840 else
1841 Diag(Loc, diag::err_invalid_member_in_interface)
1842 << (InvalidDecl-1) << "";
1843 return 0;
1844 }
1845 }
1846
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001847 // C++ 9.2p6: A member shall not be declared to have automatic storage
1848 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001849 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1850 // data members and cannot be applied to names declared const or static,
1851 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001852 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001853 case DeclSpec::SCS_unspecified:
1854 case DeclSpec::SCS_typedef:
1855 case DeclSpec::SCS_static:
1856 break;
1857 case DeclSpec::SCS_mutable:
1858 if (isFunc) {
1859 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Richard Smithec642442013-04-12 22:46:28 +00001861 // FIXME: It would be nicer if the keyword was ignored only for this
1862 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001863 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001864 }
1865 break;
1866 default:
1867 Diag(DS.getStorageClassSpecLoc(),
1868 diag::err_storageclass_invalid_for_member);
1869 D.getMutableDeclSpec().ClearStorageClassSpecs();
1870 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001871 }
1872
Sebastian Redl669d5d72008-11-14 23:42:31 +00001873 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1874 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001875 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001876
David Blaikie1d87fba2013-01-30 01:22:18 +00001877 if (DS.isConstexprSpecified() && isInstField) {
1878 SemaDiagnosticBuilder B =
1879 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1880 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1881 if (InitStyle == ICIS_NoInit) {
1882 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1883 D.getMutableDeclSpec().ClearConstexprSpec();
1884 const char *PrevSpec;
1885 unsigned DiagID;
1886 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1887 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001888 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001889 assert(!Failed && "Making a constexpr member const shouldn't fail");
1890 } else {
1891 B << 1;
1892 const char *PrevSpec;
1893 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001894 if (D.getMutableDeclSpec().SetStorageClassSpec(
1895 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001896 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001897 "This is the only DeclSpec that should fail to be applied");
1898 B << 1;
1899 } else {
1900 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1901 isInstField = false;
1902 }
1903 }
1904 }
1905
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001906 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001907 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001908 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001909
1910 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001911 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001912 Diag(Loc, diag::err_bad_variable_name)
1913 << Name;
1914 return 0;
1915 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001916
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001917 IdentifierInfo *II = Name.getAsIdentifierInfo();
1918
Douglas Gregorf2503652011-09-21 14:40:46 +00001919 // Member field could not be with "template" keyword.
1920 // So TemplateParameterLists should be empty in this case.
1921 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001922 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001923 if (TemplateParams->size()) {
1924 // There is no such thing as a member field template.
1925 Diag(D.getIdentifierLoc(), diag::err_template_member)
1926 << II
1927 << SourceRange(TemplateParams->getTemplateLoc(),
1928 TemplateParams->getRAngleLoc());
1929 } else {
1930 // There is an extraneous 'template<>' for this member.
1931 Diag(TemplateParams->getTemplateLoc(),
1932 diag::err_template_member_noparams)
1933 << II
1934 << SourceRange(TemplateParams->getTemplateLoc(),
1935 TemplateParams->getRAngleLoc());
1936 }
1937 return 0;
1938 }
1939
Douglas Gregor922fff22010-10-13 22:19:53 +00001940 if (SS.isSet() && !SS.isInvalid()) {
1941 // The user provided a superfluous scope specifier inside a class
1942 // definition:
1943 //
1944 // class X {
1945 // int X::member;
1946 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001947 if (DeclContext *DC = computeDeclContext(SS, false))
1948 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001949 else
1950 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1951 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001952
Douglas Gregor922fff22010-10-13 22:19:53 +00001953 SS.clear();
1954 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001955
John McCall76da55d2013-04-16 07:28:30 +00001956 AttributeList *MSPropertyAttr =
1957 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanb26f0122013-06-28 20:48:34 +00001958 if (MSPropertyAttr) {
1959 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1960 BitWidth, InitStyle, AS, MSPropertyAttr);
1961 if (!Member)
1962 return 0;
1963 isInstField = false;
1964 } else {
1965 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1966 BitWidth, InitStyle, AS);
1967 assert(Member && "HandleField never returns null");
1968 }
1969 } else {
1970 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
1971
1972 Member = HandleDeclarator(S, D, TemplateParameterLists);
1973 if (!Member)
1974 return 0;
1975
1976 // Non-instance-fields can't have a bitfield.
1977 if (BitWidth) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001978 if (Member->isInvalidDecl()) {
1979 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001980 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001981 // C++ 9.6p3: A bit-field shall not be a static member.
1982 // "static member 'A' cannot be a bit-field"
1983 Diag(Loc, diag::err_static_not_bitfield)
1984 << Name << BitWidth->getSourceRange();
1985 } else if (isa<TypedefDecl>(Member)) {
1986 // "typedef member 'x' cannot be a bit-field"
1987 Diag(Loc, diag::err_typedef_not_bitfield)
1988 << Name << BitWidth->getSourceRange();
1989 } else {
1990 // A function typedef ("typedef int f(); f a;").
1991 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1992 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001993 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001994 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001995 }
Mike Stump1eb44332009-09-09 15:08:12 +00001996
Chris Lattner8b963ef2009-03-05 23:01:03 +00001997 BitWidth = 0;
1998 Member->setInvalidDecl();
1999 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00002000
2001 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Larisse Voufoef4579c2013-08-06 01:03:05 +00002003 // If we have declared a member function template or static data member
2004 // template, set the access of the templated declaration as well.
Douglas Gregor37b372b2009-08-20 22:52:58 +00002005 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2006 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002007 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2008 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00002009 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002010
Richard Smitha4b39652012-08-06 03:25:17 +00002011 if (VS.isOverrideSpecified())
2012 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2013 if (VS.isFinalSpecified())
2014 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00002015
Douglas Gregorf5251602011-03-08 17:10:18 +00002016 if (VS.getLastLocation().isValid()) {
2017 // Update the end location of a method that has a virt-specifiers.
2018 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2019 MD->setRangeEnd(VS.getLastLocation());
2020 }
Richard Smitha4b39652012-08-06 03:25:17 +00002021
Anders Carlsson4ebf1602011-01-20 06:29:02 +00002022 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00002023
Douglas Gregor10bd3682008-11-17 22:58:34 +00002024 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002025
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002026 if (isInstField) {
2027 FieldDecl *FD = cast<FieldDecl>(Member);
2028 FieldCollector->Add(FD);
2029
2030 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2031 FD->getLocation())
2032 != DiagnosticsEngine::Ignored) {
2033 // Remember all explicit private FieldDecls that have a name, no side
2034 // effects and are not part of a dependent type declaration.
2035 if (!FD->isImplicit() && FD->getDeclName() &&
2036 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002037 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002038 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002039 !InitializationHasSideEffects(*FD))
2040 UnusedPrivateFields.insert(FD);
2041 }
2042 }
2043
John McCalld226f652010-08-21 09:40:31 +00002044 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002045}
2046
Hans Wennborg471f9852012-09-18 15:58:06 +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),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002055 S(S) {
2056 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2057 this->VD = IFD->getAnonField();
2058 else
2059 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002060 }
2061
2062 void HandleExpr(Expr *E) {
2063 if (!E) return;
2064
2065 // Expressions like x(x) sometimes lack the surrounding expressions
2066 // but need to be checked anyways.
2067 HandleValue(E);
2068 Visit(E);
2069 }
2070
2071 void HandleValue(Expr *E) {
2072 E = E->IgnoreParens();
2073
2074 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2075 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002076 return;
2077
2078 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2079 // or union.
2080 MemberExpr *FieldME = ME;
2081
Hans Wennborg471f9852012-09-18 15:58:06 +00002082 Expr *Base = E;
2083 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002084 ME = cast<MemberExpr>(Base);
2085
2086 if (isa<VarDecl>(ME->getMemberDecl()))
2087 return;
2088
2089 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2090 if (!FD->isAnonymousStructOrUnion())
2091 FieldME = ME;
2092
Hans Wennborg471f9852012-09-18 15:58:06 +00002093 Base = ME->getBase();
2094 }
2095
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002096 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00002097 unsigned diag = VD->getType()->isReferenceType()
2098 ? diag::warn_reference_field_is_uninit
2099 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002100 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002101 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002102 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002103 }
2104
2105 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2106 HandleValue(CO->getTrueExpr());
2107 HandleValue(CO->getFalseExpr());
2108 return;
2109 }
2110
2111 if (BinaryConditionalOperator *BCO =
2112 dyn_cast<BinaryConditionalOperator>(E)) {
2113 HandleValue(BCO->getCommon());
2114 HandleValue(BCO->getFalseExpr());
2115 return;
2116 }
2117
2118 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2119 switch (BO->getOpcode()) {
2120 default:
2121 return;
2122 case(BO_PtrMemD):
2123 case(BO_PtrMemI):
2124 HandleValue(BO->getLHS());
2125 return;
2126 case(BO_Comma):
2127 HandleValue(BO->getRHS());
2128 return;
2129 }
2130 }
2131 }
2132
2133 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2134 if (E->getCastKind() == CK_LValueToRValue)
2135 HandleValue(E->getSubExpr());
2136
2137 Inherited::VisitImplicitCastExpr(E);
2138 }
2139
2140 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2141 Expr *Callee = E->getCallee();
2142 if (isa<MemberExpr>(Callee))
2143 HandleValue(Callee);
2144
2145 Inherited::VisitCXXMemberCallExpr(E);
2146 }
2147 };
2148 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2149 ValueDecl *VD) {
2150 UninitializedFieldVisitor(S, VD).HandleExpr(E);
2151 }
2152} // namespace
2153
Richard Smith7a614d82011-06-11 17:19:42 +00002154/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002155/// in-class initializer for a non-static C++ class member, and after
2156/// instantiating an in-class initializer in a class template. Such actions
2157/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002158void
Richard Smithca523302012-06-10 03:12:00 +00002159Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002160 Expr *InitExpr) {
2161 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002162 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2163 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002164
2165 if (!InitExpr) {
2166 FD->setInvalidDecl();
2167 FD->removeInClassInitializer();
2168 return;
2169 }
2170
Peter Collingbournefef21892011-10-23 18:59:44 +00002171 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2172 FD->setInvalidDecl();
2173 FD->removeInClassInitializer();
2174 return;
2175 }
2176
Hans Wennborg471f9852012-09-18 15:58:06 +00002177 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2178 != DiagnosticsEngine::Ignored) {
2179 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2180 }
2181
Richard Smith7a614d82011-06-11 17:19:42 +00002182 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002183 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002184 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002185 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002186 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002187 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002188 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2189 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002190 if (Init.isInvalid()) {
2191 FD->setInvalidDecl();
2192 return;
2193 }
Richard Smith7a614d82011-06-11 17:19:42 +00002194 }
2195
Richard Smith41956372013-01-14 22:39:08 +00002196 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002197 // The initialization of each base and member constitutes a
2198 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002199 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002200 if (Init.isInvalid()) {
2201 FD->setInvalidDecl();
2202 return;
2203 }
2204
2205 InitExpr = Init.release();
2206
2207 FD->setInClassInitializer(InitExpr);
2208}
2209
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002210/// \brief Find the direct and/or virtual base specifiers that
2211/// correspond to the given base type, for use in base initialization
2212/// within a constructor.
2213static bool FindBaseInitializer(Sema &SemaRef,
2214 CXXRecordDecl *ClassDecl,
2215 QualType BaseType,
2216 const CXXBaseSpecifier *&DirectBaseSpec,
2217 const CXXBaseSpecifier *&VirtualBaseSpec) {
2218 // First, check for a direct base class.
2219 DirectBaseSpec = 0;
2220 for (CXXRecordDecl::base_class_const_iterator Base
2221 = ClassDecl->bases_begin();
2222 Base != ClassDecl->bases_end(); ++Base) {
2223 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2224 // We found a direct base of this type. That's what we're
2225 // initializing.
2226 DirectBaseSpec = &*Base;
2227 break;
2228 }
2229 }
2230
2231 // Check for a virtual base class.
2232 // FIXME: We might be able to short-circuit this if we know in advance that
2233 // there are no virtual bases.
2234 VirtualBaseSpec = 0;
2235 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2236 // We haven't found a base yet; search the class hierarchy for a
2237 // virtual base class.
2238 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2239 /*DetectVirtual=*/false);
2240 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2241 BaseType, Paths)) {
2242 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2243 Path != Paths.end(); ++Path) {
2244 if (Path->back().Base->isVirtual()) {
2245 VirtualBaseSpec = Path->back().Base;
2246 break;
2247 }
2248 }
2249 }
2250 }
2251
2252 return DirectBaseSpec || VirtualBaseSpec;
2253}
2254
Sebastian Redl6df65482011-09-24 17:48:25 +00002255/// \brief Handle a C++ member initializer using braced-init-list syntax.
2256MemInitResult
2257Sema::ActOnMemInitializer(Decl *ConstructorD,
2258 Scope *S,
2259 CXXScopeSpec &SS,
2260 IdentifierInfo *MemberOrBase,
2261 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002262 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002263 SourceLocation IdLoc,
2264 Expr *InitList,
2265 SourceLocation EllipsisLoc) {
2266 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002267 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002268 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002269}
2270
2271/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002272MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002273Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002274 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002275 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002276 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002277 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002278 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002279 SourceLocation IdLoc,
2280 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002281 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002282 SourceLocation RParenLoc,
2283 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002284 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002285 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002286 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002287 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002288}
2289
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002290namespace {
2291
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002292// Callback to only accept typo corrections that can be a valid C++ member
2293// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002294class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002295public:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002296 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2297 : ClassDecl(ClassDecl) {}
2298
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002299 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002300 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2301 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2302 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002303 return isa<TypeDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002304 }
2305 return false;
2306 }
2307
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002308private:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002309 CXXRecordDecl *ClassDecl;
2310};
2311
2312}
2313
Sebastian Redl6df65482011-09-24 17:48:25 +00002314/// \brief Handle a C++ member initializer.
2315MemInitResult
2316Sema::BuildMemInitializer(Decl *ConstructorD,
2317 Scope *S,
2318 CXXScopeSpec &SS,
2319 IdentifierInfo *MemberOrBase,
2320 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002321 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002322 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002323 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002324 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002325 if (!ConstructorD)
2326 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002327
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002328 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002329
2330 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002331 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002332 if (!Constructor) {
2333 // The user wrote a constructor initializer on a function that is
2334 // not a C++ constructor. Ignore the error for now, because we may
2335 // have more member initializers coming; we'll diagnose it just
2336 // once in ActOnMemInitializers.
2337 return true;
2338 }
2339
2340 CXXRecordDecl *ClassDecl = Constructor->getParent();
2341
2342 // C++ [class.base.init]p2:
2343 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002344 // constructor's class and, if not found in that scope, are looked
2345 // up in the scope containing the constructor's definition.
2346 // [Note: if the constructor's class contains a member with the
2347 // same name as a direct or virtual base class of the class, a
2348 // mem-initializer-id naming the member or base class and composed
2349 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002350 // mem-initializer-id for the hidden base class may be specified
2351 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002352 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002353 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002354 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002355 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002356 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002357 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002358 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2359 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002360 if (EllipsisLoc.isValid())
2361 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002362 << MemberOrBase
2363 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002364
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002365 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002366 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002367 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002368 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002369 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002370 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002371 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002372
2373 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002374 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002375 } else if (DS.getTypeSpecType() == TST_decltype) {
2376 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002377 } else {
2378 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2379 LookupParsedName(R, S, &SS);
2380
2381 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2382 if (!TyD) {
2383 if (R.isAmbiguous()) return true;
2384
John McCallfd225442010-04-09 19:01:14 +00002385 // We don't want access-control diagnostics here.
2386 R.suppressDiagnostics();
2387
Douglas Gregor7a886e12010-01-19 06:46:48 +00002388 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2389 bool NotUnknownSpecialization = false;
2390 DeclContext *DC = computeDeclContext(SS, false);
2391 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2392 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2393
2394 if (!NotUnknownSpecialization) {
2395 // When the scope specifier can refer to a member of an unknown
2396 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002397 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2398 SS.getWithLocInContext(Context),
2399 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002400 if (BaseType.isNull())
2401 return true;
2402
Douglas Gregor7a886e12010-01-19 06:46:48 +00002403 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002404 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002405 }
2406 }
2407
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002408 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002409 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002410 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002411 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002412 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002413 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002414 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002415 // We have found a non-static data member with a similar
2416 // name to what was typed; complain and initialize that
2417 // member.
Richard Smith2d670972013-08-17 00:46:16 +00002418 diagnoseTypo(Corr,
2419 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2420 << MemberOrBase << true);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002421 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002422 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002423 const CXXBaseSpecifier *DirectBaseSpec;
2424 const CXXBaseSpecifier *VirtualBaseSpec;
2425 if (FindBaseInitializer(*this, ClassDecl,
2426 Context.getTypeDeclType(Type),
2427 DirectBaseSpec, VirtualBaseSpec)) {
2428 // We have found a direct or virtual base class with a
2429 // similar name to what was typed; complain and initialize
2430 // that base class.
Richard Smith2d670972013-08-17 00:46:16 +00002431 diagnoseTypo(Corr,
2432 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2433 << MemberOrBase << false,
2434 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002435
Richard Smith2d670972013-08-17 00:46:16 +00002436 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2437 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002438 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002439 diag::note_base_class_specified_here)
2440 << BaseSpec->getType()
2441 << BaseSpec->getSourceRange();
2442
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002443 TyD = Type;
2444 }
2445 }
2446 }
2447
Douglas Gregor7a886e12010-01-19 06:46:48 +00002448 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002449 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002450 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002451 return true;
2452 }
John McCall2b194412009-12-21 10:41:20 +00002453 }
2454
Douglas Gregor7a886e12010-01-19 06:46:48 +00002455 if (BaseType.isNull()) {
2456 BaseType = Context.getTypeDeclType(TyD);
2457 if (SS.isSet()) {
2458 NestedNameSpecifier *Qualifier =
2459 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002460
Douglas Gregor7a886e12010-01-19 06:46:48 +00002461 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002462 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002463 }
John McCall2b194412009-12-21 10:41:20 +00002464 }
2465 }
Mike Stump1eb44332009-09-09 15:08:12 +00002466
John McCalla93c9342009-12-07 02:54:59 +00002467 if (!TInfo)
2468 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002469
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002470 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002471}
2472
Chandler Carruth81c64772011-09-03 01:14:15 +00002473/// Checks a member initializer expression for cases where reference (or
2474/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002475static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2476 Expr *Init,
2477 SourceLocation IdLoc) {
2478 QualType MemberTy = Member->getType();
2479
2480 // We only handle pointers and references currently.
2481 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2482 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2483 return;
2484
2485 const bool IsPointer = MemberTy->isPointerType();
2486 if (IsPointer) {
2487 if (const UnaryOperator *Op
2488 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2489 // The only case we're worried about with pointers requires taking the
2490 // address.
2491 if (Op->getOpcode() != UO_AddrOf)
2492 return;
2493
2494 Init = Op->getSubExpr();
2495 } else {
2496 // We only handle address-of expression initializers for pointers.
2497 return;
2498 }
2499 }
2500
Richard Smitha4bb99c2013-06-12 21:51:50 +00002501 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002502 // We only warn when referring to a non-reference parameter declaration.
2503 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2504 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002505 return;
2506
2507 S.Diag(Init->getExprLoc(),
2508 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2509 : diag::warn_bind_ref_member_to_parameter)
2510 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002511 } else {
2512 // Other initializers are fine.
2513 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002514 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002515
2516 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2517 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002518}
2519
John McCallf312b1e2010-08-26 23:41:50 +00002520MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002521Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002522 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002523 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2524 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2525 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002526 "Member must be a FieldDecl or IndirectFieldDecl");
2527
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002528 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002529 return true;
2530
Douglas Gregor464b2f02010-11-05 22:21:31 +00002531 if (Member->isInvalidDecl())
2532 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002533
John McCallb4190042009-11-04 23:02:40 +00002534 // Diagnose value-uses of fields to initialize themselves, e.g.
2535 // foo(foo)
2536 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002537 // TODO: implement -Wuninitialized and fold this into that framework.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002538 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002539 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002540 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002541 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002542 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002543 } else {
2544 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002545 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002546 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002547
Richard Trieude5e75c2012-06-14 23:11:34 +00002548 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2549 != DiagnosticsEngine::Ignored)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002550 for (unsigned i = 0, e = Args.size(); i != e; ++i)
Richard Trieude5e75c2012-06-14 23:11:34 +00002551 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002552 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002553 // initializing the i'th field, throw a warning if any of the >= i'th
2554 // fields are used, as they are not yet initialized.
2555 // Right now we are only handling the case where the i'th field uses
2556 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002557 // Also need to take into account that some fields may be initialized by
2558 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002559 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002560
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002561 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002562
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002563 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002564 // Can't check initialization for a member of dependent type or when
2565 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002566 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002567 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002568 bool InitList = false;
2569 if (isa<InitListExpr>(Init)) {
2570 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002571 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002572 }
2573
Chandler Carruth894aed92010-12-06 09:23:57 +00002574 // Initialize the member.
2575 InitializedEntity MemberEntity =
2576 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2577 : InitializedEntity::InitializeMember(IndirectMember, 0);
2578 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002579 InitList ? InitializationKind::CreateDirectList(IdLoc)
2580 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2581 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002582
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002583 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2584 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002585 if (MemberInit.isInvalid())
2586 return true;
2587
Richard Smith8a07cd32013-06-12 20:42:33 +00002588 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2589
Richard Smith41956372013-01-14 22:39:08 +00002590 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002591 // The initialization of each base and member constitutes a
2592 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002593 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002594 if (MemberInit.isInvalid())
2595 return true;
2596
Richard Smithc83c2302012-12-19 01:39:02 +00002597 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002598 }
2599
Chandler Carruth894aed92010-12-06 09:23:57 +00002600 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002601 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2602 InitRange.getBegin(), Init,
2603 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002604 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002605 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2606 InitRange.getBegin(), Init,
2607 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002608 }
Eli Friedman59c04372009-07-29 19:44:27 +00002609}
2610
John McCallf312b1e2010-08-26 23:41:50 +00002611MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002612Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002613 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002614 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002615 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002616 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002617 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002618 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002619
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002620 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002621 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002622 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2623 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002624 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002625 }
2626
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002627 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002628 // Initialize the object.
2629 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2630 QualType(ClassDecl->getTypeForDecl(), 0));
2631 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002632 InitList ? InitializationKind::CreateDirectList(NameLoc)
2633 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2634 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002635 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002636 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002637 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002638 if (DelegationInit.isInvalid())
2639 return true;
2640
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002641 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2642 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002643
Richard Smith41956372013-01-14 22:39:08 +00002644 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002645 // The initialization of each base and member constitutes a
2646 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002647 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2648 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002649 if (DelegationInit.isInvalid())
2650 return true;
2651
Eli Friedmand21016f2012-05-19 23:35:23 +00002652 // If we are in a dependent context, template instantiation will
2653 // perform this type-checking again. Just save the arguments that we
2654 // received in a ParenListExpr.
2655 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2656 // of the information that we have about the base
2657 // initializer. However, deconstructing the ASTs is a dicey process,
2658 // and this approach is far more likely to get the corner cases right.
2659 if (CurContext->isDependentContext())
2660 DelegationInit = Owned(Init);
2661
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002662 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002663 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002664 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002665}
2666
2667MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002668Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002669 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002670 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002671 SourceLocation BaseLoc
2672 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002673
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002674 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2675 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2676 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2677
2678 // C++ [class.base.init]p2:
2679 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002680 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002681 // of that class, the mem-initializer is ill-formed. A
2682 // mem-initializer-list can initialize a base class using any
2683 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002684 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002685
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002686 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002687 if (EllipsisLoc.isValid()) {
2688 // This is a pack expansion.
2689 if (!BaseType->containsUnexpandedParameterPack()) {
2690 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002691 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002692
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002693 EllipsisLoc = SourceLocation();
2694 }
2695 } else {
2696 // Check for any unexpanded parameter packs.
2697 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2698 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002699
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002700 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002701 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002702 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002703
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002704 // Check for direct and virtual base classes.
2705 const CXXBaseSpecifier *DirectBaseSpec = 0;
2706 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2707 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002708 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2709 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002710 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002711
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002712 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2713 VirtualBaseSpec);
2714
2715 // C++ [base.class.init]p2:
2716 // Unless the mem-initializer-id names a nonstatic data member of the
2717 // constructor's class or a direct or virtual base of that class, the
2718 // mem-initializer is ill-formed.
2719 if (!DirectBaseSpec && !VirtualBaseSpec) {
2720 // If the class has any dependent bases, then it's possible that
2721 // one of those types will resolve to the same type as
2722 // BaseType. Therefore, just treat this as a dependent base
2723 // class initialization. FIXME: Should we try to check the
2724 // initialization anyway? It seems odd.
2725 if (ClassDecl->hasAnyDependentBases())
2726 Dependent = true;
2727 else
2728 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2729 << BaseType << Context.getTypeDeclType(ClassDecl)
2730 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2731 }
2732 }
2733
2734 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002735 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002736
Sebastian Redl6df65482011-09-24 17:48:25 +00002737 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2738 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002739 InitRange.getBegin(), Init,
2740 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002741 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002742
2743 // C++ [base.class.init]p2:
2744 // If a mem-initializer-id is ambiguous because it designates both
2745 // a direct non-virtual base class and an inherited virtual base
2746 // class, the mem-initializer is ill-formed.
2747 if (DirectBaseSpec && VirtualBaseSpec)
2748 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002749 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002750
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002751 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002752 if (!BaseSpec)
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002753 BaseSpec = VirtualBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002754
2755 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002756 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002757 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002758 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002759 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002760 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002761 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002762
2763 InitializedEntity BaseEntity =
2764 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2765 InitializationKind Kind =
2766 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2767 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2768 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002769 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2770 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002771 if (BaseInit.isInvalid())
2772 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002773
Richard Smith41956372013-01-14 22:39:08 +00002774 // C++11 [class.base.init]p7:
2775 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002776 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002777 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002778 if (BaseInit.isInvalid())
2779 return true;
2780
2781 // If we are in a dependent context, template instantiation will
2782 // perform this type-checking again. Just save the arguments that we
2783 // received in a ParenListExpr.
2784 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2785 // of the information that we have about the base
2786 // initializer. However, deconstructing the ASTs is a dicey process,
2787 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002788 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002789 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002790
Sean Huntcbb67482011-01-08 20:30:50 +00002791 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002792 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002793 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002794 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002795 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002796}
2797
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002798// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002799static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2800 if (T.isNull()) T = E->getType();
2801 QualType TargetType = SemaRef.BuildReferenceType(
2802 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002803 SourceLocation ExprLoc = E->getLocStart();
2804 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2805 TargetType, ExprLoc);
2806
2807 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2808 SourceRange(ExprLoc, ExprLoc),
2809 E->getSourceRange()).take();
2810}
2811
Anders Carlssone5ef7402010-04-23 03:10:23 +00002812/// ImplicitInitializerKind - How an implicit base or member initializer should
2813/// initialize its base or member.
2814enum ImplicitInitializerKind {
2815 IIK_Default,
2816 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002817 IIK_Move,
2818 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002819};
2820
Anders Carlssondefefd22010-04-23 02:00:02 +00002821static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002822BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002823 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002824 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002825 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002826 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002827 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002828 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2829 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002830
John McCall60d7b3a2010-08-24 06:29:42 +00002831 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002832
2833 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002834 case IIK_Inherit: {
2835 const CXXRecordDecl *Inherited =
2836 Constructor->getInheritedConstructor()->getParent();
2837 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2838 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2839 // C++11 [class.inhctor]p8:
2840 // Each expression in the expression-list is of the form
2841 // static_cast<T&&>(p), where p is the name of the corresponding
2842 // constructor parameter and T is the declared type of p.
2843 SmallVector<Expr*, 16> Args;
2844 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2845 ParmVarDecl *PD = Constructor->getParamDecl(I);
2846 ExprResult ArgExpr =
2847 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2848 VK_LValue, SourceLocation());
2849 if (ArgExpr.isInvalid())
2850 return true;
2851 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2852 }
2853
2854 InitializationKind InitKind = InitializationKind::CreateDirect(
2855 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002856 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002857 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2858 break;
2859 }
2860 }
2861 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002862 case IIK_Default: {
2863 InitializationKind InitKind
2864 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002865 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2866 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002867 break;
2868 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002869
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002870 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002871 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002872 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002873 ParmVarDecl *Param = Constructor->getParamDecl(0);
2874 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002875
Anders Carlssone5ef7402010-04-23 03:10:23 +00002876 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002877 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002878 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002879 Constructor->getLocation(), ParamType,
2880 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002881
Eli Friedman5f2987c2012-02-02 03:46:19 +00002882 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2883
Anders Carlssonc7957502010-04-24 22:02:54 +00002884 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002885 QualType ArgTy =
2886 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2887 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002888
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002889 if (Moving) {
2890 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2891 }
2892
John McCallf871d0c2010-08-07 06:22:56 +00002893 CXXCastPath BasePath;
2894 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002895 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2896 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002897 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002898 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002899
Anders Carlssone5ef7402010-04-23 03:10:23 +00002900 InitializationKind InitKind
2901 = InitializationKind::CreateDirect(Constructor->getLocation(),
2902 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002903 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2904 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002905 break;
2906 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002907 }
John McCall9ae2f072010-08-23 23:25:46 +00002908
Douglas Gregor53c374f2010-12-07 00:41:46 +00002909 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002910 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002911 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002912
Anders Carlssondefefd22010-04-23 02:00:02 +00002913 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002914 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002915 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2916 SourceLocation()),
2917 BaseSpec->isVirtual(),
2918 SourceLocation(),
2919 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002920 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002921 SourceLocation());
2922
Anders Carlssondefefd22010-04-23 02:00:02 +00002923 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002924}
2925
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002926static bool RefersToRValueRef(Expr *MemRef) {
2927 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2928 return Referenced->getType()->isRValueReferenceType();
2929}
2930
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002931static bool
2932BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002933 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002934 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002935 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002936 if (Field->isInvalidDecl())
2937 return true;
2938
Chandler Carruthf186b542010-06-29 23:50:44 +00002939 SourceLocation Loc = Constructor->getLocation();
2940
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002941 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2942 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002943 ParmVarDecl *Param = Constructor->getParamDecl(0);
2944 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002945
2946 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002947 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2948 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002949
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002950 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002951 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002952 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002953 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002954
Eli Friedman5f2987c2012-02-02 03:46:19 +00002955 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2956
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002957 if (Moving) {
2958 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2959 }
2960
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002961 // Build a reference to this field within the parameter.
2962 CXXScopeSpec SS;
2963 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2964 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002965 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2966 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002967 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002968 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002969 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002970 ParamType, Loc,
2971 /*IsArrow=*/false,
2972 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002973 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002974 /*FirstQualifierInScope=*/0,
2975 MemberLookup,
2976 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002977 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002978 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002979
2980 // C++11 [class.copy]p15:
2981 // - if a member m has rvalue reference type T&&, it is direct-initialized
2982 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002983 if (RefersToRValueRef(CtorArg.get())) {
2984 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002985 }
2986
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002987 // When the field we are copying is an array, create index variables for
2988 // each dimension of the array. We use these index variables to subscript
2989 // the source array, and other clients (e.g., CodeGen) will perform the
2990 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002991 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002992 QualType BaseType = Field->getType();
2993 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002994 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002995 while (const ConstantArrayType *Array
2996 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002997 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002998 // Create the iteration variable for this array index.
2999 IdentifierInfo *IterationVarName = 0;
3000 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003001 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003002 llvm::raw_svector_ostream OS(Str);
3003 OS << "__i" << IndexVariables.size();
3004 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3005 }
3006 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003007 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003008 IterationVarName, SizeType,
3009 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003010 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003011 IndexVariables.push_back(IterationVar);
3012
3013 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003014 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003015 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003016 assert(!IterationVarRef.isInvalid() &&
3017 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003018 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3019 assert(!IterationVarRef.isInvalid() &&
3020 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003021
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003022 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003023 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003024 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003025 Loc);
3026 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003027 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003028
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003029 BaseType = Array->getElementType();
3030 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003031
3032 // The array subscript expression is an lvalue, which is wrong for moving.
3033 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003034 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003035
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003036 // Construct the entity that we will be initializing. For an array, this
3037 // will be first element in the array, which may require several levels
3038 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003039 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003040 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003041 if (Indirect)
3042 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3043 else
3044 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003045 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3046 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3047 0,
3048 Entities.back()));
3049
3050 // Direct-initialize to use the copy constructor.
3051 InitializationKind InitKind =
3052 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3053
Sebastian Redl74e611a2011-09-04 18:14:28 +00003054 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003055 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003056
John McCall60d7b3a2010-08-24 06:29:42 +00003057 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003058 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003059 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003060 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003061 if (MemberInit.isInvalid())
3062 return true;
3063
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003064 if (Indirect) {
3065 assert(IndexVariables.size() == 0 &&
3066 "Indirect field improperly initialized");
3067 CXXMemberInit
3068 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3069 Loc, Loc,
3070 MemberInit.takeAs<Expr>(),
3071 Loc);
3072 } else
3073 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3074 Loc, MemberInit.takeAs<Expr>(),
3075 Loc,
3076 IndexVariables.data(),
3077 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003078 return false;
3079 }
3080
Richard Smith07b0fdc2013-03-18 21:12:30 +00003081 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3082 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003083
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003084 QualType FieldBaseElementType =
3085 SemaRef.Context.getBaseElementType(Field->getType());
3086
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003087 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003088 InitializedEntity InitEntity
3089 = Indirect? InitializedEntity::InitializeMember(Indirect)
3090 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003091 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003092 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003093
3094 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3095 ExprResult MemberInit =
3096 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003097
Douglas Gregor53c374f2010-12-07 00:41:46 +00003098 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003099 if (MemberInit.isInvalid())
3100 return true;
3101
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003102 if (Indirect)
3103 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3104 Indirect, Loc,
3105 Loc,
3106 MemberInit.get(),
3107 Loc);
3108 else
3109 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3110 Field, Loc, Loc,
3111 MemberInit.get(),
3112 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003113 return false;
3114 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003115
Sean Hunt1f2f3842011-05-17 00:19:05 +00003116 if (!Field->getParent()->isUnion()) {
3117 if (FieldBaseElementType->isReferenceType()) {
3118 SemaRef.Diag(Constructor->getLocation(),
3119 diag::err_uninitialized_member_in_ctor)
3120 << (int)Constructor->isImplicit()
3121 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3122 << 0 << Field->getDeclName();
3123 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3124 return true;
3125 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003126
Sean Hunt1f2f3842011-05-17 00:19:05 +00003127 if (FieldBaseElementType.isConstQualified()) {
3128 SemaRef.Diag(Constructor->getLocation(),
3129 diag::err_uninitialized_member_in_ctor)
3130 << (int)Constructor->isImplicit()
3131 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3132 << 1 << Field->getDeclName();
3133 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3134 return true;
3135 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003136 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003137
David Blaikie4e4d0842012-03-11 07:00:24 +00003138 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003139 FieldBaseElementType->isObjCRetainableType() &&
3140 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3141 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003142 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003143 // Default-initialize Objective-C pointers to NULL.
3144 CXXMemberInit
3145 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3146 Loc, Loc,
3147 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3148 Loc);
3149 return false;
3150 }
3151
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003152 // Nothing to initialize.
3153 CXXMemberInit = 0;
3154 return false;
3155}
John McCallf1860e52010-05-20 23:23:51 +00003156
3157namespace {
3158struct BaseAndFieldInfo {
3159 Sema &S;
3160 CXXConstructorDecl *Ctor;
3161 bool AnyErrorsInInits;
3162 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003163 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003164 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003165
3166 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3167 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003168 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3169 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003170 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003171 else if (Generated && Ctor->isMoveConstructor())
3172 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003173 else if (Ctor->getInheritedConstructor())
3174 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003175 else
3176 IIK = IIK_Default;
3177 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003178
3179 bool isImplicitCopyOrMove() const {
3180 switch (IIK) {
3181 case IIK_Copy:
3182 case IIK_Move:
3183 return true;
3184
3185 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003186 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003187 return false;
3188 }
David Blaikie30263482012-01-20 21:50:17 +00003189
3190 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003191 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003192
3193 bool addFieldInitializer(CXXCtorInitializer *Init) {
3194 AllToInit.push_back(Init);
3195
3196 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003197 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003198 S.UnusedPrivateFields.remove(Init->getAnyMember());
3199
3200 return false;
3201 }
John McCallf1860e52010-05-20 23:23:51 +00003202};
3203}
3204
Richard Smitha4950662011-09-19 13:34:43 +00003205/// \brief Determine whether the given indirect field declaration is somewhere
3206/// within an anonymous union.
3207static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3208 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3209 CEnd = F->chain_end();
3210 C != CEnd; ++C)
3211 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3212 if (Record->isUnion())
3213 return true;
3214
3215 return false;
3216}
3217
Douglas Gregorddb21472011-11-02 23:04:16 +00003218/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3219/// array type.
3220static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3221 if (T->isIncompleteArrayType())
3222 return true;
3223
3224 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3225 if (!ArrayT->getSize())
3226 return true;
3227
3228 T = ArrayT->getElementType();
3229 }
3230
3231 return false;
3232}
3233
Richard Smith7a614d82011-06-11 17:19:42 +00003234static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003235 FieldDecl *Field,
3236 IndirectFieldDecl *Indirect = 0) {
Eli Friedman5fb478b2013-06-28 21:07:41 +00003237 if (Field->isInvalidDecl())
3238 return false;
John McCallf1860e52010-05-20 23:23:51 +00003239
Chandler Carruthe861c602010-06-30 02:59:29 +00003240 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003241 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3242 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003243
Richard Smith0b8220a2012-08-07 21:30:42 +00003244 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003245 // has a brace-or-equal-initializer, the entity is initialized as specified
3246 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003247 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003248 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3249 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003250 CXXCtorInitializer *Init;
3251 if (Indirect)
3252 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3253 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003254 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003255 SourceLocation());
3256 else
3257 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3258 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003259 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003260 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003261 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003262 }
3263
Richard Smithc115f632011-09-18 11:14:50 +00003264 // Don't build an implicit initializer for union members if none was
3265 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003266 if (Field->getParent()->isUnion() ||
3267 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003268 return false;
3269
Douglas Gregorddb21472011-11-02 23:04:16 +00003270 // Don't initialize incomplete or zero-length arrays.
3271 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3272 return false;
3273
John McCallf1860e52010-05-20 23:23:51 +00003274 // Don't try to build an implicit initializer if there were semantic
3275 // errors in any of the initializers (and therefore we might be
3276 // missing some that the user actually wrote).
Eli Friedman5fb478b2013-06-28 21:07:41 +00003277 if (Info.AnyErrorsInInits)
John McCallf1860e52010-05-20 23:23:51 +00003278 return false;
3279
Sean Huntcbb67482011-01-08 20:30:50 +00003280 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003281 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3282 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003283 return true;
John McCallf1860e52010-05-20 23:23:51 +00003284
Richard Smith0b8220a2012-08-07 21:30:42 +00003285 if (!Init)
3286 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003287
Richard Smith0b8220a2012-08-07 21:30:42 +00003288 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003289}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003290
3291bool
3292Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3293 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003294 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003295 Constructor->setNumCtorInitializers(1);
3296 CXXCtorInitializer **initializer =
3297 new (Context) CXXCtorInitializer*[1];
3298 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3299 Constructor->setCtorInitializers(initializer);
3300
Sean Huntb76af9c2011-05-03 23:05:34 +00003301 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003302 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003303 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3304 }
3305
Sean Huntc1598702011-05-05 00:05:47 +00003306 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003307
Sean Hunt059ce0d2011-05-01 07:04:31 +00003308 return false;
3309}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003310
David Blaikie93c86172013-01-17 05:26:25 +00003311bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3312 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003313 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003314 // Just store the initializers as written, they will be checked during
3315 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003316 if (!Initializers.empty()) {
3317 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003318 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003319 new (Context) CXXCtorInitializer*[Initializers.size()];
3320 memcpy(baseOrMemberInitializers, Initializers.data(),
3321 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003322 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003323 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003324
3325 // Let template instantiation know whether we had errors.
3326 if (AnyErrors)
3327 Constructor->setInvalidDecl();
3328
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003329 return false;
3330 }
3331
John McCallf1860e52010-05-20 23:23:51 +00003332 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003333
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003334 // We need to build the initializer AST according to order of construction
3335 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003336 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003337 if (!ClassDecl)
3338 return true;
3339
Eli Friedman80c30da2009-11-09 19:20:36 +00003340 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003341
David Blaikie93c86172013-01-17 05:26:25 +00003342 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003343 CXXCtorInitializer *Member = Initializers[i];
Richard Smithcbc820a2013-07-22 02:56:56 +00003344
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003345 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003346 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003347 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003348 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003349 }
3350
Anders Carlsson711f34a2010-04-21 19:52:01 +00003351 // Keep track of the direct virtual bases.
3352 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3353 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3354 E = ClassDecl->bases_end(); I != E; ++I) {
3355 if (I->isVirtual())
3356 DirectVBases.insert(I);
3357 }
3358
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003359 // Push virtual bases before others.
3360 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3361 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3362
Sean Huntcbb67482011-01-08 20:30:50 +00003363 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003364 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Richard Smithcbc820a2013-07-22 02:56:56 +00003365 // [class.base.init]p7, per DR257:
3366 // A mem-initializer where the mem-initializer-id names a virtual base
3367 // class is ignored during execution of a constructor of any class that
3368 // is not the most derived class.
3369 if (ClassDecl->isAbstract()) {
3370 // FIXME: Provide a fixit to remove the base specifier. This requires
3371 // tracking the location of the associated comma for a base specifier.
3372 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3373 << VBase->getType() << ClassDecl;
3374 DiagnoseAbstractType(ClassDecl);
3375 }
3376
John McCallf1860e52010-05-20 23:23:51 +00003377 Info.AllToInit.push_back(Value);
Richard Smithcbc820a2013-07-22 02:56:56 +00003378 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3379 // [class.base.init]p8, per DR257:
3380 // If a given [...] base class is not named by a mem-initializer-id
3381 // [...] and the entity is not a virtual base class of an abstract
3382 // class, then [...] the entity is default-initialized.
Anders Carlsson711f34a2010-04-21 19:52:01 +00003383 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003384 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003385 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Richard Smithcbc820a2013-07-22 02:56:56 +00003386 VBase, IsInheritedVirtualBase,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003387 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003388 HadError = true;
3389 continue;
3390 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003391
John McCallf1860e52010-05-20 23:23:51 +00003392 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003393 }
3394 }
Mike Stump1eb44332009-09-09 15:08:12 +00003395
John McCallf1860e52010-05-20 23:23:51 +00003396 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003397 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3398 E = ClassDecl->bases_end(); Base != E; ++Base) {
3399 // Virtuals are in the virtual base list and already constructed.
3400 if (Base->isVirtual())
3401 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003402
Sean Huntcbb67482011-01-08 20:30:50 +00003403 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003404 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3405 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003406 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003407 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003408 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003409 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003410 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003411 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003412 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003413 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003414
John McCallf1860e52010-05-20 23:23:51 +00003415 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003416 }
3417 }
Mike Stump1eb44332009-09-09 15:08:12 +00003418
John McCallf1860e52010-05-20 23:23:51 +00003419 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003420 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3421 MemEnd = ClassDecl->decls_end();
3422 Mem != MemEnd; ++Mem) {
3423 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003424 // C++ [class.bit]p2:
3425 // A declaration for a bit-field that omits the identifier declares an
3426 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3427 // initialized.
3428 if (F->isUnnamedBitfield())
3429 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003430
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003431 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003432 // handle anonymous struct/union fields based on their individual
3433 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003434 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003435 continue;
3436
3437 if (CollectFieldInitializer(*this, Info, F))
3438 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003439 continue;
3440 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003441
3442 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003443 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003444 continue;
3445
3446 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3447 if (F->getType()->isIncompleteArrayType()) {
3448 assert(ClassDecl->hasFlexibleArrayMember() &&
3449 "Incomplete array type is not valid");
3450 continue;
3451 }
3452
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003453 // Initialize each field of an anonymous struct individually.
3454 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3455 HadError = true;
3456
3457 continue;
3458 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003459 }
Mike Stump1eb44332009-09-09 15:08:12 +00003460
David Blaikie93c86172013-01-17 05:26:25 +00003461 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003462 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003463 Constructor->setNumCtorInitializers(NumInitializers);
3464 CXXCtorInitializer **baseOrMemberInitializers =
3465 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003466 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003467 NumInitializers * sizeof(CXXCtorInitializer*));
3468 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003469
John McCallef027fe2010-03-16 21:39:52 +00003470 // Constructors implicitly reference the base and member
3471 // destructors.
3472 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3473 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003474 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003475
3476 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003477}
3478
David Blaikieee000bb2013-01-17 08:49:22 +00003479static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003480 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003481 const RecordDecl *RD = RT->getDecl();
3482 if (RD->isAnonymousStructOrUnion()) {
3483 for (RecordDecl::field_iterator Field = RD->field_begin(),
3484 E = RD->field_end(); Field != E; ++Field)
3485 PopulateKeysForFields(*Field, IdealInits);
3486 return;
3487 }
Eli Friedman6347f422009-07-21 19:28:10 +00003488 }
David Blaikieee000bb2013-01-17 08:49:22 +00003489 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003490}
3491
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003492static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3493 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003494}
3495
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003496static const void *GetKeyForMember(ASTContext &Context,
3497 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003498 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003499 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003500
David Blaikieee000bb2013-01-17 08:49:22 +00003501 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003502}
3503
David Blaikie93c86172013-01-17 05:26:25 +00003504static void DiagnoseBaseOrMemInitializerOrder(
3505 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3506 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003507 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003508 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003509
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003510 // Don't check initializers order unless the warning is enabled at the
3511 // location of at least one initializer.
3512 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003513 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003514 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003515 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3516 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003517 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003518 ShouldCheckOrder = true;
3519 break;
3520 }
3521 }
3522 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003523 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003524
John McCalld6ca8da2010-04-10 07:37:23 +00003525 // Build the list of bases and members in the order that they'll
3526 // actually be initialized. The explicit initializers should be in
3527 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003528 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003529
Anders Carlsson071d6102010-04-02 03:38:04 +00003530 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3531
John McCalld6ca8da2010-04-10 07:37:23 +00003532 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003533 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003534 ClassDecl->vbases_begin(),
3535 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003536 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003537
John McCalld6ca8da2010-04-10 07:37:23 +00003538 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003539 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003540 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003541 if (Base->isVirtual())
3542 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003543 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003544 }
Mike Stump1eb44332009-09-09 15:08:12 +00003545
John McCalld6ca8da2010-04-10 07:37:23 +00003546 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003547 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003548 E = ClassDecl->field_end(); Field != E; ++Field) {
3549 if (Field->isUnnamedBitfield())
3550 continue;
3551
David Blaikieee000bb2013-01-17 08:49:22 +00003552 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003553 }
3554
John McCalld6ca8da2010-04-10 07:37:23 +00003555 unsigned NumIdealInits = IdealInitKeys.size();
3556 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003557
Sean Huntcbb67482011-01-08 20:30:50 +00003558 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003559 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003560 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003561 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003562
3563 // Scan forward to try to find this initializer in the idealized
3564 // initializers list.
3565 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3566 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003567 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003568
3569 // If we didn't find this initializer, it must be because we
3570 // scanned past it on a previous iteration. That can only
3571 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003572 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003573 Sema::SemaDiagnosticBuilder D =
3574 SemaRef.Diag(PrevInit->getSourceLocation(),
3575 diag::warn_initializer_out_of_order);
3576
Francois Pichet00eb3f92010-12-04 09:14:42 +00003577 if (PrevInit->isAnyMemberInitializer())
3578 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003579 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003580 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003581
Francois Pichet00eb3f92010-12-04 09:14:42 +00003582 if (Init->isAnyMemberInitializer())
3583 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003584 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003585 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003586
3587 // Move back to the initializer's location in the ideal list.
3588 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3589 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003590 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003591
3592 assert(IdealIndex != NumIdealInits &&
3593 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003594 }
John McCalld6ca8da2010-04-10 07:37:23 +00003595
3596 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003597 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003598}
3599
John McCall3c3ccdb2010-04-10 09:28:51 +00003600namespace {
3601bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003602 CXXCtorInitializer *Init,
3603 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003604 if (!PrevInit) {
3605 PrevInit = Init;
3606 return false;
3607 }
3608
Douglas Gregordc392c12013-03-25 23:28:23 +00003609 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003610 S.Diag(Init->getSourceLocation(),
3611 diag::err_multiple_mem_initialization)
3612 << Field->getDeclName()
3613 << Init->getSourceRange();
3614 else {
John McCallf4c73712011-01-19 06:33:43 +00003615 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003616 assert(BaseClass && "neither field nor base");
3617 S.Diag(Init->getSourceLocation(),
3618 diag::err_multiple_base_initialization)
3619 << QualType(BaseClass, 0)
3620 << Init->getSourceRange();
3621 }
3622 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3623 << 0 << PrevInit->getSourceRange();
3624
3625 return true;
3626}
3627
Sean Huntcbb67482011-01-08 20:30:50 +00003628typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003629typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3630
3631bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003632 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003633 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003634 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003635 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003636 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003637
3638 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003639 if (Parent->isUnion()) {
3640 UnionEntry &En = Unions[Parent];
3641 if (En.first && En.first != Child) {
3642 S.Diag(Init->getSourceLocation(),
3643 diag::err_multiple_mem_union_initialization)
3644 << Field->getDeclName()
3645 << Init->getSourceRange();
3646 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3647 << 0 << En.second->getSourceRange();
3648 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003649 }
3650 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003651 En.first = Child;
3652 En.second = Init;
3653 }
David Blaikie6fe29652011-11-17 06:01:57 +00003654 if (!Parent->isAnonymousStructOrUnion())
3655 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003656 }
3657
3658 Child = Parent;
3659 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003660 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003661
3662 return false;
3663}
3664}
3665
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003666/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003667void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003668 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003669 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003670 bool AnyErrors) {
3671 if (!ConstructorDecl)
3672 return;
3673
3674 AdjustDeclIfTemplate(ConstructorDecl);
3675
3676 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003677 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003678
3679 if (!Constructor) {
3680 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3681 return;
3682 }
3683
John McCall3c3ccdb2010-04-10 09:28:51 +00003684 // Mapping for the duplicate initializers check.
3685 // For member initializers, this is keyed with a FieldDecl*.
3686 // For base initializers, this is keyed with a Type*.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003687 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003688
3689 // Mapping for the inconsistent anonymous-union initializers check.
3690 RedundantUnionMap MemberUnions;
3691
Anders Carlssonea356fb2010-04-02 05:42:15 +00003692 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003693 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003694 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003695
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003696 // Set the source order index.
3697 Init->setSourceOrder(i);
3698
Francois Pichet00eb3f92010-12-04 09:14:42 +00003699 if (Init->isAnyMemberInitializer()) {
3700 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003701 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3702 CheckRedundantUnionInit(*this, Init, MemberUnions))
3703 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003704 } else if (Init->isBaseInitializer()) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003705 const void *Key =
3706 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall3c3ccdb2010-04-10 09:28:51 +00003707 if (CheckRedundantInit(*this, Init, Members[Key]))
3708 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003709 } else {
3710 assert(Init->isDelegatingInitializer());
3711 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003712 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003713 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003714 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003715 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003716 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003717 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003718 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003719 // Return immediately as the initializer is set.
3720 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003721 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003722 }
3723
Anders Carlssonea356fb2010-04-02 05:42:15 +00003724 if (HadError)
3725 return;
3726
David Blaikie93c86172013-01-17 05:26:25 +00003727 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003728
David Blaikie93c86172013-01-17 05:26:25 +00003729 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003730}
3731
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003732void
John McCallef027fe2010-03-16 21:39:52 +00003733Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3734 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003735 // Ignore dependent contexts. Also ignore unions, since their members never
3736 // have destructors implicitly called.
3737 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003738 return;
John McCall58e6f342010-03-16 05:22:47 +00003739
3740 // FIXME: all the access-control diagnostics are positioned on the
3741 // field/base declaration. That's probably good; that said, the
3742 // user might reasonably want to know why the destructor is being
3743 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003744
Anders Carlsson9f853df2009-11-17 04:44:12 +00003745 // Non-static data members.
3746 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3747 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003748 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003749 if (Field->isInvalidDecl())
3750 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003751
3752 // Don't destroy incomplete or zero-length arrays.
3753 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3754 continue;
3755
Anders Carlsson9f853df2009-11-17 04:44:12 +00003756 QualType FieldType = Context.getBaseElementType(Field->getType());
3757
3758 const RecordType* RT = FieldType->getAs<RecordType>();
3759 if (!RT)
3760 continue;
3761
3762 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003763 if (FieldClassDecl->isInvalidDecl())
3764 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003765 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003766 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003767 // The destructor for an implicit anonymous union member is never invoked.
3768 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3769 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003770
Douglas Gregordb89f282010-07-01 22:47:18 +00003771 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003772 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003773 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003774 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003775 << Field->getDeclName()
3776 << FieldType);
3777
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003778 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003779 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003780 }
3781
John McCall58e6f342010-03-16 05:22:47 +00003782 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3783
Anders Carlsson9f853df2009-11-17 04:44:12 +00003784 // Bases.
3785 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3786 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003787 // Bases are always records in a well-formed non-dependent class.
3788 const RecordType *RT = Base->getType()->getAs<RecordType>();
3789
3790 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003791 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003792 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003793
John McCall58e6f342010-03-16 05:22:47 +00003794 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003795 // If our base class is invalid, we probably can't get its dtor anyway.
3796 if (BaseClassDecl->isInvalidDecl())
3797 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003798 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003799 continue;
John McCall58e6f342010-03-16 05:22:47 +00003800
Douglas Gregordb89f282010-07-01 22:47:18 +00003801 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003802 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003803
3804 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003805 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003806 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003807 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003808 << Base->getSourceRange(),
3809 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003810
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003811 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003812 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003813 }
3814
3815 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003816 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3817 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003818
3819 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003820 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003821
3822 // Ignore direct virtual bases.
3823 if (DirectVirtualBases.count(RT))
3824 continue;
3825
John McCall58e6f342010-03-16 05:22:47 +00003826 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003827 // If our base class is invalid, we probably can't get its dtor anyway.
3828 if (BaseClassDecl->isInvalidDecl())
3829 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003830 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003831 continue;
John McCall58e6f342010-03-16 05:22:47 +00003832
Douglas Gregordb89f282010-07-01 22:47:18 +00003833 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003834 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00003835 if (CheckDestructorAccess(
3836 ClassDecl->getLocation(), Dtor,
3837 PDiag(diag::err_access_dtor_vbase)
3838 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3839 Context.getTypeDeclType(ClassDecl)) ==
3840 AR_accessible) {
3841 CheckDerivedToBaseConversion(
3842 Context.getTypeDeclType(ClassDecl), VBase->getType(),
3843 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3844 SourceRange(), DeclarationName(), 0);
3845 }
John McCall58e6f342010-03-16 05:22:47 +00003846
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003847 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003848 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003849 }
3850}
3851
John McCalld226f652010-08-21 09:40:31 +00003852void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003853 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003854 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003855
Mike Stump1eb44332009-09-09 15:08:12 +00003856 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003857 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003858 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003859}
3860
Mike Stump1eb44332009-09-09 15:08:12 +00003861bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003862 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003863 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3864 unsigned DiagID;
3865 AbstractDiagSelID SelID;
3866
3867 public:
3868 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3869 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003870
3871 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
Eli Friedman2217f852012-08-14 02:06:07 +00003872 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003873 if (SelID == -1)
3874 S.Diag(Loc, DiagID) << T;
3875 else
3876 S.Diag(Loc, DiagID) << SelID << T;
3877 }
3878 } Diagnoser(DiagID, SelID);
3879
3880 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003881}
3882
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003883bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003884 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003885 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003886 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003887
Anders Carlsson11f21a02009-03-23 19:10:31 +00003888 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003889 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003890
Ted Kremenek6217b802009-07-29 21:53:49 +00003891 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003892 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003893 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003894 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003895
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003896 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003897 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003898 }
Mike Stump1eb44332009-09-09 15:08:12 +00003899
Ted Kremenek6217b802009-07-29 21:53:49 +00003900 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003901 if (!RT)
3902 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003903
John McCall86ff3082010-02-04 22:26:26 +00003904 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003905
John McCall94c3b562010-08-18 09:41:07 +00003906 // We can't answer whether something is abstract until it has a
3907 // definition. If it's currently being defined, we'll walk back
3908 // over all the declarations when we have a full definition.
3909 const CXXRecordDecl *Def = RD->getDefinition();
3910 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003911 return false;
3912
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003913 if (!RD->isAbstract())
3914 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003915
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003916 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003917 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003918
John McCall94c3b562010-08-18 09:41:07 +00003919 return true;
3920}
3921
3922void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3923 // Check if we've already emitted the list of pure virtual functions
3924 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003925 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003926 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003927
Richard Smithcbc820a2013-07-22 02:56:56 +00003928 // If the diagnostic is suppressed, don't emit the notes. We're only
3929 // going to emit them once, so try to attach them to a diagnostic we're
3930 // actually going to show.
3931 if (Diags.isLastDiagnosticIgnored())
3932 return;
3933
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003934 CXXFinalOverriderMap FinalOverriders;
3935 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003936
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003937 // Keep a set of seen pure methods so we won't diagnose the same method
3938 // more than once.
3939 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3940
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003941 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3942 MEnd = FinalOverriders.end();
3943 M != MEnd;
3944 ++M) {
3945 for (OverridingMethods::iterator SO = M->second.begin(),
3946 SOEnd = M->second.end();
3947 SO != SOEnd; ++SO) {
3948 // C++ [class.abstract]p4:
3949 // A class is abstract if it contains or inherits at least one
3950 // pure virtual function for which the final overrider is pure
3951 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003952
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003953 //
3954 if (SO->second.size() != 1)
3955 continue;
3956
3957 if (!SO->second.front().Method->isPure())
3958 continue;
3959
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003960 if (!SeenPureMethods.insert(SO->second.front().Method))
3961 continue;
3962
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003963 Diag(SO->second.front().Method->getLocation(),
3964 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003965 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003966 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003967 }
3968
3969 if (!PureVirtualClassDiagSet)
3970 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3971 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003972}
3973
Anders Carlsson8211eff2009-03-24 01:19:16 +00003974namespace {
John McCall94c3b562010-08-18 09:41:07 +00003975struct AbstractUsageInfo {
3976 Sema &S;
3977 CXXRecordDecl *Record;
3978 CanQualType AbstractType;
3979 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003980
John McCall94c3b562010-08-18 09:41:07 +00003981 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3982 : S(S), Record(Record),
3983 AbstractType(S.Context.getCanonicalType(
3984 S.Context.getTypeDeclType(Record))),
3985 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003986
John McCall94c3b562010-08-18 09:41:07 +00003987 void DiagnoseAbstractType() {
3988 if (Invalid) return;
3989 S.DiagnoseAbstractType(Record);
3990 Invalid = true;
3991 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003992
John McCall94c3b562010-08-18 09:41:07 +00003993 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3994};
3995
3996struct CheckAbstractUsage {
3997 AbstractUsageInfo &Info;
3998 const NamedDecl *Ctx;
3999
4000 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4001 : Info(Info), Ctx(Ctx) {}
4002
4003 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4004 switch (TL.getTypeLocClass()) {
4005#define ABSTRACT_TYPELOC(CLASS, PARENT)
4006#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00004007 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00004008#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00004009 }
John McCall94c3b562010-08-18 09:41:07 +00004010 }
Mike Stump1eb44332009-09-09 15:08:12 +00004011
John McCall94c3b562010-08-18 09:41:07 +00004012 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4013 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4014 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00004015 if (!TL.getArg(I))
4016 continue;
4017
John McCall94c3b562010-08-18 09:41:07 +00004018 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4019 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004020 }
John McCall94c3b562010-08-18 09:41:07 +00004021 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004022
John McCall94c3b562010-08-18 09:41:07 +00004023 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4024 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4025 }
Mike Stump1eb44332009-09-09 15:08:12 +00004026
John McCall94c3b562010-08-18 09:41:07 +00004027 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4028 // Visit the type parameters from a permissive context.
4029 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4030 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4031 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4032 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4033 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4034 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004035 }
John McCall94c3b562010-08-18 09:41:07 +00004036 }
Mike Stump1eb44332009-09-09 15:08:12 +00004037
John McCall94c3b562010-08-18 09:41:07 +00004038 // Visit pointee types from a permissive context.
4039#define CheckPolymorphic(Type) \
4040 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4041 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4042 }
4043 CheckPolymorphic(PointerTypeLoc)
4044 CheckPolymorphic(ReferenceTypeLoc)
4045 CheckPolymorphic(MemberPointerTypeLoc)
4046 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004047 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004048
John McCall94c3b562010-08-18 09:41:07 +00004049 /// Handle all the types we haven't given a more specific
4050 /// implementation for above.
4051 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4052 // Every other kind of type that we haven't called out already
4053 // that has an inner type is either (1) sugar or (2) contains that
4054 // inner type in some way as a subobject.
4055 if (TypeLoc Next = TL.getNextTypeLoc())
4056 return Visit(Next, Sel);
4057
4058 // If there's no inner type and we're in a permissive context,
4059 // don't diagnose.
4060 if (Sel == Sema::AbstractNone) return;
4061
4062 // Check whether the type matches the abstract type.
4063 QualType T = TL.getType();
4064 if (T->isArrayType()) {
4065 Sel = Sema::AbstractArrayType;
4066 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004067 }
John McCall94c3b562010-08-18 09:41:07 +00004068 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4069 if (CT != Info.AbstractType) return;
4070
4071 // It matched; do some magic.
4072 if (Sel == Sema::AbstractArrayType) {
4073 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4074 << T << TL.getSourceRange();
4075 } else {
4076 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4077 << Sel << T << TL.getSourceRange();
4078 }
4079 Info.DiagnoseAbstractType();
4080 }
4081};
4082
4083void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4084 Sema::AbstractDiagSelID Sel) {
4085 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4086}
4087
4088}
4089
4090/// Check for invalid uses of an abstract type in a method declaration.
4091static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4092 CXXMethodDecl *MD) {
4093 // No need to do the check on definitions, which require that
4094 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004095 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004096 return;
4097
4098 // For safety's sake, just ignore it if we don't have type source
4099 // information. This should never happen for non-implicit methods,
4100 // but...
4101 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4102 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4103}
4104
4105/// Check for invalid uses of an abstract type within a class definition.
4106static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4107 CXXRecordDecl *RD) {
4108 for (CXXRecordDecl::decl_iterator
4109 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4110 Decl *D = *I;
4111 if (D->isImplicit()) continue;
4112
4113 // Methods and method templates.
4114 if (isa<CXXMethodDecl>(D)) {
4115 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4116 } else if (isa<FunctionTemplateDecl>(D)) {
4117 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4118 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4119
4120 // Fields and static variables.
4121 } else if (isa<FieldDecl>(D)) {
4122 FieldDecl *FD = cast<FieldDecl>(D);
4123 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4124 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4125 } else if (isa<VarDecl>(D)) {
4126 VarDecl *VD = cast<VarDecl>(D);
4127 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4128 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4129
4130 // Nested classes and class templates.
4131 } else if (isa<CXXRecordDecl>(D)) {
4132 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4133 } else if (isa<ClassTemplateDecl>(D)) {
4134 CheckAbstractClassUsage(Info,
4135 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4136 }
4137 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004138}
4139
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004140/// \brief Perform semantic checks on a class definition that has been
4141/// completing, introducing implicitly-declared members, checking for
4142/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004143void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004144 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004145 return;
4146
John McCall94c3b562010-08-18 09:41:07 +00004147 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4148 AbstractUsageInfo Info(*this, Record);
4149 CheckAbstractClassUsage(Info, Record);
4150 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004151
4152 // If this is not an aggregate type and has no user-declared constructor,
4153 // complain about any non-static data members of reference or const scalar
4154 // type, since they will never get initializers.
4155 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004156 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4157 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004158 bool Complained = false;
4159 for (RecordDecl::field_iterator F = Record->field_begin(),
4160 FEnd = Record->field_end();
4161 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004162 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004163 continue;
4164
Douglas Gregor325e5932010-04-15 00:00:53 +00004165 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004166 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004167 if (!Complained) {
4168 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4169 << Record->getTagKind() << Record;
4170 Complained = true;
4171 }
4172
4173 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4174 << F->getType()->isReferenceType()
4175 << F->getDeclName();
4176 }
4177 }
4178 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004179
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004180 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004181 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004182
4183 if (Record->getIdentifier()) {
4184 // C++ [class.mem]p13:
4185 // If T is the name of a class, then each of the following shall have a
4186 // name different from T:
4187 // - every member of every anonymous union that is a member of class T.
4188 //
4189 // C++ [class.mem]p14:
4190 // In addition, if class T has a user-declared constructor (12.1), every
4191 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004192 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4193 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4194 ++I) {
4195 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004196 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4197 isa<IndirectFieldDecl>(D)) {
4198 Diag(D->getLocation(), diag::err_member_name_of_class)
4199 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004200 break;
4201 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004202 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004203 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004204
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004205 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004206 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004207 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004208 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004209 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4210 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4211 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004212
David Blaikieb6b5b972012-09-21 03:21:07 +00004213 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4214 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4215 DiagnoseAbstractType(Record);
4216 }
4217
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004218 if (!Record->isDependentType()) {
4219 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4220 MEnd = Record->method_end();
4221 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004222 // See if a method overloads virtual methods in a base
4223 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004224 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004225 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004226
4227 // Check whether the explicitly-defaulted special members are valid.
4228 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4229 CheckExplicitlyDefaultedSpecialMember(*M);
4230
4231 // For an explicitly defaulted or deleted special member, we defer
4232 // determining triviality until the class is complete. That time is now!
4233 if (!M->isImplicit() && !M->isUserProvided()) {
4234 CXXSpecialMember CSM = getSpecialMember(*M);
4235 if (CSM != CXXInvalid) {
4236 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4237
4238 // Inform the class that we've finished declaring this member.
4239 Record->finishedDefaultedOrDeletedMember(*M);
4240 }
4241 }
4242 }
4243 }
4244
4245 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4246 // function that is not a constructor declares that member function to be
4247 // const. [...] The class of which that function is a member shall be
4248 // a literal type.
4249 //
4250 // If the class has virtual bases, any constexpr members will already have
4251 // been diagnosed by the checks performed on the member declaration, so
4252 // suppress this (less useful) diagnostic.
4253 //
4254 // We delay this until we know whether an explicitly-defaulted (or deleted)
4255 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004256 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004257 !Record->isLiteral() && !Record->getNumVBases()) {
4258 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4259 MEnd = Record->method_end();
4260 M != MEnd; ++M) {
4261 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4262 switch (Record->getTemplateSpecializationKind()) {
4263 case TSK_ImplicitInstantiation:
4264 case TSK_ExplicitInstantiationDeclaration:
4265 case TSK_ExplicitInstantiationDefinition:
4266 // If a template instantiates to a non-literal type, but its members
4267 // instantiate to constexpr functions, the template is technically
4268 // ill-formed, but we allow it for sanity.
4269 continue;
4270
4271 case TSK_Undeclared:
4272 case TSK_ExplicitSpecialization:
4273 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4274 diag::err_constexpr_method_non_literal);
4275 break;
4276 }
4277
4278 // Only produce one error per class.
4279 break;
4280 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004281 }
4282 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004283
Richard Smith07b0fdc2013-03-18 21:12:30 +00004284 // Declare inheriting constructors. We do this eagerly here because:
4285 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004286 // constructors from different classes.
4287 // - The lazy declaration of the other implicit constructors is so as to not
4288 // waste space and performance on classes that are not meant to be
4289 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004290 // have inheriting constructors.
4291 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004292}
4293
Richard Smith7756afa2012-06-10 05:43:50 +00004294/// Is the special member function which would be selected to perform the
4295/// specified operation on the specified class type a constexpr constructor?
4296static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4297 Sema::CXXSpecialMember CSM,
4298 bool ConstArg) {
4299 Sema::SpecialMemberOverloadResult *SMOR =
4300 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4301 false, false, false, false);
4302 if (!SMOR || !SMOR->getMethod())
4303 // A constructor we wouldn't select can't be "involved in initializing"
4304 // anything.
4305 return true;
4306 return SMOR->getMethod()->isConstexpr();
4307}
4308
4309/// Determine whether the specified special member function would be constexpr
4310/// if it were implicitly defined.
4311static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4312 Sema::CXXSpecialMember CSM,
4313 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004314 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004315 return false;
4316
4317 // C++11 [dcl.constexpr]p4:
4318 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004319 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004320 switch (CSM) {
4321 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004322 // Since default constructor lookup is essentially trivial (and cannot
4323 // involve, for instance, template instantiation), we compute whether a
4324 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4325 //
4326 // This is important for performance; we need to know whether the default
4327 // constructor is constexpr to determine whether the type is a literal type.
4328 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4329
Richard Smith7756afa2012-06-10 05:43:50 +00004330 case Sema::CXXCopyConstructor:
4331 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004332 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004333 break;
4334
4335 case Sema::CXXCopyAssignment:
4336 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004337 if (!S.getLangOpts().CPlusPlus1y)
4338 return false;
4339 // In C++1y, we need to perform overload resolution.
4340 Ctor = false;
4341 break;
4342
Richard Smith7756afa2012-06-10 05:43:50 +00004343 case Sema::CXXDestructor:
4344 case Sema::CXXInvalid:
4345 return false;
4346 }
4347
4348 // -- if the class is a non-empty union, or for each non-empty anonymous
4349 // union member of a non-union class, exactly one non-static data member
4350 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004351 //
4352 // If we squint, this is guaranteed, since exactly one non-static data member
4353 // will be initialized (if the constructor isn't deleted), we just don't know
4354 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004355 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004356 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004357
4358 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004359 if (Ctor && ClassDecl->getNumVBases())
4360 return false;
4361
4362 // C++1y [class.copy]p26:
4363 // -- [the class] is a literal type, and
4364 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004365 return false;
4366
4367 // -- every constructor involved in initializing [...] base class
4368 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004369 // -- the assignment operator selected to copy/move each direct base
4370 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004371 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4372 BEnd = ClassDecl->bases_end();
4373 B != BEnd; ++B) {
4374 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4375 if (!BaseType) continue;
4376
4377 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4378 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4379 return false;
4380 }
4381
4382 // -- every constructor involved in initializing non-static data members
4383 // [...] shall be a constexpr constructor;
4384 // -- every non-static data member and base class sub-object shall be
4385 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004386 // -- for each non-stastic data member of X that is of class type (or array
4387 // thereof), the assignment operator selected to copy/move that member is
4388 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004389 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4390 FEnd = ClassDecl->field_end();
4391 F != FEnd; ++F) {
4392 if (F->isInvalidDecl())
4393 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004394 if (const RecordType *RecordTy =
4395 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004396 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4397 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4398 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004399 }
4400 }
4401
4402 // All OK, it's constexpr!
4403 return true;
4404}
4405
Richard Smithb9d0b762012-07-27 04:22:15 +00004406static Sema::ImplicitExceptionSpecification
4407computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4408 switch (S.getSpecialMember(MD)) {
4409 case Sema::CXXDefaultConstructor:
4410 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4411 case Sema::CXXCopyConstructor:
4412 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4413 case Sema::CXXCopyAssignment:
4414 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4415 case Sema::CXXMoveConstructor:
4416 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4417 case Sema::CXXMoveAssignment:
4418 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4419 case Sema::CXXDestructor:
4420 return S.ComputeDefaultedDtorExceptionSpec(MD);
4421 case Sema::CXXInvalid:
4422 break;
4423 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004424 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4425 "only special members have implicit exception specs");
4426 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004427}
4428
Richard Smithdd25e802012-07-30 23:48:14 +00004429static void
4430updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4431 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4432 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4433 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004434 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4435 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004436}
4437
Reid Kleckneref072032013-08-27 23:08:25 +00004438static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4439 CXXMethodDecl *MD) {
4440 FunctionProtoType::ExtProtoInfo EPI;
4441
4442 // Build an exception specification pointing back at this member.
4443 EPI.ExceptionSpecType = EST_Unevaluated;
4444 EPI.ExceptionSpecDecl = MD;
4445
4446 // Set the calling convention to the default for C++ instance methods.
4447 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4448 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4449 /*IsCXXMethod=*/true));
4450 return EPI;
4451}
4452
Richard Smithb9d0b762012-07-27 04:22:15 +00004453void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4454 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4455 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4456 return;
4457
Richard Smithdd25e802012-07-30 23:48:14 +00004458 // Evaluate the exception specification.
4459 ImplicitExceptionSpecification ExceptSpec =
4460 computeImplicitExceptionSpec(*this, Loc, MD);
4461
4462 // Update the type of the special member to use it.
4463 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4464
4465 // A user-provided destructor can be defined outside the class. When that
4466 // happens, be sure to update the exception specification on both
4467 // declarations.
4468 const FunctionProtoType *CanonicalFPT =
4469 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4470 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4471 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4472 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004473}
4474
Richard Smith3003e1d2012-05-15 04:39:51 +00004475void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4476 CXXRecordDecl *RD = MD->getParent();
4477 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004478
Richard Smith3003e1d2012-05-15 04:39:51 +00004479 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4480 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004481
4482 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004483 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004484 bool First = MD == MD->getCanonicalDecl();
4485
4486 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004487
4488 // C++11 [dcl.fct.def.default]p1:
4489 // A function that is explicitly defaulted shall
4490 // -- be a special member function (checked elsewhere),
4491 // -- have the same type (except for ref-qualifiers, and except that a
4492 // copy operation can take a non-const reference) as an implicit
4493 // declaration, and
4494 // -- not have default arguments.
4495 unsigned ExpectedParams = 1;
4496 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4497 ExpectedParams = 0;
4498 if (MD->getNumParams() != ExpectedParams) {
4499 // This also checks for default arguments: a copy or move constructor with a
4500 // default argument is classified as a default constructor, and assignment
4501 // operations and destructors can't have default arguments.
4502 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4503 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004504 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004505 } else if (MD->isVariadic()) {
4506 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4507 << CSM << MD->getSourceRange();
4508 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004509 }
4510
Richard Smith3003e1d2012-05-15 04:39:51 +00004511 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004512
Richard Smith7756afa2012-06-10 05:43:50 +00004513 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004514 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004515 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004516 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004517 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004518
Richard Smith3003e1d2012-05-15 04:39:51 +00004519 QualType ReturnType = Context.VoidTy;
4520 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4521 // Check for return type matching.
4522 ReturnType = Type->getResultType();
4523 QualType ExpectedReturnType =
4524 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4525 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4526 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4527 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4528 HadError = true;
4529 }
4530
4531 // A defaulted special member cannot have cv-qualifiers.
4532 if (Type->getTypeQuals()) {
4533 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004534 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004535 HadError = true;
4536 }
4537 }
4538
4539 // Check for parameter type matching.
4540 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004541 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004542 if (ExpectedParams && ArgType->isReferenceType()) {
4543 // Argument must be reference to possibly-const T.
4544 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004545 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004546
4547 if (ReferentType.isVolatileQualified()) {
4548 Diag(MD->getLocation(),
4549 diag::err_defaulted_special_member_volatile_param) << CSM;
4550 HadError = true;
4551 }
4552
Richard Smith7756afa2012-06-10 05:43:50 +00004553 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004554 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4555 Diag(MD->getLocation(),
4556 diag::err_defaulted_special_member_copy_const_param)
4557 << (CSM == CXXCopyAssignment);
4558 // FIXME: Explain why this special member can't be const.
4559 } else {
4560 Diag(MD->getLocation(),
4561 diag::err_defaulted_special_member_move_const_param)
4562 << (CSM == CXXMoveAssignment);
4563 }
4564 HadError = true;
4565 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004566 } else if (ExpectedParams) {
4567 // A copy assignment operator can take its argument by value, but a
4568 // defaulted one cannot.
4569 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004570 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004571 HadError = true;
4572 }
Sean Huntbe631222011-05-17 20:44:43 +00004573
Richard Smith61802452011-12-22 02:22:31 +00004574 // C++11 [dcl.fct.def.default]p2:
4575 // An explicitly-defaulted function may be declared constexpr only if it
4576 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004577 // Do not apply this rule to members of class templates, since core issue 1358
4578 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004579 // functions which cannot be constexpr (for non-constructors in C++11 and for
4580 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004581 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4582 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004583 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4584 : isa<CXXConstructorDecl>(MD)) &&
4585 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004586 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4587 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004588 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004589 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004590 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004591
Richard Smith61802452011-12-22 02:22:31 +00004592 // and may have an explicit exception-specification only if it is compatible
4593 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004594 if (Type->hasExceptionSpec()) {
4595 // Delay the check if this is the first declaration of the special member,
4596 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004597 if (First) {
4598 // If the exception specification needs to be instantiated, do so now,
4599 // before we clobber it with an EST_Unevaluated specification below.
4600 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4601 InstantiateExceptionSpec(MD->getLocStart(), MD);
4602 Type = MD->getType()->getAs<FunctionProtoType>();
4603 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004604 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004605 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004606 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4607 }
Richard Smith61802452011-12-22 02:22:31 +00004608
4609 // If a function is explicitly defaulted on its first declaration,
4610 if (First) {
4611 // -- it is implicitly considered to be constexpr if the implicit
4612 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004613 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004614
Richard Smith3003e1d2012-05-15 04:39:51 +00004615 // -- it is implicitly considered to have the same exception-specification
4616 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004617 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4618 EPI.ExceptionSpecType = EST_Unevaluated;
4619 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004620 MD->setType(Context.getFunctionType(ReturnType,
4621 ArrayRef<QualType>(&ArgType,
4622 ExpectedParams),
4623 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004624 }
4625
Richard Smith3003e1d2012-05-15 04:39:51 +00004626 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004627 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004628 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004629 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004630 // C++11 [dcl.fct.def.default]p4:
4631 // [For a] user-provided explicitly-defaulted function [...] if such a
4632 // function is implicitly defined as deleted, the program is ill-formed.
4633 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4634 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004635 }
4636 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004637
Richard Smith3003e1d2012-05-15 04:39:51 +00004638 if (HadError)
4639 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004640}
4641
Richard Smith1d28caf2012-12-11 01:14:52 +00004642/// Check whether the exception specification provided for an
4643/// explicitly-defaulted special member matches the exception specification
4644/// that would have been generated for an implicit special member, per
4645/// C++11 [dcl.fct.def.default]p2.
4646void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4647 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4648 // Compute the implicit exception specification.
Reid Kleckneref072032013-08-27 23:08:25 +00004649 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4650 /*IsCXXMethod=*/true);
4651 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith1d28caf2012-12-11 01:14:52 +00004652 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4653 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004654 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004655
4656 // Ensure that it matches.
4657 CheckEquivalentExceptionSpec(
4658 PDiag(diag::err_incorrect_defaulted_exception_spec)
4659 << getSpecialMember(MD), PDiag(),
4660 ImplicitType, SourceLocation(),
4661 SpecifiedType, MD->getLocation());
4662}
4663
4664void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4665 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4666 I != N; ++I)
4667 CheckExplicitlyDefaultedMemberExceptionSpec(
4668 DelayedDefaultedMemberExceptionSpecs[I].first,
4669 DelayedDefaultedMemberExceptionSpecs[I].second);
4670
4671 DelayedDefaultedMemberExceptionSpecs.clear();
4672}
4673
Richard Smith7d5088a2012-02-18 02:02:13 +00004674namespace {
4675struct SpecialMemberDeletionInfo {
4676 Sema &S;
4677 CXXMethodDecl *MD;
4678 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004679 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004680
4681 // Properties of the special member, computed for convenience.
4682 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4683 SourceLocation Loc;
4684
4685 bool AllFieldsAreConst;
4686
4687 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004688 Sema::CXXSpecialMember CSM, bool Diagnose)
4689 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004690 IsConstructor(false), IsAssignment(false), IsMove(false),
4691 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4692 AllFieldsAreConst(true) {
4693 switch (CSM) {
4694 case Sema::CXXDefaultConstructor:
4695 case Sema::CXXCopyConstructor:
4696 IsConstructor = true;
4697 break;
4698 case Sema::CXXMoveConstructor:
4699 IsConstructor = true;
4700 IsMove = true;
4701 break;
4702 case Sema::CXXCopyAssignment:
4703 IsAssignment = true;
4704 break;
4705 case Sema::CXXMoveAssignment:
4706 IsAssignment = true;
4707 IsMove = true;
4708 break;
4709 case Sema::CXXDestructor:
4710 break;
4711 case Sema::CXXInvalid:
4712 llvm_unreachable("invalid special member kind");
4713 }
4714
4715 if (MD->getNumParams()) {
4716 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4717 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4718 }
4719 }
4720
4721 bool inUnion() const { return MD->getParent()->isUnion(); }
4722
4723 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004724 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4725 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004726 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004727 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4728 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4729 Quals = 0;
4730 return S.LookupSpecialMember(Class, CSM,
4731 ConstArg || (Quals & Qualifiers::Const),
4732 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004733 MD->getRefQualifier() == RQ_RValue,
4734 TQ & Qualifiers::Const,
4735 TQ & Qualifiers::Volatile);
4736 }
4737
Richard Smith6c4c36c2012-03-30 20:53:28 +00004738 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004739
Richard Smith6c4c36c2012-03-30 20:53:28 +00004740 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004741 bool shouldDeleteForField(FieldDecl *FD);
4742 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004743
Richard Smith517bb842012-07-18 03:51:16 +00004744 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4745 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004746 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4747 Sema::SpecialMemberOverloadResult *SMOR,
4748 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004749
4750 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004751};
4752}
4753
John McCall12d8d802012-04-09 20:53:23 +00004754/// Is the given special member inaccessible when used on the given
4755/// sub-object.
4756bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4757 CXXMethodDecl *target) {
4758 /// If we're operating on a base class, the object type is the
4759 /// type of this special member.
4760 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004761 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004762 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4763 objectTy = S.Context.getTypeDeclType(MD->getParent());
4764 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4765
4766 // If we're operating on a field, the object type is the type of the field.
4767 } else {
4768 objectTy = S.Context.getTypeDeclType(target->getParent());
4769 }
4770
4771 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4772}
4773
Richard Smith6c4c36c2012-03-30 20:53:28 +00004774/// Check whether we should delete a special member due to the implicit
4775/// definition containing a call to a special member of a subobject.
4776bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4777 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4778 bool IsDtorCallInCtor) {
4779 CXXMethodDecl *Decl = SMOR->getMethod();
4780 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4781
4782 int DiagKind = -1;
4783
4784 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4785 DiagKind = !Decl ? 0 : 1;
4786 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4787 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004788 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004789 DiagKind = 3;
4790 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4791 !Decl->isTrivial()) {
4792 // A member of a union must have a trivial corresponding special member.
4793 // As a weird special case, a destructor call from a union's constructor
4794 // must be accessible and non-deleted, but need not be trivial. Such a
4795 // destructor is never actually called, but is semantically checked as
4796 // if it were.
4797 DiagKind = 4;
4798 }
4799
4800 if (DiagKind == -1)
4801 return false;
4802
4803 if (Diagnose) {
4804 if (Field) {
4805 S.Diag(Field->getLocation(),
4806 diag::note_deleted_special_member_class_subobject)
4807 << CSM << MD->getParent() << /*IsField*/true
4808 << Field << DiagKind << IsDtorCallInCtor;
4809 } else {
4810 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4811 S.Diag(Base->getLocStart(),
4812 diag::note_deleted_special_member_class_subobject)
4813 << CSM << MD->getParent() << /*IsField*/false
4814 << Base->getType() << DiagKind << IsDtorCallInCtor;
4815 }
4816
4817 if (DiagKind == 1)
4818 S.NoteDeletedFunction(Decl);
4819 // FIXME: Explain inaccessibility if DiagKind == 3.
4820 }
4821
4822 return true;
4823}
4824
Richard Smith9a561d52012-02-26 09:11:52 +00004825/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004826/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004827bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004828 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004829 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004830
4831 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004832 // -- any direct or virtual base class, or non-static data member with no
4833 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004834 // either M has no default constructor or overload resolution as applied
4835 // to M's default constructor results in an ambiguity or in a function
4836 // that is deleted or inaccessible
4837 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4838 // -- a direct or virtual base class B that cannot be copied/moved because
4839 // overload resolution, as applied to B's corresponding special member,
4840 // results in an ambiguity or a function that is deleted or inaccessible
4841 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004842 // C++11 [class.dtor]p5:
4843 // -- any direct or virtual base class [...] has a type with a destructor
4844 // that is deleted or inaccessible
4845 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004846 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004847 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004848 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004849
Richard Smith6c4c36c2012-03-30 20:53:28 +00004850 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4851 // -- any direct or virtual base class or non-static data member has a
4852 // type with a destructor that is deleted or inaccessible
4853 if (IsConstructor) {
4854 Sema::SpecialMemberOverloadResult *SMOR =
4855 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4856 false, false, false, false, false);
4857 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4858 return true;
4859 }
4860
Richard Smith9a561d52012-02-26 09:11:52 +00004861 return false;
4862}
4863
4864/// Check whether we should delete a special member function due to the class
4865/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004866bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004867 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004868 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004869}
4870
4871/// Check whether we should delete a special member function due to the class
4872/// having a particular non-static data member.
4873bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4874 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4875 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4876
4877 if (CSM == Sema::CXXDefaultConstructor) {
4878 // For a default constructor, all references must be initialized in-class
4879 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004880 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4881 if (Diagnose)
4882 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4883 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004884 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004885 }
Richard Smith79363f52012-02-27 06:07:25 +00004886 // C++11 [class.ctor]p5: any non-variant non-static data member of
4887 // const-qualified type (or array thereof) with no
4888 // brace-or-equal-initializer does not have a user-provided default
4889 // constructor.
4890 if (!inUnion() && FieldType.isConstQualified() &&
4891 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004892 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4893 if (Diagnose)
4894 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004895 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004896 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004897 }
4898
4899 if (inUnion() && !FieldType.isConstQualified())
4900 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004901 } else if (CSM == Sema::CXXCopyConstructor) {
4902 // For a copy constructor, data members must not be of rvalue reference
4903 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004904 if (FieldType->isRValueReferenceType()) {
4905 if (Diagnose)
4906 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4907 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004908 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004909 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004910 } else if (IsAssignment) {
4911 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004912 if (FieldType->isReferenceType()) {
4913 if (Diagnose)
4914 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4915 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004916 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004917 }
4918 if (!FieldRecord && FieldType.isConstQualified()) {
4919 // C++11 [class.copy]p23:
4920 // -- a non-static data member of const non-class type (or array thereof)
4921 if (Diagnose)
4922 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004923 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004924 return true;
4925 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004926 }
4927
4928 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004929 // Some additional restrictions exist on the variant members.
4930 if (!inUnion() && FieldRecord->isUnion() &&
4931 FieldRecord->isAnonymousStructOrUnion()) {
4932 bool AllVariantFieldsAreConst = true;
4933
Richard Smithdf8dc862012-03-29 19:00:10 +00004934 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004935 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4936 UE = FieldRecord->field_end();
4937 UI != UE; ++UI) {
4938 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004939
4940 if (!UnionFieldType.isConstQualified())
4941 AllVariantFieldsAreConst = false;
4942
Richard Smith9a561d52012-02-26 09:11:52 +00004943 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4944 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004945 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4946 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004947 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004948 }
4949
4950 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004951 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004952 FieldRecord->field_begin() != FieldRecord->field_end()) {
4953 if (Diagnose)
4954 S.Diag(FieldRecord->getLocation(),
4955 diag::note_deleted_default_ctor_all_const)
4956 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004957 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004958 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004959
Richard Smithdf8dc862012-03-29 19:00:10 +00004960 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004961 // This is technically non-conformant, but sanity demands it.
4962 return false;
4963 }
4964
Richard Smith517bb842012-07-18 03:51:16 +00004965 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4966 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004967 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004968 }
4969
4970 return false;
4971}
4972
4973/// C++11 [class.ctor] p5:
4974/// A defaulted default constructor for a class X is defined as deleted if
4975/// X is a union and all of its variant members are of const-qualified type.
4976bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004977 // This is a silly definition, because it gives an empty union a deleted
4978 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004979 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4980 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4981 if (Diagnose)
4982 S.Diag(MD->getParent()->getLocation(),
4983 diag::note_deleted_default_ctor_all_const)
4984 << MD->getParent() << /*not anonymous union*/0;
4985 return true;
4986 }
4987 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004988}
4989
4990/// Determine whether a defaulted special member function should be defined as
4991/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4992/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004993bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4994 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004995 if (MD->isInvalidDecl())
4996 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004997 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004998 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004999 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005000 return false;
5001
Richard Smith7d5088a2012-02-18 02:02:13 +00005002 // C++11 [expr.lambda.prim]p19:
5003 // The closure type associated with a lambda-expression has a
5004 // deleted (8.4.3) default constructor and a deleted copy
5005 // assignment operator.
5006 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005007 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5008 if (Diagnose)
5009 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00005010 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005011 }
5012
Richard Smith5bdaac52012-04-02 20:59:25 +00005013 // For an anonymous struct or union, the copy and assignment special members
5014 // will never be used, so skip the check. For an anonymous union declared at
5015 // namespace scope, the constructor and destructor are used.
5016 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5017 RD->isAnonymousStructOrUnion())
5018 return false;
5019
Richard Smith6c4c36c2012-03-30 20:53:28 +00005020 // C++11 [class.copy]p7, p18:
5021 // If the class definition declares a move constructor or move assignment
5022 // operator, an implicitly declared copy constructor or copy assignment
5023 // operator is defined as deleted.
5024 if (MD->isImplicit() &&
5025 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5026 CXXMethodDecl *UserDeclaredMove = 0;
5027
5028 // In Microsoft mode, a user-declared move only causes the deletion of the
5029 // corresponding copy operation, not both copy operations.
5030 if (RD->hasUserDeclaredMoveConstructor() &&
5031 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5032 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005033
5034 // Find any user-declared move constructor.
5035 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5036 E = RD->ctor_end(); I != E; ++I) {
5037 if (I->isMoveConstructor()) {
5038 UserDeclaredMove = *I;
5039 break;
5040 }
5041 }
Richard Smith1c931be2012-04-02 18:40:40 +00005042 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005043 } else if (RD->hasUserDeclaredMoveAssignment() &&
5044 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5045 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005046
5047 // Find any user-declared move assignment operator.
5048 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5049 E = RD->method_end(); I != E; ++I) {
5050 if (I->isMoveAssignmentOperator()) {
5051 UserDeclaredMove = *I;
5052 break;
5053 }
5054 }
Richard Smith1c931be2012-04-02 18:40:40 +00005055 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005056 }
5057
5058 if (UserDeclaredMove) {
5059 Diag(UserDeclaredMove->getLocation(),
5060 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005061 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005062 << UserDeclaredMove->isMoveAssignmentOperator();
5063 return true;
5064 }
5065 }
Sean Hunte16da072011-10-10 06:18:57 +00005066
Richard Smith5bdaac52012-04-02 20:59:25 +00005067 // Do access control from the special member function
5068 ContextRAII MethodContext(*this, MD);
5069
Richard Smith9a561d52012-02-26 09:11:52 +00005070 // C++11 [class.dtor]p5:
5071 // -- for a virtual destructor, lookup of the non-array deallocation function
5072 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005073 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005074 FunctionDecl *OperatorDelete = 0;
5075 DeclarationName Name =
5076 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5077 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005078 OperatorDelete, false)) {
5079 if (Diagnose)
5080 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005081 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005082 }
Richard Smith9a561d52012-02-26 09:11:52 +00005083 }
5084
Richard Smith6c4c36c2012-03-30 20:53:28 +00005085 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005086
Sean Huntcdee3fe2011-05-11 22:34:38 +00005087 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005088 BE = RD->bases_end(); BI != BE; ++BI)
5089 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005090 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005091 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005092
Richard Smithe0883602013-07-22 18:06:23 +00005093 // Per DR1611, do not consider virtual bases of constructors of abstract
5094 // classes, since we are not going to construct them.
Richard Smithcbc820a2013-07-22 02:56:56 +00005095 if (!RD->isAbstract() || !SMI.IsConstructor) {
5096 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5097 BE = RD->vbases_end();
5098 BI != BE; ++BI)
5099 if (SMI.shouldDeleteForBase(BI))
5100 return true;
5101 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00005102
5103 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005104 FE = RD->field_end(); FI != FE; ++FI)
5105 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005106 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005107 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005108
Richard Smith7d5088a2012-02-18 02:02:13 +00005109 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005110 return true;
5111
5112 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005113}
5114
Richard Smithac713512012-12-08 02:53:02 +00005115/// Perform lookup for a special member of the specified kind, and determine
5116/// whether it is trivial. If the triviality can be determined without the
5117/// lookup, skip it. This is intended for use when determining whether a
5118/// special member of a containing object is trivial, and thus does not ever
5119/// perform overload resolution for default constructors.
5120///
5121/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5122/// member that was most likely to be intended to be trivial, if any.
5123static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5124 Sema::CXXSpecialMember CSM, unsigned Quals,
5125 CXXMethodDecl **Selected) {
5126 if (Selected)
5127 *Selected = 0;
5128
5129 switch (CSM) {
5130 case Sema::CXXInvalid:
5131 llvm_unreachable("not a special member");
5132
5133 case Sema::CXXDefaultConstructor:
5134 // C++11 [class.ctor]p5:
5135 // A default constructor is trivial if:
5136 // - all the [direct subobjects] have trivial default constructors
5137 //
5138 // Note, no overload resolution is performed in this case.
5139 if (RD->hasTrivialDefaultConstructor())
5140 return true;
5141
5142 if (Selected) {
5143 // If there's a default constructor which could have been trivial, dig it
5144 // out. Otherwise, if there's any user-provided default constructor, point
5145 // to that as an example of why there's not a trivial one.
5146 CXXConstructorDecl *DefCtor = 0;
5147 if (RD->needsImplicitDefaultConstructor())
5148 S.DeclareImplicitDefaultConstructor(RD);
5149 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5150 CE = RD->ctor_end(); CI != CE; ++CI) {
5151 if (!CI->isDefaultConstructor())
5152 continue;
5153 DefCtor = *CI;
5154 if (!DefCtor->isUserProvided())
5155 break;
5156 }
5157
5158 *Selected = DefCtor;
5159 }
5160
5161 return false;
5162
5163 case Sema::CXXDestructor:
5164 // C++11 [class.dtor]p5:
5165 // A destructor is trivial if:
5166 // - all the direct [subobjects] have trivial destructors
5167 if (RD->hasTrivialDestructor())
5168 return true;
5169
5170 if (Selected) {
5171 if (RD->needsImplicitDestructor())
5172 S.DeclareImplicitDestructor(RD);
5173 *Selected = RD->getDestructor();
5174 }
5175
5176 return false;
5177
5178 case Sema::CXXCopyConstructor:
5179 // C++11 [class.copy]p12:
5180 // A copy constructor is trivial if:
5181 // - the constructor selected to copy each direct [subobject] is trivial
5182 if (RD->hasTrivialCopyConstructor()) {
5183 if (Quals == Qualifiers::Const)
5184 // We must either select the trivial copy constructor or reach an
5185 // ambiguity; no need to actually perform overload resolution.
5186 return true;
5187 } else if (!Selected) {
5188 return false;
5189 }
5190 // In C++98, we are not supposed to perform overload resolution here, but we
5191 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5192 // cases like B as having a non-trivial copy constructor:
5193 // struct A { template<typename T> A(T&); };
5194 // struct B { mutable A a; };
5195 goto NeedOverloadResolution;
5196
5197 case Sema::CXXCopyAssignment:
5198 // C++11 [class.copy]p25:
5199 // A copy assignment operator is trivial if:
5200 // - the assignment operator selected to copy each direct [subobject] is
5201 // trivial
5202 if (RD->hasTrivialCopyAssignment()) {
5203 if (Quals == Qualifiers::Const)
5204 return true;
5205 } else if (!Selected) {
5206 return false;
5207 }
5208 // In C++98, we are not supposed to perform overload resolution here, but we
5209 // treat that as a language defect.
5210 goto NeedOverloadResolution;
5211
5212 case Sema::CXXMoveConstructor:
5213 case Sema::CXXMoveAssignment:
5214 NeedOverloadResolution:
5215 Sema::SpecialMemberOverloadResult *SMOR =
5216 S.LookupSpecialMember(RD, CSM,
5217 Quals & Qualifiers::Const,
5218 Quals & Qualifiers::Volatile,
5219 /*RValueThis*/false, /*ConstThis*/false,
5220 /*VolatileThis*/false);
5221
5222 // The standard doesn't describe how to behave if the lookup is ambiguous.
5223 // We treat it as not making the member non-trivial, just like the standard
5224 // mandates for the default constructor. This should rarely matter, because
5225 // the member will also be deleted.
5226 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5227 return true;
5228
5229 if (!SMOR->getMethod()) {
5230 assert(SMOR->getKind() ==
5231 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5232 return false;
5233 }
5234
5235 // We deliberately don't check if we found a deleted special member. We're
5236 // not supposed to!
5237 if (Selected)
5238 *Selected = SMOR->getMethod();
5239 return SMOR->getMethod()->isTrivial();
5240 }
5241
5242 llvm_unreachable("unknown special method kind");
5243}
5244
Benjamin Kramera574c892013-02-15 12:30:38 +00005245static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005246 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5247 CI != CE; ++CI)
5248 if (!CI->isImplicit())
5249 return *CI;
5250
5251 // Look for constructor templates.
5252 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5253 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5254 if (CXXConstructorDecl *CD =
5255 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5256 return CD;
5257 }
5258
5259 return 0;
5260}
5261
5262/// The kind of subobject we are checking for triviality. The values of this
5263/// enumeration are used in diagnostics.
5264enum TrivialSubobjectKind {
5265 /// The subobject is a base class.
5266 TSK_BaseClass,
5267 /// The subobject is a non-static data member.
5268 TSK_Field,
5269 /// The object is actually the complete object.
5270 TSK_CompleteObject
5271};
5272
5273/// Check whether the special member selected for a given type would be trivial.
5274static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5275 QualType SubType,
5276 Sema::CXXSpecialMember CSM,
5277 TrivialSubobjectKind Kind,
5278 bool Diagnose) {
5279 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5280 if (!SubRD)
5281 return true;
5282
5283 CXXMethodDecl *Selected;
5284 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5285 Diagnose ? &Selected : 0))
5286 return true;
5287
5288 if (Diagnose) {
5289 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5290 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5291 << Kind << SubType.getUnqualifiedType();
5292 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5293 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5294 } else if (!Selected)
5295 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5296 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5297 else if (Selected->isUserProvided()) {
5298 if (Kind == TSK_CompleteObject)
5299 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5300 << Kind << SubType.getUnqualifiedType() << CSM;
5301 else {
5302 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5303 << Kind << SubType.getUnqualifiedType() << CSM;
5304 S.Diag(Selected->getLocation(), diag::note_declared_at);
5305 }
5306 } else {
5307 if (Kind != TSK_CompleteObject)
5308 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5309 << Kind << SubType.getUnqualifiedType() << CSM;
5310
5311 // Explain why the defaulted or deleted special member isn't trivial.
5312 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5313 }
5314 }
5315
5316 return false;
5317}
5318
5319/// Check whether the members of a class type allow a special member to be
5320/// trivial.
5321static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5322 Sema::CXXSpecialMember CSM,
5323 bool ConstArg, bool Diagnose) {
5324 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5325 FE = RD->field_end(); FI != FE; ++FI) {
5326 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5327 continue;
5328
5329 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5330
5331 // Pretend anonymous struct or union members are members of this class.
5332 if (FI->isAnonymousStructOrUnion()) {
5333 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5334 CSM, ConstArg, Diagnose))
5335 return false;
5336 continue;
5337 }
5338
5339 // C++11 [class.ctor]p5:
5340 // A default constructor is trivial if [...]
5341 // -- no non-static data member of its class has a
5342 // brace-or-equal-initializer
5343 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5344 if (Diagnose)
5345 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5346 return false;
5347 }
5348
5349 // Objective C ARC 4.3.5:
5350 // [...] nontrivally ownership-qualified types are [...] not trivially
5351 // default constructible, copy constructible, move constructible, copy
5352 // assignable, move assignable, or destructible [...]
5353 if (S.getLangOpts().ObjCAutoRefCount &&
5354 FieldType.hasNonTrivialObjCLifetime()) {
5355 if (Diagnose)
5356 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5357 << RD << FieldType.getObjCLifetime();
5358 return false;
5359 }
5360
5361 if (ConstArg && !FI->isMutable())
5362 FieldType.addConst();
5363 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5364 TSK_Field, Diagnose))
5365 return false;
5366 }
5367
5368 return true;
5369}
5370
5371/// Diagnose why the specified class does not have a trivial special member of
5372/// the given kind.
5373void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5374 QualType Ty = Context.getRecordType(RD);
5375 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5376 Ty.addConst();
5377
5378 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5379 TSK_CompleteObject, /*Diagnose*/true);
5380}
5381
5382/// Determine whether a defaulted or deleted special member function is trivial,
5383/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5384/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5385bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5386 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005387 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5388
5389 CXXRecordDecl *RD = MD->getParent();
5390
5391 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005392
5393 // C++11 [class.copy]p12, p25:
5394 // A [special member] is trivial if its declared parameter type is the same
5395 // as if it had been implicitly declared [...]
5396 switch (CSM) {
5397 case CXXDefaultConstructor:
5398 case CXXDestructor:
5399 // Trivial default constructors and destructors cannot have parameters.
5400 break;
5401
5402 case CXXCopyConstructor:
5403 case CXXCopyAssignment: {
5404 // Trivial copy operations always have const, non-volatile parameter types.
5405 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005406 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005407 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5408 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5409 if (Diagnose)
5410 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5411 << Param0->getSourceRange() << Param0->getType()
5412 << Context.getLValueReferenceType(
5413 Context.getRecordType(RD).withConst());
5414 return false;
5415 }
5416 break;
5417 }
5418
5419 case CXXMoveConstructor:
5420 case CXXMoveAssignment: {
5421 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005422 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005423 const RValueReferenceType *RT =
5424 Param0->getType()->getAs<RValueReferenceType>();
5425 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5426 if (Diagnose)
5427 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5428 << Param0->getSourceRange() << Param0->getType()
5429 << Context.getRValueReferenceType(Context.getRecordType(RD));
5430 return false;
5431 }
5432 break;
5433 }
5434
5435 case CXXInvalid:
5436 llvm_unreachable("not a special member");
5437 }
5438
5439 // FIXME: We require that the parameter-declaration-clause is equivalent to
5440 // that of an implicit declaration, not just that the declared parameter type
5441 // matches, in order to prevent absuridities like a function simultaneously
5442 // being a trivial copy constructor and a non-trivial default constructor.
5443 // This issue has not yet been assigned a core issue number.
5444 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5445 if (Diagnose)
5446 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5447 diag::note_nontrivial_default_arg)
5448 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5449 return false;
5450 }
5451 if (MD->isVariadic()) {
5452 if (Diagnose)
5453 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5454 return false;
5455 }
5456
5457 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5458 // A copy/move [constructor or assignment operator] is trivial if
5459 // -- the [member] selected to copy/move each direct base class subobject
5460 // is trivial
5461 //
5462 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5463 // A [default constructor or destructor] is trivial if
5464 // -- all the direct base classes have trivial [default constructors or
5465 // destructors]
5466 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5467 BE = RD->bases_end(); BI != BE; ++BI)
5468 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5469 ConstArg ? BI->getType().withConst()
5470 : BI->getType(),
5471 CSM, TSK_BaseClass, Diagnose))
5472 return false;
5473
5474 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5475 // A copy/move [constructor or assignment operator] for a class X is
5476 // trivial if
5477 // -- for each non-static data member of X that is of class type (or array
5478 // thereof), the constructor selected to copy/move that member is
5479 // trivial
5480 //
5481 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5482 // A [default constructor or destructor] is trivial if
5483 // -- for all of the non-static data members of its class that are of class
5484 // type (or array thereof), each such class has a trivial [default
5485 // constructor or destructor]
5486 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5487 return false;
5488
5489 // C++11 [class.dtor]p5:
5490 // A destructor is trivial if [...]
5491 // -- the destructor is not virtual
5492 if (CSM == CXXDestructor && MD->isVirtual()) {
5493 if (Diagnose)
5494 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5495 return false;
5496 }
5497
5498 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5499 // A [special member] for class X is trivial if [...]
5500 // -- class X has no virtual functions and no virtual base classes
5501 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5502 if (!Diagnose)
5503 return false;
5504
5505 if (RD->getNumVBases()) {
5506 // Check for virtual bases. We already know that the corresponding
5507 // member in all bases is trivial, so vbases must all be direct.
5508 CXXBaseSpecifier &BS = *RD->vbases_begin();
5509 assert(BS.isVirtual());
5510 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5511 return false;
5512 }
5513
5514 // Must have a virtual method.
5515 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5516 ME = RD->method_end(); MI != ME; ++MI) {
5517 if (MI->isVirtual()) {
5518 SourceLocation MLoc = MI->getLocStart();
5519 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5520 return false;
5521 }
5522 }
5523
5524 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5525 }
5526
5527 // Looks like it's trivial!
5528 return true;
5529}
5530
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005531/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005532namespace {
5533 struct FindHiddenVirtualMethodData {
5534 Sema *S;
5535 CXXMethodDecl *Method;
5536 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005537 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005538 };
5539}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005540
David Blaikie5f750682012-10-19 00:53:08 +00005541/// \brief Check whether any most overriden method from MD in Methods
5542static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5543 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5544 if (MD->size_overridden_methods() == 0)
5545 return Methods.count(MD->getCanonicalDecl());
5546 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5547 E = MD->end_overridden_methods();
5548 I != E; ++I)
5549 if (CheckMostOverridenMethods(*I, Methods))
5550 return true;
5551 return false;
5552}
5553
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005554/// \brief Member lookup function that determines whether a given C++
5555/// method overloads virtual methods in a base class without overriding any,
5556/// to be used with CXXRecordDecl::lookupInBases().
5557static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5558 CXXBasePath &Path,
5559 void *UserData) {
5560 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5561
5562 FindHiddenVirtualMethodData &Data
5563 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5564
5565 DeclarationName Name = Data.Method->getDeclName();
5566 assert(Name.getNameKind() == DeclarationName::Identifier);
5567
5568 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005569 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005570 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005571 !Path.Decls.empty();
5572 Path.Decls = Path.Decls.slice(1)) {
5573 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005574 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005575 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005576 foundSameNameMethod = true;
5577 // Interested only in hidden virtual methods.
5578 if (!MD->isVirtual())
5579 continue;
5580 // If the method we are checking overrides a method from its base
5581 // don't warn about the other overloaded methods.
5582 if (!Data.S->IsOverload(Data.Method, MD, false))
5583 return true;
5584 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005585 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005586 overloadedMethods.push_back(MD);
5587 }
5588 }
5589
5590 if (foundSameNameMethod)
5591 Data.OverloadedMethods.append(overloadedMethods.begin(),
5592 overloadedMethods.end());
5593 return foundSameNameMethod;
5594}
5595
David Blaikie5f750682012-10-19 00:53:08 +00005596/// \brief Add the most overriden methods from MD to Methods
5597static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5598 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5599 if (MD->size_overridden_methods() == 0)
5600 Methods.insert(MD->getCanonicalDecl());
5601 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5602 E = MD->end_overridden_methods();
5603 I != E; ++I)
5604 AddMostOverridenMethods(*I, Methods);
5605}
5606
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005607/// \brief See if a method overloads virtual methods in a base class without
5608/// overriding any.
5609void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5610 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005611 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005612 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005613 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005614 return;
5615
5616 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5617 /*bool RecordPaths=*/false,
5618 /*bool DetectVirtual=*/false);
5619 FindHiddenVirtualMethodData Data;
5620 Data.Method = MD;
5621 Data.S = this;
5622
5623 // Keep the base methods that were overriden or introduced in the subclass
5624 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005625 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5626 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5627 NamedDecl *ND = *I;
5628 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005629 ND = shad->getTargetDecl();
5630 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5631 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005632 }
5633
5634 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5635 !Data.OverloadedMethods.empty()) {
5636 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5637 << MD << (Data.OverloadedMethods.size() > 1);
5638
5639 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5640 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005641 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005642 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005643 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5644 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005645 }
5646 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005647}
5648
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005649void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005650 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005651 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005652 SourceLocation RBrac,
5653 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005654 if (!TagDecl)
5655 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005656
Douglas Gregor42af25f2009-05-11 19:58:34 +00005657 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005658
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005659 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5660 if (l->getKind() != AttributeList::AT_Visibility)
5661 continue;
5662 l->setInvalid();
5663 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5664 l->getName();
5665 }
5666
David Blaikie77b6de02011-09-22 02:58:26 +00005667 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005668 // strict aliasing violation!
5669 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005670 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005671
Douglas Gregor23c94db2010-07-02 17:43:08 +00005672 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005673 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005674}
5675
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005676/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5677/// special functions, such as the default constructor, copy
5678/// constructor, or destructor, to the given C++ class (C++
5679/// [special]p1). This routine can only be executed just before the
5680/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005681void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005682 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005683 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005684
Richard Smithbc2a35d2012-12-08 08:32:28 +00005685 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005686 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005687
Richard Smithbc2a35d2012-12-08 08:32:28 +00005688 // If the properties or semantics of the copy constructor couldn't be
5689 // determined while the class was being declared, force a declaration
5690 // of it now.
5691 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5692 DeclareImplicitCopyConstructor(ClassDecl);
5693 }
5694
Richard Smith80ad52f2013-01-02 11:42:31 +00005695 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005696 ++ASTContext::NumImplicitMoveConstructors;
5697
Richard Smithbc2a35d2012-12-08 08:32:28 +00005698 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5699 DeclareImplicitMoveConstructor(ClassDecl);
5700 }
5701
Douglas Gregora376d102010-07-02 21:50:04 +00005702 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5703 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005704
5705 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005706 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005707 // it shows up in the right place in the vtable and that we diagnose
5708 // problems with the implicit exception specification.
5709 if (ClassDecl->isDynamicClass() ||
5710 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005711 DeclareImplicitCopyAssignment(ClassDecl);
5712 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005713
Richard Smith80ad52f2013-01-02 11:42:31 +00005714 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005715 ++ASTContext::NumImplicitMoveAssignmentOperators;
5716
5717 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005718 if (ClassDecl->isDynamicClass() ||
5719 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005720 DeclareImplicitMoveAssignment(ClassDecl);
5721 }
5722
Douglas Gregor4923aa22010-07-02 20:37:36 +00005723 if (!ClassDecl->hasUserDeclaredDestructor()) {
5724 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005725
5726 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005727 // have to declare the destructor immediately. This ensures that, e.g., it
5728 // shows up in the right place in the vtable and that we diagnose problems
5729 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005730 if (ClassDecl->isDynamicClass() ||
5731 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005732 DeclareImplicitDestructor(ClassDecl);
5733 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005734}
5735
Francois Pichet8387e2a2011-04-22 22:18:13 +00005736void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5737 if (!D)
5738 return;
5739
5740 int NumParamList = D->getNumTemplateParameterLists();
5741 for (int i = 0; i < NumParamList; i++) {
5742 TemplateParameterList* Params = D->getTemplateParameterList(i);
5743 for (TemplateParameterList::iterator Param = Params->begin(),
5744 ParamEnd = Params->end();
5745 Param != ParamEnd; ++Param) {
5746 NamedDecl *Named = cast<NamedDecl>(*Param);
5747 if (Named->getDeclName()) {
5748 S->AddDecl(Named);
5749 IdResolver.AddDecl(Named);
5750 }
5751 }
5752 }
5753}
5754
John McCalld226f652010-08-21 09:40:31 +00005755void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005756 if (!D)
5757 return;
5758
5759 TemplateParameterList *Params = 0;
5760 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5761 Params = Template->getTemplateParameters();
5762 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5763 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5764 Params = PartialSpec->getTemplateParameters();
5765 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005766 return;
5767
Douglas Gregor6569d682009-05-27 23:11:45 +00005768 for (TemplateParameterList::iterator Param = Params->begin(),
5769 ParamEnd = Params->end();
5770 Param != ParamEnd; ++Param) {
5771 NamedDecl *Named = cast<NamedDecl>(*Param);
5772 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005773 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005774 IdResolver.AddDecl(Named);
5775 }
5776 }
5777}
5778
John McCalld226f652010-08-21 09:40:31 +00005779void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005780 if (!RecordD) return;
5781 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005782 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005783 PushDeclContext(S, Record);
5784}
5785
John McCalld226f652010-08-21 09:40:31 +00005786void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005787 if (!RecordD) return;
5788 PopDeclContext();
5789}
5790
Douglas Gregor72b505b2008-12-16 21:30:33 +00005791/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5792/// parsing a top-level (non-nested) C++ class, and we are now
5793/// parsing those parts of the given Method declaration that could
5794/// not be parsed earlier (C++ [class.mem]p2), such as default
5795/// arguments. This action should enter the scope of the given
5796/// Method declaration as if we had just parsed the qualified method
5797/// name. However, it should not bring the parameters into scope;
5798/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005799void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005800}
5801
5802/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5803/// C++ method declaration. We're (re-)introducing the given
5804/// function parameter into scope for use in parsing later parts of
5805/// the method declaration. For example, we could see an
5806/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005807void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005808 if (!ParamD)
5809 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005810
John McCalld226f652010-08-21 09:40:31 +00005811 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005812
5813 // If this parameter has an unparsed default argument, clear it out
5814 // to make way for the parsed default argument.
5815 if (Param->hasUnparsedDefaultArg())
5816 Param->setDefaultArg(0);
5817
John McCalld226f652010-08-21 09:40:31 +00005818 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005819 if (Param->getDeclName())
5820 IdResolver.AddDecl(Param);
5821}
5822
5823/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5824/// processing the delayed method declaration for Method. The method
5825/// declaration is now considered finished. There may be a separate
5826/// ActOnStartOfFunctionDef action later (not necessarily
5827/// immediately!) for this method, if it was also defined inside the
5828/// class body.
John McCalld226f652010-08-21 09:40:31 +00005829void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005830 if (!MethodD)
5831 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005832
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005833 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005834
John McCalld226f652010-08-21 09:40:31 +00005835 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005836
5837 // Now that we have our default arguments, check the constructor
5838 // again. It could produce additional diagnostics or affect whether
5839 // the class has implicitly-declared destructors, among other
5840 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005841 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5842 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005843
5844 // Check the default arguments, which we may have added.
5845 if (!Method->isInvalidDecl())
5846 CheckCXXDefaultArguments(Method);
5847}
5848
Douglas Gregor42a552f2008-11-05 20:51:48 +00005849/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005850/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005851/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005852/// emit diagnostics and set the invalid bit to true. In any case, the type
5853/// will be updated to reflect a well-formed type for the constructor and
5854/// returned.
5855QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005856 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005857 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005858
5859 // C++ [class.ctor]p3:
5860 // A constructor shall not be virtual (10.3) or static (9.4). A
5861 // constructor can be invoked for a const, volatile or const
5862 // volatile object. A constructor shall not be declared const,
5863 // volatile, or const volatile (9.3.2).
5864 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005865 if (!D.isInvalidType())
5866 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5867 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5868 << SourceRange(D.getIdentifierLoc());
5869 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005870 }
John McCalld931b082010-08-26 03:08:43 +00005871 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005872 if (!D.isInvalidType())
5873 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5874 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5875 << SourceRange(D.getIdentifierLoc());
5876 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005877 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005878 }
Mike Stump1eb44332009-09-09 15:08:12 +00005879
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005880 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005881 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005882 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005883 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5884 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005885 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005886 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5887 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005888 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005889 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5890 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005891 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005892 }
Mike Stump1eb44332009-09-09 15:08:12 +00005893
Douglas Gregorc938c162011-01-26 05:01:58 +00005894 // C++0x [class.ctor]p4:
5895 // A constructor shall not be declared with a ref-qualifier.
5896 if (FTI.hasRefQualifier()) {
5897 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5898 << FTI.RefQualifierIsLValueRef
5899 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5900 D.setInvalidType();
5901 }
5902
Douglas Gregor42a552f2008-11-05 20:51:48 +00005903 // Rebuild the function type "R" without any type qualifiers (in
5904 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005905 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005906 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005907 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5908 return R;
5909
5910 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5911 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005912 EPI.RefQualifier = RQ_None;
5913
Richard Smith07b0fdc2013-03-18 21:12:30 +00005914 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005915}
5916
Douglas Gregor72b505b2008-12-16 21:30:33 +00005917/// CheckConstructor - Checks a fully-formed constructor for
5918/// well-formedness, issuing any diagnostics required. Returns true if
5919/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005920void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005921 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005922 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5923 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005924 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005925
5926 // C++ [class.copy]p3:
5927 // A declaration of a constructor for a class X is ill-formed if
5928 // its first parameter is of type (optionally cv-qualified) X and
5929 // either there are no other parameters or else all other
5930 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005931 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005932 ((Constructor->getNumParams() == 1) ||
5933 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005934 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5935 Constructor->getTemplateSpecializationKind()
5936 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005937 QualType ParamType = Constructor->getParamDecl(0)->getType();
5938 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5939 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005940 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005941 const char *ConstRef
5942 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5943 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005944 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005945 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005946
5947 // FIXME: Rather that making the constructor invalid, we should endeavor
5948 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005949 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005950 }
5951 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005952}
5953
John McCall15442822010-08-04 01:04:25 +00005954/// CheckDestructor - Checks a fully-formed destructor definition for
5955/// well-formedness, issuing any diagnostics required. Returns true
5956/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005957bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005958 CXXRecordDecl *RD = Destructor->getParent();
5959
Peter Collingbournef51cfb82013-05-20 14:12:25 +00005960 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005961 SourceLocation Loc;
5962
5963 if (!Destructor->isImplicit())
5964 Loc = Destructor->getLocation();
5965 else
5966 Loc = RD->getLocation();
5967
5968 // If we have a virtual destructor, look up the deallocation function
5969 FunctionDecl *OperatorDelete = 0;
5970 DeclarationName Name =
5971 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005972 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005973 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005974
Eli Friedman5f2987c2012-02-02 03:46:19 +00005975 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005976
5977 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005978 }
Anders Carlsson37909802009-11-30 21:24:50 +00005979
5980 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005981}
5982
Mike Stump1eb44332009-09-09 15:08:12 +00005983static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005984FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5985 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5986 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005987 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005988}
5989
Douglas Gregor42a552f2008-11-05 20:51:48 +00005990/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5991/// the well-formednes of the destructor declarator @p D with type @p
5992/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005993/// emit diagnostics and set the declarator to invalid. Even if this happens,
5994/// will be updated to reflect a well-formed type for the destructor and
5995/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005996QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005997 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005998 // C++ [class.dtor]p1:
5999 // [...] A typedef-name that names a class is a class-name
6000 // (7.1.3); however, a typedef-name that names a class shall not
6001 // be used as the identifier in the declarator for a destructor
6002 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006003 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00006004 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00006005 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00006006 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00006007 else if (const TemplateSpecializationType *TST =
6008 DeclaratorType->getAs<TemplateSpecializationType>())
6009 if (TST->isTypeAlias())
6010 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6011 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006012
6013 // C++ [class.dtor]p2:
6014 // A destructor is used to destroy objects of its class type. A
6015 // destructor takes no parameters, and no return type can be
6016 // specified for it (not even void). The address of a destructor
6017 // shall not be taken. A destructor shall not be static. A
6018 // destructor can be invoked for a const, volatile or const
6019 // volatile object. A destructor shall not be declared const,
6020 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00006021 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006022 if (!D.isInvalidType())
6023 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6024 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00006025 << SourceRange(D.getIdentifierLoc())
6026 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6027
John McCalld931b082010-08-26 03:08:43 +00006028 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006029 }
Chris Lattner65401802009-04-25 08:28:21 +00006030 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006031 // Destructors don't have return types, but the parser will
6032 // happily parse something like:
6033 //
6034 // class X {
6035 // float ~X();
6036 // };
6037 //
6038 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006039 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6040 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6041 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00006042 }
Mike Stump1eb44332009-09-09 15:08:12 +00006043
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006044 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006045 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006046 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006047 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6048 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006049 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006050 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6051 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006052 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006053 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6054 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006055 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006056 }
6057
Douglas Gregorc938c162011-01-26 05:01:58 +00006058 // C++0x [class.dtor]p2:
6059 // A destructor shall not be declared with a ref-qualifier.
6060 if (FTI.hasRefQualifier()) {
6061 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6062 << FTI.RefQualifierIsLValueRef
6063 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6064 D.setInvalidType();
6065 }
6066
Douglas Gregor42a552f2008-11-05 20:51:48 +00006067 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006068 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006069 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6070
6071 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006072 FTI.freeArgs();
6073 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006074 }
6075
Mike Stump1eb44332009-09-09 15:08:12 +00006076 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006077 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006078 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006079 D.setInvalidType();
6080 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006081
6082 // Rebuild the function type "R" without any type qualifiers or
6083 // parameters (in case any of the errors above fired) and with
6084 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006085 // types.
John McCalle23cf432010-12-14 08:05:40 +00006086 if (!D.isInvalidType())
6087 return R;
6088
Douglas Gregord92ec472010-07-01 05:10:53 +00006089 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006090 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6091 EPI.Variadic = false;
6092 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006093 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006094 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006095}
6096
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006097/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6098/// well-formednes of the conversion function declarator @p D with
6099/// type @p R. If there are any errors in the declarator, this routine
6100/// will emit diagnostics and return true. Otherwise, it will return
6101/// false. Either way, the type @p R will be updated to reflect a
6102/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006103void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006104 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006105 // C++ [class.conv.fct]p1:
6106 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006107 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006108 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006109 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006110 if (!D.isInvalidType())
6111 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006112 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6113 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006114 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006115 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006116 }
John McCalla3f81372010-04-13 00:04:31 +00006117
6118 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6119
Chris Lattner6e475012009-04-25 08:35:12 +00006120 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006121 // Conversion functions don't have return types, but the parser will
6122 // happily parse something like:
6123 //
6124 // class X {
6125 // float operator bool();
6126 // };
6127 //
6128 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006129 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6130 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6131 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006132 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006133 }
6134
John McCalla3f81372010-04-13 00:04:31 +00006135 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6136
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006137 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006138 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006139 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6140
6141 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006142 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006143 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006144 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006145 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006146 D.setInvalidType();
6147 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006148
John McCalla3f81372010-04-13 00:04:31 +00006149 // Diagnose "&operator bool()" and other such nonsense. This
6150 // is actually a gcc extension which we don't support.
6151 if (Proto->getResultType() != ConvType) {
6152 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6153 << Proto->getResultType();
6154 D.setInvalidType();
6155 ConvType = Proto->getResultType();
6156 }
6157
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006158 // C++ [class.conv.fct]p4:
6159 // The conversion-type-id shall not represent a function type nor
6160 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006161 if (ConvType->isArrayType()) {
6162 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6163 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006164 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006165 } else if (ConvType->isFunctionType()) {
6166 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6167 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006168 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006169 }
6170
6171 // Rebuild the function type "R" without any parameters (in case any
6172 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006173 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006174 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006175 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006176
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006177 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006178 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006179 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006180 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006181 diag::warn_cxx98_compat_explicit_conversion_functions :
6182 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006183 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006184}
6185
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006186/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6187/// the declaration of the given C++ conversion function. This routine
6188/// is responsible for recording the conversion function in the C++
6189/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006190Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006191 assert(Conversion && "Expected to receive a conversion function declaration");
6192
Douglas Gregor9d350972008-12-12 08:25:50 +00006193 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006194
6195 // Make sure we aren't redeclaring the conversion function.
6196 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006197
6198 // C++ [class.conv.fct]p1:
6199 // [...] A conversion function is never used to convert a
6200 // (possibly cv-qualified) object to the (possibly cv-qualified)
6201 // same object type (or a reference to it), to a (possibly
6202 // cv-qualified) base class of that type (or a reference to it),
6203 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006204 // FIXME: Suppress this warning if the conversion function ends up being a
6205 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006206 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006207 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006208 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006209 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006210 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6211 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006212 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006213 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006214 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6215 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006216 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006217 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006218 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006219 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006220 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006221 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006222 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006223 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006224 }
6225
Douglas Gregore80622f2010-09-29 04:25:11 +00006226 if (FunctionTemplateDecl *ConversionTemplate
6227 = Conversion->getDescribedFunctionTemplate())
6228 return ConversionTemplate;
6229
John McCalld226f652010-08-21 09:40:31 +00006230 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006231}
6232
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006233//===----------------------------------------------------------------------===//
6234// Namespace Handling
6235//===----------------------------------------------------------------------===//
6236
Richard Smithd1a55a62012-10-04 22:13:39 +00006237/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6238/// reopened.
6239static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6240 SourceLocation Loc,
6241 IdentifierInfo *II, bool *IsInline,
6242 NamespaceDecl *PrevNS) {
6243 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006244
Richard Smithc969e6a2012-10-05 01:46:25 +00006245 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6246 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6247 // inline namespaces, with the intention of bringing names into namespace std.
6248 //
6249 // We support this just well enough to get that case working; this is not
6250 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006251 if (*IsInline && II && II->getName().startswith("__atomic") &&
6252 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006253 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006254 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6255 NS = NS->getPreviousDecl())
6256 NS->setInline(*IsInline);
6257 // Patch up the lookup table for the containing namespace. This isn't really
6258 // correct, but it's good enough for this particular case.
6259 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6260 E = PrevNS->decls_end(); I != E; ++I)
6261 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6262 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6263 return;
6264 }
6265
6266 if (PrevNS->isInline())
6267 // The user probably just forgot the 'inline', so suggest that it
6268 // be added back.
6269 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6270 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6271 else
6272 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6273 << IsInline;
6274
6275 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6276 *IsInline = PrevNS->isInline();
6277}
John McCallea318642010-08-26 09:15:37 +00006278
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006279/// ActOnStartNamespaceDef - This is called at the start of a namespace
6280/// definition.
John McCalld226f652010-08-21 09:40:31 +00006281Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006282 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006283 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006284 SourceLocation IdentLoc,
6285 IdentifierInfo *II,
6286 SourceLocation LBrace,
6287 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006288 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6289 // For anonymous namespace, take the location of the left brace.
6290 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006291 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006292 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006293 bool IsStd = false;
6294 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006295 Scope *DeclRegionScope = NamespcScope->getParent();
6296
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006297 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006298 if (II) {
6299 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006300 // The identifier in an original-namespace-definition shall not
6301 // have been previously defined in the declarative region in
6302 // which the original-namespace-definition appears. The
6303 // identifier in an original-namespace-definition is the name of
6304 // the namespace. Subsequently in that declarative region, it is
6305 // treated as an original-namespace-name.
6306 //
6307 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006308 // look through using directives, just look for any ordinary names.
6309
6310 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006311 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6312 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006313 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006314 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6315 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6316 ++I) {
6317 if ((*I)->getIdentifierNamespace() & IDNS) {
6318 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006319 break;
6320 }
6321 }
6322
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006323 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6324
6325 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006326 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006327 if (IsInline != PrevNS->isInline())
6328 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6329 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006330 } else if (PrevDecl) {
6331 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006332 Diag(Loc, diag::err_redefinition_different_kind)
6333 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006334 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006335 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006336 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006337 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006338 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006339 // This is the first "real" definition of the namespace "std", so update
6340 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006341 PrevNS = getStdNamespace();
6342 IsStd = true;
6343 AddToKnown = !IsInline;
6344 } else {
6345 // We've seen this namespace for the first time.
6346 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006347 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006348 } else {
John McCall9aeed322009-10-01 00:25:31 +00006349 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006350
6351 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006352 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006353 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006354 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006355 } else {
6356 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006357 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006358 }
6359
Richard Smithd1a55a62012-10-04 22:13:39 +00006360 if (PrevNS && IsInline != PrevNS->isInline())
6361 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6362 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006363 }
6364
6365 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6366 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006367 if (IsInvalid)
6368 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006369
6370 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006371
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006372 // FIXME: Should we be merging attributes?
6373 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006374 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006375
6376 if (IsStd)
6377 StdNamespace = Namespc;
6378 if (AddToKnown)
6379 KnownNamespaces[Namespc] = false;
6380
6381 if (II) {
6382 PushOnScopeChains(Namespc, DeclRegionScope);
6383 } else {
6384 // Link the anonymous namespace into its parent.
6385 DeclContext *Parent = CurContext->getRedeclContext();
6386 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6387 TU->setAnonymousNamespace(Namespc);
6388 } else {
6389 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006390 }
John McCall9aeed322009-10-01 00:25:31 +00006391
Douglas Gregora4181472010-03-24 00:46:35 +00006392 CurContext->addDecl(Namespc);
6393
John McCall9aeed322009-10-01 00:25:31 +00006394 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6395 // behaves as if it were replaced by
6396 // namespace unique { /* empty body */ }
6397 // using namespace unique;
6398 // namespace unique { namespace-body }
6399 // where all occurrences of 'unique' in a translation unit are
6400 // replaced by the same identifier and this identifier differs
6401 // from all other identifiers in the entire program.
6402
6403 // We just create the namespace with an empty name and then add an
6404 // implicit using declaration, just like the standard suggests.
6405 //
6406 // CodeGen enforces the "universally unique" aspect by giving all
6407 // declarations semantically contained within an anonymous
6408 // namespace internal linkage.
6409
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006410 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006411 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006412 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006413 /* 'using' */ LBrace,
6414 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006415 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006416 /* identifier */ SourceLocation(),
6417 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006418 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006419 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006420 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006421 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006422 }
6423
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006424 ActOnDocumentableDecl(Namespc);
6425
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006426 // Although we could have an invalid decl (i.e. the namespace name is a
6427 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006428 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6429 // for the namespace has the declarations that showed up in that particular
6430 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006431 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006432 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006433}
6434
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006435/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6436/// is a namespace alias, returns the namespace it points to.
6437static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6438 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6439 return AD->getNamespace();
6440 return dyn_cast_or_null<NamespaceDecl>(D);
6441}
6442
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006443/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6444/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006445void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006446 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6447 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006448 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006449 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006450 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006451 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006452}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006453
John McCall384aff82010-08-25 07:42:41 +00006454CXXRecordDecl *Sema::getStdBadAlloc() const {
6455 return cast_or_null<CXXRecordDecl>(
6456 StdBadAlloc.get(Context.getExternalSource()));
6457}
6458
6459NamespaceDecl *Sema::getStdNamespace() const {
6460 return cast_or_null<NamespaceDecl>(
6461 StdNamespace.get(Context.getExternalSource()));
6462}
6463
Douglas Gregor66992202010-06-29 17:53:46 +00006464/// \brief Retrieve the special "std" namespace, which may require us to
6465/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006466NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006467 if (!StdNamespace) {
6468 // The "std" namespace has not yet been defined, so build one implicitly.
6469 StdNamespace = NamespaceDecl::Create(Context,
6470 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006471 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006472 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006473 &PP.getIdentifierTable().get("std"),
6474 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006475 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006476 }
6477
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006478 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006479}
6480
Sebastian Redl395e04d2012-01-17 22:49:33 +00006481bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006482 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006483 "Looking for std::initializer_list outside of C++.");
6484
6485 // We're looking for implicit instantiations of
6486 // template <typename E> class std::initializer_list.
6487
6488 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6489 return false;
6490
Sebastian Redl84760e32012-01-17 22:49:58 +00006491 ClassTemplateDecl *Template = 0;
6492 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006493
Sebastian Redl84760e32012-01-17 22:49:58 +00006494 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006495
Sebastian Redl84760e32012-01-17 22:49:58 +00006496 ClassTemplateSpecializationDecl *Specialization =
6497 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6498 if (!Specialization)
6499 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006500
Sebastian Redl84760e32012-01-17 22:49:58 +00006501 Template = Specialization->getSpecializedTemplate();
6502 Arguments = Specialization->getTemplateArgs().data();
6503 } else if (const TemplateSpecializationType *TST =
6504 Ty->getAs<TemplateSpecializationType>()) {
6505 Template = dyn_cast_or_null<ClassTemplateDecl>(
6506 TST->getTemplateName().getAsTemplateDecl());
6507 Arguments = TST->getArgs();
6508 }
6509 if (!Template)
6510 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006511
6512 if (!StdInitializerList) {
6513 // Haven't recognized std::initializer_list yet, maybe this is it.
6514 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6515 if (TemplateClass->getIdentifier() !=
6516 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006517 !getStdNamespace()->InEnclosingNamespaceSetOf(
6518 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006519 return false;
6520 // This is a template called std::initializer_list, but is it the right
6521 // template?
6522 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006523 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006524 return false;
6525 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6526 return false;
6527
6528 // It's the right template.
6529 StdInitializerList = Template;
6530 }
6531
6532 if (Template != StdInitializerList)
6533 return false;
6534
6535 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006536 if (Element)
6537 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006538 return true;
6539}
6540
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006541static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6542 NamespaceDecl *Std = S.getStdNamespace();
6543 if (!Std) {
6544 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6545 return 0;
6546 }
6547
6548 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6549 Loc, Sema::LookupOrdinaryName);
6550 if (!S.LookupQualifiedName(Result, Std)) {
6551 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6552 return 0;
6553 }
6554 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6555 if (!Template) {
6556 Result.suppressDiagnostics();
6557 // We found something weird. Complain about the first thing we found.
6558 NamedDecl *Found = *Result.begin();
6559 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6560 return 0;
6561 }
6562
6563 // We found some template called std::initializer_list. Now verify that it's
6564 // correct.
6565 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006566 if (Params->getMinRequiredArguments() != 1 ||
6567 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006568 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6569 return 0;
6570 }
6571
6572 return Template;
6573}
6574
6575QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6576 if (!StdInitializerList) {
6577 StdInitializerList = LookupStdInitializerList(*this, Loc);
6578 if (!StdInitializerList)
6579 return QualType();
6580 }
6581
6582 TemplateArgumentListInfo Args(Loc, Loc);
6583 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6584 Context.getTrivialTypeSourceInfo(Element,
6585 Loc)));
6586 return Context.getCanonicalType(
6587 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6588}
6589
Sebastian Redl98d36062012-01-17 22:50:14 +00006590bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6591 // C++ [dcl.init.list]p2:
6592 // A constructor is an initializer-list constructor if its first parameter
6593 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6594 // std::initializer_list<E> for some type E, and either there are no other
6595 // parameters or else all other parameters have default arguments.
6596 if (Ctor->getNumParams() < 1 ||
6597 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6598 return false;
6599
6600 QualType ArgType = Ctor->getParamDecl(0)->getType();
6601 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6602 ArgType = RT->getPointeeType().getUnqualifiedType();
6603
6604 return isStdInitializerList(ArgType, 0);
6605}
6606
Douglas Gregor9172aa62011-03-26 22:25:30 +00006607/// \brief Determine whether a using statement is in a context where it will be
6608/// apply in all contexts.
6609static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6610 switch (CurContext->getDeclKind()) {
6611 case Decl::TranslationUnit:
6612 return true;
6613 case Decl::LinkageSpec:
6614 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6615 default:
6616 return false;
6617 }
6618}
6619
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006620namespace {
6621
6622// Callback to only accept typo corrections that are namespaces.
6623class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00006624public:
6625 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6626 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006627 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006628 return false;
6629 }
6630};
6631
6632}
6633
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006634static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6635 CXXScopeSpec &SS,
6636 SourceLocation IdentLoc,
6637 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006638 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006639 R.clear();
6640 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006641 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006642 Validator)) {
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006643 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +00006644 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6645 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006646 Ident->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +00006647 S.diagnoseTypo(Corrected,
6648 S.PDiag(diag::err_using_directive_member_suggest)
6649 << Ident << DC << DroppedSpecifier << SS.getRange(),
6650 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006651 } else {
Richard Smith2d670972013-08-17 00:46:16 +00006652 S.diagnoseTypo(Corrected,
6653 S.PDiag(diag::err_using_directive_suggest) << Ident,
6654 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006655 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006656 R.addDecl(Corrected.getCorrectionDecl());
6657 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006658 }
6659 return false;
6660}
6661
John McCalld226f652010-08-21 09:40:31 +00006662Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006663 SourceLocation UsingLoc,
6664 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006665 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006666 SourceLocation IdentLoc,
6667 IdentifierInfo *NamespcName,
6668 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006669 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6670 assert(NamespcName && "Invalid NamespcName.");
6671 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006672
6673 // This can only happen along a recovery path.
6674 while (S->getFlags() & Scope::TemplateParamScope)
6675 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006676 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006677
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006678 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006679 NestedNameSpecifier *Qualifier = 0;
6680 if (SS.isSet())
6681 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6682
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006683 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006684 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6685 LookupParsedName(R, S, &SS);
6686 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006687 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006688
Douglas Gregor66992202010-06-29 17:53:46 +00006689 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006690 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006691 // Allow "using namespace std;" or "using namespace ::std;" even if
6692 // "std" hasn't been defined yet, for GCC compatibility.
6693 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6694 NamespcName->isStr("std")) {
6695 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006696 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006697 R.resolveKind();
6698 }
6699 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006700 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006701 }
6702
John McCallf36e02d2009-10-09 21:13:30 +00006703 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006704 NamedDecl *Named = R.getFoundDecl();
6705 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6706 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006707 // C++ [namespace.udir]p1:
6708 // A using-directive specifies that the names in the nominated
6709 // namespace can be used in the scope in which the
6710 // using-directive appears after the using-directive. During
6711 // unqualified name lookup (3.4.1), the names appear as if they
6712 // were declared in the nearest enclosing namespace which
6713 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006714 // namespace. [Note: in this context, "contains" means "contains
6715 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006716
6717 // Find enclosing context containing both using-directive and
6718 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006719 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006720 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6721 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6722 CommonAncestor = CommonAncestor->getParent();
6723
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006724 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006725 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006726 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006727
Douglas Gregor9172aa62011-03-26 22:25:30 +00006728 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman24146972013-08-22 00:27:10 +00006729 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006730 Diag(IdentLoc, diag::warn_using_directive_in_header);
6731 }
6732
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006733 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006734 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006735 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006736 }
6737
Richard Smith6b3d3e52013-02-20 19:22:51 +00006738 if (UDir)
6739 ProcessDeclAttributeList(S, UDir, AttrList);
6740
John McCalld226f652010-08-21 09:40:31 +00006741 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006742}
6743
6744void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006745 // If the scope has an associated entity and the using directive is at
6746 // namespace or translation unit scope, add the UsingDirectiveDecl into
6747 // its lookup structure so qualified name lookup can find it.
6748 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6749 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006750 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006751 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006752 // Otherwise, it is at block sope. The using-directives will affect lookup
6753 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006754 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006755}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006756
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006757
John McCalld226f652010-08-21 09:40:31 +00006758Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006759 AccessSpecifier AS,
6760 bool HasUsingKeyword,
6761 SourceLocation UsingLoc,
6762 CXXScopeSpec &SS,
6763 UnqualifiedId &Name,
6764 AttributeList *AttrList,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00006765 bool HasTypenameKeyword,
John McCall78b81052010-11-10 02:40:36 +00006766 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006767 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006768
Douglas Gregor12c118a2009-11-04 16:30:06 +00006769 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006770 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006771 case UnqualifiedId::IK_Identifier:
6772 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006773 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006774 case UnqualifiedId::IK_ConversionFunctionId:
6775 break;
6776
6777 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006778 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006779 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006780 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006781 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006782 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006783 diag::err_using_decl_constructor)
6784 << SS.getRange();
6785
Richard Smith80ad52f2013-01-02 11:42:31 +00006786 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006787
John McCalld226f652010-08-21 09:40:31 +00006788 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006789
6790 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006791 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006792 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006793 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006794
6795 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006796 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006797 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006798 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006799 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006800
6801 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6802 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006803 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006804 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006805
Richard Smith07b0fdc2013-03-18 21:12:30 +00006806 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006807 if (!HasUsingKeyword) {
Enea Zaffanellad4de59d2013-07-17 17:28:56 +00006808 Diag(Name.getLocStart(),
Richard Smith1b2209f2013-06-13 02:12:17 +00006809 getLangOpts().CPlusPlus11 ? diag::err_access_decl
6810 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006811 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006812 }
6813
Douglas Gregor56c04582010-12-16 00:46:58 +00006814 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6815 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6816 return 0;
6817
John McCall9488ea12009-11-17 05:59:44 +00006818 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006819 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006820 /* IsInstantiation */ false,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00006821 HasTypenameKeyword, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006822 if (UD)
6823 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006824
John McCalld226f652010-08-21 09:40:31 +00006825 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006826}
6827
Douglas Gregor09acc982010-07-07 23:08:52 +00006828/// \brief Determine whether a using declaration considers the given
6829/// declarations as "equivalent", e.g., if they are redeclarations of
6830/// the same entity or are both typedefs of the same type.
6831static bool
6832IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6833 bool &SuppressRedeclaration) {
6834 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6835 SuppressRedeclaration = false;
6836 return true;
6837 }
6838
Richard Smith162e1c12011-04-15 14:24:37 +00006839 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6840 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006841 SuppressRedeclaration = true;
6842 return Context.hasSameType(TD1->getUnderlyingType(),
6843 TD2->getUnderlyingType());
6844 }
6845
6846 return false;
6847}
6848
6849
John McCall9f54ad42009-12-10 09:41:52 +00006850/// Determines whether to create a using shadow decl for a particular
6851/// decl, given the set of decls existing prior to this using lookup.
6852bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6853 const LookupResult &Previous) {
6854 // Diagnose finding a decl which is not from a base class of the
6855 // current class. We do this now because there are cases where this
6856 // function will silently decide not to build a shadow decl, which
6857 // will pre-empt further diagnostics.
6858 //
6859 // We don't need to do this in C++0x because we do the check once on
6860 // the qualifier.
6861 //
6862 // FIXME: diagnose the following if we care enough:
6863 // struct A { int foo; };
6864 // struct B : A { using A::foo; };
6865 // template <class T> struct C : A {};
6866 // template <class T> struct D : C<T> { using B::foo; } // <---
6867 // This is invalid (during instantiation) in C++03 because B::foo
6868 // resolves to the using decl in B, which is not a base class of D<T>.
6869 // We can't diagnose it immediately because C<T> is an unknown
6870 // specialization. The UsingShadowDecl in D<T> then points directly
6871 // to A::foo, which will look well-formed when we instantiate.
6872 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006873 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006874 DeclContext *OrigDC = Orig->getDeclContext();
6875
6876 // Handle enums and anonymous structs.
6877 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6878 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6879 while (OrigRec->isAnonymousStructOrUnion())
6880 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6881
6882 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6883 if (OrigDC == CurContext) {
6884 Diag(Using->getLocation(),
6885 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006886 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006887 Diag(Orig->getLocation(), diag::note_using_decl_target);
6888 return true;
6889 }
6890
Douglas Gregordc355712011-02-25 00:36:19 +00006891 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006892 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006893 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006894 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006895 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006896 Diag(Orig->getLocation(), diag::note_using_decl_target);
6897 return true;
6898 }
6899 }
6900
6901 if (Previous.empty()) return false;
6902
6903 NamedDecl *Target = Orig;
6904 if (isa<UsingShadowDecl>(Target))
6905 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6906
John McCalld7533ec2009-12-11 02:33:26 +00006907 // If the target happens to be one of the previous declarations, we
6908 // don't have a conflict.
6909 //
6910 // FIXME: but we might be increasing its access, in which case we
6911 // should redeclare it.
6912 NamedDecl *NonTag = 0, *Tag = 0;
6913 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6914 I != E; ++I) {
6915 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006916 bool Result;
6917 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6918 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006919
6920 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6921 }
6922
John McCall9f54ad42009-12-10 09:41:52 +00006923 if (Target->isFunctionOrFunctionTemplate()) {
6924 FunctionDecl *FD;
6925 if (isa<FunctionTemplateDecl>(Target))
6926 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6927 else
6928 FD = cast<FunctionDecl>(Target);
6929
6930 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006931 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006932 case Ovl_Overload:
6933 return false;
6934
6935 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006936 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006937 break;
6938
6939 // We found a decl with the exact signature.
6940 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006941 // If we're in a record, we want to hide the target, so we
6942 // return true (without a diagnostic) to tell the caller not to
6943 // build a shadow decl.
6944 if (CurContext->isRecord())
6945 return true;
6946
6947 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006948 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006949 break;
6950 }
6951
6952 Diag(Target->getLocation(), diag::note_using_decl_target);
6953 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6954 return true;
6955 }
6956
6957 // Target is not a function.
6958
John McCall9f54ad42009-12-10 09:41:52 +00006959 if (isa<TagDecl>(Target)) {
6960 // No conflict between a tag and a non-tag.
6961 if (!Tag) return false;
6962
John McCall41ce66f2009-12-10 19:51:03 +00006963 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006964 Diag(Target->getLocation(), diag::note_using_decl_target);
6965 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6966 return true;
6967 }
6968
6969 // No conflict between a tag and a non-tag.
6970 if (!NonTag) return false;
6971
John McCall41ce66f2009-12-10 19:51:03 +00006972 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006973 Diag(Target->getLocation(), diag::note_using_decl_target);
6974 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6975 return true;
6976}
6977
John McCall9488ea12009-11-17 05:59:44 +00006978/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006979UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006980 UsingDecl *UD,
6981 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006982
6983 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006984 NamedDecl *Target = Orig;
6985 if (isa<UsingShadowDecl>(Target)) {
6986 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6987 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006988 }
6989
6990 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006991 = UsingShadowDecl::Create(Context, CurContext,
6992 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006993 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006994
6995 Shadow->setAccess(UD->getAccess());
6996 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6997 Shadow->setInvalidDecl();
6998
John McCall9488ea12009-11-17 05:59:44 +00006999 if (S)
John McCall604e7f12009-12-08 07:46:18 +00007000 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00007001 else
John McCall604e7f12009-12-08 07:46:18 +00007002 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00007003
John McCall604e7f12009-12-08 07:46:18 +00007004
John McCall9f54ad42009-12-10 09:41:52 +00007005 return Shadow;
7006}
John McCall604e7f12009-12-08 07:46:18 +00007007
John McCall9f54ad42009-12-10 09:41:52 +00007008/// Hides a using shadow declaration. This is required by the current
7009/// using-decl implementation when a resolvable using declaration in a
7010/// class is followed by a declaration which would hide or override
7011/// one or more of the using decl's targets; for example:
7012///
7013/// struct Base { void foo(int); };
7014/// struct Derived : Base {
7015/// using Base::foo;
7016/// void foo(int);
7017/// };
7018///
7019/// The governing language is C++03 [namespace.udecl]p12:
7020///
7021/// When a using-declaration brings names from a base class into a
7022/// derived class scope, member functions in the derived class
7023/// override and/or hide member functions with the same name and
7024/// parameter types in a base class (rather than conflicting).
7025///
7026/// There are two ways to implement this:
7027/// (1) optimistically create shadow decls when they're not hidden
7028/// by existing declarations, or
7029/// (2) don't create any shadow decls (or at least don't make them
7030/// visible) until we've fully parsed/instantiated the class.
7031/// The problem with (1) is that we might have to retroactively remove
7032/// a shadow decl, which requires several O(n) operations because the
7033/// decl structures are (very reasonably) not designed for removal.
7034/// (2) avoids this but is very fiddly and phase-dependent.
7035void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00007036 if (Shadow->getDeclName().getNameKind() ==
7037 DeclarationName::CXXConversionFunctionName)
7038 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7039
John McCall9f54ad42009-12-10 09:41:52 +00007040 // Remove it from the DeclContext...
7041 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007042
John McCall9f54ad42009-12-10 09:41:52 +00007043 // ...and the scope, if applicable...
7044 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007045 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007046 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007047 }
7048
John McCall9f54ad42009-12-10 09:41:52 +00007049 // ...and the using decl.
7050 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7051
7052 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007053 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007054}
7055
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007056namespace {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007057class UsingValidatorCCC : public CorrectionCandidateCallback {
7058public:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007059 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation)
7060 : HasTypenameKeyword(HasTypenameKeyword),
7061 IsInstantiation(IsInstantiation) {}
7062
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007063 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7064 NamedDecl *ND = Candidate.getCorrectionDecl();
7065
7066 // Keywords are not valid here.
7067 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007068 return false;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007069
7070 // Completely unqualified names are invalid for a 'using' declaration.
7071 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7072 return false;
7073
7074 if (isa<TypeDecl>(ND))
7075 return HasTypenameKeyword || !IsInstantiation;
7076
7077 return !HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007078 }
7079
7080private:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007081 bool HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007082 bool IsInstantiation;
7083};
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007084} // end anonymous namespace
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007085
John McCall7ba107a2009-11-18 02:36:19 +00007086/// Builds a using declaration.
7087///
7088/// \param IsInstantiation - Whether this call arises from an
7089/// instantiation of an unresolved using declaration. We treat
7090/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007091NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7092 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007093 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007094 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007095 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007096 bool IsInstantiation,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007097 bool HasTypenameKeyword,
John McCall7ba107a2009-11-18 02:36:19 +00007098 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007099 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007100 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007101 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007102
Anders Carlsson550b14b2009-08-28 05:49:21 +00007103 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007104
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007105 if (SS.isEmpty()) {
7106 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007107 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007108 }
Mike Stump1eb44332009-09-09 15:08:12 +00007109
John McCall9f54ad42009-12-10 09:41:52 +00007110 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007111 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007112 ForRedeclaration);
7113 Previous.setHideTags(false);
7114 if (S) {
7115 LookupName(Previous, S);
7116
7117 // It is really dumb that we have to do this.
7118 LookupResult::Filter F = Previous.makeFilter();
7119 while (F.hasNext()) {
7120 NamedDecl *D = F.next();
7121 if (!isDeclInScope(D, CurContext, S))
7122 F.erase();
7123 }
7124 F.done();
7125 } else {
7126 assert(IsInstantiation && "no scope in non-instantiation");
7127 assert(CurContext->isRecord() && "scope not record in instantiation");
7128 LookupQualifiedName(Previous, CurContext);
7129 }
7130
John McCall9f54ad42009-12-10 09:41:52 +00007131 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007132 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7133 SS, IdentLoc, Previous))
John McCall9f54ad42009-12-10 09:41:52 +00007134 return 0;
7135
7136 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007137 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7138 return 0;
7139
John McCallaf8e6ed2009-11-12 03:15:40 +00007140 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007141 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007142 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007143 if (!LookupContext) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007144 if (HasTypenameKeyword) {
John McCalled976492009-12-04 22:46:56 +00007145 // FIXME: not all declaration name kinds are legal here
7146 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7147 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007148 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007149 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007150 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007151 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7152 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007153 }
John McCalled976492009-12-04 22:46:56 +00007154 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007155 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007156 NameInfo, HasTypenameKeyword);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007157 }
John McCalled976492009-12-04 22:46:56 +00007158 D->setAccess(AS);
7159 CurContext->addDecl(D);
7160
7161 if (!LookupContext) return D;
7162 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007163
John McCall77bb1aa2010-05-01 00:40:08 +00007164 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007165 UD->setInvalidDecl();
7166 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007167 }
7168
Richard Smithc5a89a12012-04-02 01:30:27 +00007169 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007170 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007171 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007172 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007173 return UD;
7174 }
7175
7176 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007177
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007178 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007179
John McCall604e7f12009-12-08 07:46:18 +00007180 // Unlike most lookups, we don't always want to hide tag
7181 // declarations: tag names are visible through the using declaration
7182 // even if hidden by ordinary names, *except* in a dependent context
7183 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007184 if (!IsInstantiation)
7185 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007186
John McCallb9abd8722012-04-07 03:04:20 +00007187 // For the purposes of this lookup, we have a base object type
7188 // equal to that of the current context.
7189 if (CurContext->isRecord()) {
7190 R.setBaseObjectType(
7191 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7192 }
7193
John McCalla24dc2e2009-11-17 02:14:36 +00007194 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007195
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007196 // Try to correct typos if possible.
John McCallf36e02d2009-10-09 21:13:30 +00007197 if (R.empty()) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007198 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation);
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007199 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7200 R.getLookupKind(), S, &SS, CCC)){
7201 // We reject any correction for which ND would be NULL.
7202 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007203 R.setLookupName(Corrected.getCorrection());
7204 R.addDecl(ND);
Richard Smith2d670972013-08-17 00:46:16 +00007205 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007206 // literal '0' below.
Richard Smith2d670972013-08-17 00:46:16 +00007207 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7208 << NameInfo.getName() << LookupContext << 0
7209 << SS.getRange());
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007210 } else {
Richard Smith2d670972013-08-17 00:46:16 +00007211 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007212 << NameInfo.getName() << LookupContext << SS.getRange();
7213 UD->setInvalidDecl();
7214 return UD;
7215 }
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007216 }
7217
John McCalled976492009-12-04 22:46:56 +00007218 if (R.isAmbiguous()) {
7219 UD->setInvalidDecl();
7220 return UD;
7221 }
Mike Stump1eb44332009-09-09 15:08:12 +00007222
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007223 if (HasTypenameKeyword) {
John McCall7ba107a2009-11-18 02:36:19 +00007224 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007225 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007226 Diag(IdentLoc, diag::err_using_typename_non_type);
7227 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7228 Diag((*I)->getUnderlyingDecl()->getLocation(),
7229 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007230 UD->setInvalidDecl();
7231 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007232 }
7233 } else {
7234 // If we asked for a non-typename and we got a type, error out,
7235 // but only if this is an instantiation of an unresolved using
7236 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007237 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007238 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7239 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007240 UD->setInvalidDecl();
7241 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007242 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007243 }
7244
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007245 // C++0x N2914 [namespace.udecl]p6:
7246 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007247 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007248 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7249 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007250 UD->setInvalidDecl();
7251 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007252 }
Mike Stump1eb44332009-09-09 15:08:12 +00007253
John McCall9f54ad42009-12-10 09:41:52 +00007254 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7255 if (!CheckUsingShadowDecl(UD, *I, Previous))
7256 BuildUsingShadowDecl(S, UD, *I);
7257 }
John McCall9488ea12009-11-17 05:59:44 +00007258
7259 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007260}
7261
Sebastian Redlf677ea32011-02-05 19:23:19 +00007262/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007263bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007264 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007265
Douglas Gregordc355712011-02-25 00:36:19 +00007266 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007267 assert(SourceType &&
7268 "Using decl naming constructor doesn't have type in scope spec.");
7269 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7270
7271 // Check whether the named type is a direct base class.
7272 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7273 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7274 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7275 BaseIt != BaseE; ++BaseIt) {
7276 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7277 if (CanonicalSourceType == BaseType)
7278 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007279 if (BaseIt->getType()->isDependentType())
7280 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007281 }
7282
7283 if (BaseIt == BaseE) {
7284 // Did not find SourceType in the bases.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007285 Diag(UD->getUsingLoc(),
Sebastian Redlf677ea32011-02-05 19:23:19 +00007286 diag::err_using_decl_constructor_not_in_direct_base)
7287 << UD->getNameInfo().getSourceRange()
7288 << QualType(SourceType, 0) << TargetClass;
7289 return true;
7290 }
7291
Richard Smithc5a89a12012-04-02 01:30:27 +00007292 if (!CurContext->isDependentContext())
7293 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007294
7295 return false;
7296}
7297
John McCall9f54ad42009-12-10 09:41:52 +00007298/// Checks that the given using declaration is not an invalid
7299/// redeclaration. Note that this is checking only for the using decl
7300/// itself, not for any ill-formedness among the UsingShadowDecls.
7301bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007302 bool HasTypenameKeyword,
John McCall9f54ad42009-12-10 09:41:52 +00007303 const CXXScopeSpec &SS,
7304 SourceLocation NameLoc,
7305 const LookupResult &Prev) {
7306 // C++03 [namespace.udecl]p8:
7307 // C++0x [namespace.udecl]p10:
7308 // A using-declaration is a declaration and can therefore be used
7309 // repeatedly where (and only where) multiple declarations are
7310 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007311 //
John McCall8a726212010-11-29 18:01:58 +00007312 // That's in non-member contexts.
7313 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007314 return false;
7315
7316 NestedNameSpecifier *Qual
7317 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7318
7319 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7320 NamedDecl *D = *I;
7321
7322 bool DTypename;
7323 NestedNameSpecifier *DQual;
7324 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007325 DTypename = UD->hasTypename();
Douglas Gregordc355712011-02-25 00:36:19 +00007326 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007327 } else if (UnresolvedUsingValueDecl *UD
7328 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7329 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007330 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007331 } else if (UnresolvedUsingTypenameDecl *UD
7332 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7333 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007334 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007335 } else continue;
7336
7337 // using decls differ if one says 'typename' and the other doesn't.
7338 // FIXME: non-dependent using decls?
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007339 if (HasTypenameKeyword != DTypename) continue;
John McCall9f54ad42009-12-10 09:41:52 +00007340
7341 // using decls differ if they name different scopes (but note that
7342 // template instantiation can cause this check to trigger when it
7343 // didn't before instantiation).
7344 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7345 Context.getCanonicalNestedNameSpecifier(DQual))
7346 continue;
7347
7348 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007349 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007350 return true;
7351 }
7352
7353 return false;
7354}
7355
John McCall604e7f12009-12-08 07:46:18 +00007356
John McCalled976492009-12-04 22:46:56 +00007357/// Checks that the given nested-name qualifier used in a using decl
7358/// in the current context is appropriately related to the current
7359/// scope. If an error is found, diagnoses it and returns true.
7360bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7361 const CXXScopeSpec &SS,
7362 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007363 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007364
John McCall604e7f12009-12-08 07:46:18 +00007365 if (!CurContext->isRecord()) {
7366 // C++03 [namespace.udecl]p3:
7367 // C++0x [namespace.udecl]p8:
7368 // A using-declaration for a class member shall be a member-declaration.
7369
7370 // If we weren't able to compute a valid scope, it must be a
7371 // dependent class scope.
7372 if (!NamedContext || NamedContext->isRecord()) {
7373 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7374 << SS.getRange();
7375 return true;
7376 }
7377
7378 // Otherwise, everything is known to be fine.
7379 return false;
7380 }
7381
7382 // The current scope is a record.
7383
7384 // If the named context is dependent, we can't decide much.
7385 if (!NamedContext) {
7386 // FIXME: in C++0x, we can diagnose if we can prove that the
7387 // nested-name-specifier does not refer to a base class, which is
7388 // still possible in some cases.
7389
7390 // Otherwise we have to conservatively report that things might be
7391 // okay.
7392 return false;
7393 }
7394
7395 if (!NamedContext->isRecord()) {
7396 // Ideally this would point at the last name in the specifier,
7397 // but we don't have that level of source info.
7398 Diag(SS.getRange().getBegin(),
7399 diag::err_using_decl_nested_name_specifier_is_not_class)
7400 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7401 return true;
7402 }
7403
Douglas Gregor6fb07292010-12-21 07:41:49 +00007404 if (!NamedContext->isDependentContext() &&
7405 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7406 return true;
7407
Richard Smith80ad52f2013-01-02 11:42:31 +00007408 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007409 // C++0x [namespace.udecl]p3:
7410 // In a using-declaration used as a member-declaration, the
7411 // nested-name-specifier shall name a base class of the class
7412 // being defined.
7413
7414 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7415 cast<CXXRecordDecl>(NamedContext))) {
7416 if (CurContext == NamedContext) {
7417 Diag(NameLoc,
7418 diag::err_using_decl_nested_name_specifier_is_current_class)
7419 << SS.getRange();
7420 return true;
7421 }
7422
7423 Diag(SS.getRange().getBegin(),
7424 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7425 << (NestedNameSpecifier*) SS.getScopeRep()
7426 << cast<CXXRecordDecl>(CurContext)
7427 << SS.getRange();
7428 return true;
7429 }
7430
7431 return false;
7432 }
7433
7434 // C++03 [namespace.udecl]p4:
7435 // A using-declaration used as a member-declaration shall refer
7436 // to a member of a base class of the class being defined [etc.].
7437
7438 // Salient point: SS doesn't have to name a base class as long as
7439 // lookup only finds members from base classes. Therefore we can
7440 // diagnose here only if we can prove that that can't happen,
7441 // i.e. if the class hierarchies provably don't intersect.
7442
7443 // TODO: it would be nice if "definitely valid" results were cached
7444 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7445 // need to be repeated.
7446
7447 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007448 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007449
7450 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7451 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7452 Data->Bases.insert(Base);
7453 return true;
7454 }
7455
7456 bool hasDependentBases(const CXXRecordDecl *Class) {
7457 return !Class->forallBases(collect, this);
7458 }
7459
7460 /// Returns true if the base is dependent or is one of the
7461 /// accumulated base classes.
7462 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7463 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7464 return !Data->Bases.count(Base);
7465 }
7466
7467 bool mightShareBases(const CXXRecordDecl *Class) {
7468 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7469 }
7470 };
7471
7472 UserData Data;
7473
7474 // Returns false if we find a dependent base.
7475 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7476 return false;
7477
7478 // Returns false if the class has a dependent base or if it or one
7479 // of its bases is present in the base set of the current context.
7480 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7481 return false;
7482
7483 Diag(SS.getRange().getBegin(),
7484 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7485 << (NestedNameSpecifier*) SS.getScopeRep()
7486 << cast<CXXRecordDecl>(CurContext)
7487 << SS.getRange();
7488
7489 return true;
John McCalled976492009-12-04 22:46:56 +00007490}
7491
Richard Smith162e1c12011-04-15 14:24:37 +00007492Decl *Sema::ActOnAliasDeclaration(Scope *S,
7493 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007494 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007495 SourceLocation UsingLoc,
7496 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007497 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007498 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007499 // Skip up to the relevant declaration scope.
7500 while (S->getFlags() & Scope::TemplateParamScope)
7501 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007502 assert((S->getFlags() & Scope::DeclScope) &&
7503 "got alias-declaration outside of declaration scope");
7504
7505 if (Type.isInvalid())
7506 return 0;
7507
7508 bool Invalid = false;
7509 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7510 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007511 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007512
7513 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7514 return 0;
7515
7516 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007517 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007518 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007519 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7520 TInfo->getTypeLoc().getBeginLoc());
7521 }
Richard Smith162e1c12011-04-15 14:24:37 +00007522
7523 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7524 LookupName(Previous, S);
7525
7526 // Warn about shadowing the name of a template parameter.
7527 if (Previous.isSingleResult() &&
7528 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007529 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007530 Previous.clear();
7531 }
7532
7533 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7534 "name in alias declaration must be an identifier");
7535 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7536 Name.StartLocation,
7537 Name.Identifier, TInfo);
7538
7539 NewTD->setAccess(AS);
7540
7541 if (Invalid)
7542 NewTD->setInvalidDecl();
7543
Richard Smith6b3d3e52013-02-20 19:22:51 +00007544 ProcessDeclAttributeList(S, NewTD, AttrList);
7545
Richard Smith3e4c6c42011-05-05 21:57:07 +00007546 CheckTypedefForVariablyModifiedType(S, NewTD);
7547 Invalid |= NewTD->isInvalidDecl();
7548
Richard Smith162e1c12011-04-15 14:24:37 +00007549 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007550
7551 NamedDecl *NewND;
7552 if (TemplateParamLists.size()) {
7553 TypeAliasTemplateDecl *OldDecl = 0;
7554 TemplateParameterList *OldTemplateParams = 0;
7555
7556 if (TemplateParamLists.size() != 1) {
7557 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007558 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7559 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007560 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007561 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007562
7563 // Only consider previous declarations in the same scope.
7564 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7565 /*ExplicitInstantiationOrSpecialization*/false);
7566 if (!Previous.empty()) {
7567 Redeclaration = true;
7568
7569 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7570 if (!OldDecl && !Invalid) {
7571 Diag(UsingLoc, diag::err_redefinition_different_kind)
7572 << Name.Identifier;
7573
7574 NamedDecl *OldD = Previous.getRepresentativeDecl();
7575 if (OldD->getLocation().isValid())
7576 Diag(OldD->getLocation(), diag::note_previous_definition);
7577
7578 Invalid = true;
7579 }
7580
7581 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7582 if (TemplateParameterListsAreEqual(TemplateParams,
7583 OldDecl->getTemplateParameters(),
7584 /*Complain=*/true,
7585 TPL_TemplateMatch))
7586 OldTemplateParams = OldDecl->getTemplateParameters();
7587 else
7588 Invalid = true;
7589
7590 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7591 if (!Invalid &&
7592 !Context.hasSameType(OldTD->getUnderlyingType(),
7593 NewTD->getUnderlyingType())) {
7594 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7595 // but we can't reasonably accept it.
7596 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7597 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7598 if (OldTD->getLocation().isValid())
7599 Diag(OldTD->getLocation(), diag::note_previous_definition);
7600 Invalid = true;
7601 }
7602 }
7603 }
7604
7605 // Merge any previous default template arguments into our parameters,
7606 // and check the parameter list.
7607 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7608 TPC_TypeAliasTemplate))
7609 return 0;
7610
7611 TypeAliasTemplateDecl *NewDecl =
7612 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7613 Name.Identifier, TemplateParams,
7614 NewTD);
7615
7616 NewDecl->setAccess(AS);
7617
7618 if (Invalid)
7619 NewDecl->setInvalidDecl();
7620 else if (OldDecl)
7621 NewDecl->setPreviousDeclaration(OldDecl);
7622
7623 NewND = NewDecl;
7624 } else {
7625 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7626 NewND = NewTD;
7627 }
Richard Smith162e1c12011-04-15 14:24:37 +00007628
7629 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007630 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007631
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007632 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007633 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007634}
7635
John McCalld226f652010-08-21 09:40:31 +00007636Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007637 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007638 SourceLocation AliasLoc,
7639 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007640 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007641 SourceLocation IdentLoc,
7642 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007643
Anders Carlsson81c85c42009-03-28 23:53:49 +00007644 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007645 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7646 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007647
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007648 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007649 NamedDecl *PrevDecl
7650 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7651 ForRedeclaration);
7652 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7653 PrevDecl = 0;
7654
7655 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007656 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007657 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007658 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007659 // FIXME: At some point, we'll want to create the (redundant)
7660 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007661 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007662 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007663 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007664 }
Mike Stump1eb44332009-09-09 15:08:12 +00007665
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007666 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7667 diag::err_redefinition_different_kind;
7668 Diag(AliasLoc, DiagID) << Alias;
7669 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007670 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007671 }
7672
John McCalla24dc2e2009-11-17 02:14:36 +00007673 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007674 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007675
John McCallf36e02d2009-10-09 21:13:30 +00007676 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007677 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007678 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007679 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007680 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007681 }
Mike Stump1eb44332009-09-09 15:08:12 +00007682
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007683 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007684 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007685 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007686 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007687
John McCall3dbd3d52010-02-16 06:53:13 +00007688 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007689 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007690}
7691
Sean Hunt001cad92011-05-10 00:49:42 +00007692Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007693Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7694 CXXMethodDecl *MD) {
7695 CXXRecordDecl *ClassDecl = MD->getParent();
7696
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007697 // C++ [except.spec]p14:
7698 // An implicitly declared special member function (Clause 12) shall have an
7699 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007700 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007701 if (ClassDecl->isInvalidDecl())
7702 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007703
Sebastian Redl60618fa2011-03-12 11:50:43 +00007704 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007705 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7706 BEnd = ClassDecl->bases_end();
7707 B != BEnd; ++B) {
7708 if (B->isVirtual()) // Handled below.
7709 continue;
7710
Douglas Gregor18274032010-07-03 00:47:00 +00007711 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7712 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007713 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7714 // If this is a deleted function, add it anyway. This might be conformant
7715 // with the standard. This might not. I'm not sure. It might not matter.
7716 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007717 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007718 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007719 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007720
7721 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007722 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7723 BEnd = ClassDecl->vbases_end();
7724 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007725 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7726 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007727 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7728 // If this is a deleted function, add it anyway. This might be conformant
7729 // with the standard. This might not. I'm not sure. It might not matter.
7730 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007731 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007732 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007733 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007734
7735 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007736 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7737 FEnd = ClassDecl->field_end();
7738 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007739 if (F->hasInClassInitializer()) {
7740 if (Expr *E = F->getInClassInitializer())
7741 ExceptSpec.CalledExpr(E);
7742 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007743 // DR1351:
7744 // If the brace-or-equal-initializer of a non-static data member
7745 // invokes a defaulted default constructor of its class or of an
7746 // enclosing class in a potentially evaluated subexpression, the
7747 // program is ill-formed.
7748 //
7749 // This resolution is unworkable: the exception specification of the
7750 // default constructor can be needed in an unevaluated context, in
7751 // particular, in the operand of a noexcept-expression, and we can be
7752 // unable to compute an exception specification for an enclosed class.
7753 //
7754 // We do not allow an in-class initializer to require the evaluation
7755 // of the exception specification for any in-class initializer whose
7756 // definition is not lexically complete.
7757 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007758 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007759 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007760 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7761 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7762 // If this is a deleted function, add it anyway. This might be conformant
7763 // with the standard. This might not. I'm not sure. It might not matter.
7764 // In particular, the problem is that this function never gets called. It
7765 // might just be ill-formed because this function attempts to refer to
7766 // a deleted function here.
7767 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007768 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007769 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007770 }
John McCalle23cf432010-12-14 08:05:40 +00007771
Sean Hunt001cad92011-05-10 00:49:42 +00007772 return ExceptSpec;
7773}
7774
Richard Smith07b0fdc2013-03-18 21:12:30 +00007775Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007776Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7777 CXXRecordDecl *ClassDecl = CD->getParent();
7778
7779 // C++ [except.spec]p14:
7780 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007781 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007782 if (ClassDecl->isInvalidDecl())
7783 return ExceptSpec;
7784
7785 // Inherited constructor.
7786 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7787 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7788 // FIXME: Copying or moving the parameters could add extra exceptions to the
7789 // set, as could the default arguments for the inherited constructor. This
7790 // will be addressed when we implement the resolution of core issue 1351.
7791 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7792
7793 // Direct base-class constructors.
7794 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7795 BEnd = ClassDecl->bases_end();
7796 B != BEnd; ++B) {
7797 if (B->isVirtual()) // Handled below.
7798 continue;
7799
7800 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7801 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7802 if (BaseClassDecl == InheritedDecl)
7803 continue;
7804 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7805 if (Constructor)
7806 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7807 }
7808 }
7809
7810 // Virtual base-class constructors.
7811 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7812 BEnd = ClassDecl->vbases_end();
7813 B != BEnd; ++B) {
7814 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7815 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7816 if (BaseClassDecl == InheritedDecl)
7817 continue;
7818 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7819 if (Constructor)
7820 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7821 }
7822 }
7823
7824 // Field constructors.
7825 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7826 FEnd = ClassDecl->field_end();
7827 F != FEnd; ++F) {
7828 if (F->hasInClassInitializer()) {
7829 if (Expr *E = F->getInClassInitializer())
7830 ExceptSpec.CalledExpr(E);
7831 else if (!F->isInvalidDecl())
7832 Diag(CD->getLocation(),
7833 diag::err_in_class_initializer_references_def_ctor) << CD;
7834 } else if (const RecordType *RecordTy
7835 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7836 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7837 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7838 if (Constructor)
7839 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7840 }
7841 }
7842
Richard Smith07b0fdc2013-03-18 21:12:30 +00007843 return ExceptSpec;
7844}
7845
Richard Smithafb49182012-11-29 01:34:07 +00007846namespace {
7847/// RAII object to register a special member as being currently declared.
7848struct DeclaringSpecialMember {
7849 Sema &S;
7850 Sema::SpecialMemberDecl D;
7851 bool WasAlreadyBeingDeclared;
7852
7853 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7854 : S(S), D(RD, CSM) {
7855 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7856 if (WasAlreadyBeingDeclared)
7857 // This almost never happens, but if it does, ensure that our cache
7858 // doesn't contain a stale result.
7859 S.SpecialMemberCache.clear();
7860
7861 // FIXME: Register a note to be produced if we encounter an error while
7862 // declaring the special member.
7863 }
7864 ~DeclaringSpecialMember() {
7865 if (!WasAlreadyBeingDeclared)
7866 S.SpecialMembersBeingDeclared.erase(D);
7867 }
7868
7869 /// \brief Are we already trying to declare this special member?
7870 bool isAlreadyBeingDeclared() const {
7871 return WasAlreadyBeingDeclared;
7872 }
7873};
7874}
7875
Sean Hunt001cad92011-05-10 00:49:42 +00007876CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7877 CXXRecordDecl *ClassDecl) {
7878 // C++ [class.ctor]p5:
7879 // A default constructor for a class X is a constructor of class X
7880 // that can be called without an argument. If there is no
7881 // user-declared constructor for class X, a default constructor is
7882 // implicitly declared. An implicitly-declared default constructor
7883 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007884 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007885 "Should not build implicit default constructor!");
7886
Richard Smithafb49182012-11-29 01:34:07 +00007887 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7888 if (DSM.isAlreadyBeingDeclared())
7889 return 0;
7890
Richard Smith7756afa2012-06-10 05:43:50 +00007891 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7892 CXXDefaultConstructor,
7893 false);
7894
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007895 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007896 CanQualType ClassType
7897 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007898 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007899 DeclarationName Name
7900 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007901 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007902 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007903 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007904 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007905 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007906 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007907 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007908 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007909
7910 // Build an exception specification pointing back at this constructor.
Reid Kleckneref072032013-08-27 23:08:25 +00007911 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko55431692013-05-05 00:41:58 +00007912 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007913
Richard Smithbc2a35d2012-12-08 08:32:28 +00007914 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7915 // constructors is easy to compute.
7916 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7917
7918 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007919 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007920
Douglas Gregor18274032010-07-03 00:47:00 +00007921 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007922 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007923
Douglas Gregor23c94db2010-07-02 17:43:08 +00007924 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007925 PushOnScopeChains(DefaultCon, S, false);
7926 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007927
Douglas Gregor32df23e2010-07-01 22:02:46 +00007928 return DefaultCon;
7929}
7930
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007931void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7932 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007933 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007934 !Constructor->doesThisDeclarationHaveABody() &&
7935 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007936 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007937
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007938 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007939 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007940
Eli Friedman9a14db32012-10-18 20:14:08 +00007941 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007942 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007943 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007944 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007945 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007946 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007947 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007948 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007949 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007950
7951 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007952 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007953
7954 Constructor->setUsed();
7955 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007956
7957 if (ASTMutationListener *L = getASTMutationListener()) {
7958 L->CompletedImplicitDefinition(Constructor);
7959 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007960}
7961
Richard Smith7a614d82011-06-11 17:19:42 +00007962void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007963 // Check that any explicitly-defaulted methods have exception specifications
7964 // compatible with their implicit exception specifications.
7965 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007966}
7967
Richard Smith4841ca52013-04-10 05:48:59 +00007968namespace {
7969/// Information on inheriting constructors to declare.
7970class InheritingConstructorInfo {
7971public:
7972 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7973 : SemaRef(SemaRef), Derived(Derived) {
7974 // Mark the constructors that we already have in the derived class.
7975 //
7976 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7977 // unless there is a user-declared constructor with the same signature in
7978 // the class where the using-declaration appears.
7979 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7980 }
7981
7982 void inheritAll(CXXRecordDecl *RD) {
7983 visitAll(RD, &InheritingConstructorInfo::inherit);
7984 }
7985
7986private:
7987 /// Information about an inheriting constructor.
7988 struct InheritingConstructor {
7989 InheritingConstructor()
7990 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7991
7992 /// If \c true, a constructor with this signature is already declared
7993 /// in the derived class.
7994 bool DeclaredInDerived;
7995
7996 /// The constructor which is inherited.
7997 const CXXConstructorDecl *BaseCtor;
7998
7999 /// The derived constructor we declared.
8000 CXXConstructorDecl *DerivedCtor;
8001 };
8002
8003 /// Inheriting constructors with a given canonical type. There can be at
8004 /// most one such non-template constructor, and any number of templated
8005 /// constructors.
8006 struct InheritingConstructorsForType {
8007 InheritingConstructor NonTemplate;
Robert Wilhelme7205c02013-08-10 12:33:24 +00008008 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8009 Templates;
Richard Smith4841ca52013-04-10 05:48:59 +00008010
8011 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8012 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8013 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8014 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8015 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8016 false, S.TPL_TemplateMatch))
8017 return Templates[I].second;
8018 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8019 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008020 }
Richard Smith4841ca52013-04-10 05:48:59 +00008021
8022 return NonTemplate;
8023 }
8024 };
8025
8026 /// Get or create the inheriting constructor record for a constructor.
8027 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8028 QualType CtorType) {
8029 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8030 .getEntry(SemaRef, Ctor);
8031 }
8032
8033 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8034
8035 /// Process all constructors for a class.
8036 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8037 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8038 CtorE = RD->ctor_end();
8039 CtorIt != CtorE; ++CtorIt)
8040 (this->*Callback)(*CtorIt);
8041 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8042 I(RD->decls_begin()), E(RD->decls_end());
8043 I != E; ++I) {
8044 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8045 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8046 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008047 }
8048 }
Richard Smith4841ca52013-04-10 05:48:59 +00008049
8050 /// Note that a constructor (or constructor template) was declared in Derived.
8051 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8052 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8053 }
8054
8055 /// Inherit a single constructor.
8056 void inherit(const CXXConstructorDecl *Ctor) {
8057 const FunctionProtoType *CtorType =
8058 Ctor->getType()->castAs<FunctionProtoType>();
8059 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8060 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8061
8062 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8063
8064 // Core issue (no number yet): the ellipsis is always discarded.
8065 if (EPI.Variadic) {
8066 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8067 SemaRef.Diag(Ctor->getLocation(),
8068 diag::note_using_decl_constructor_ellipsis);
8069 EPI.Variadic = false;
8070 }
8071
8072 // Declare a constructor for each number of parameters.
8073 //
8074 // C++11 [class.inhctor]p1:
8075 // The candidate set of inherited constructors from the class X named in
8076 // the using-declaration consists of [... modulo defects ...] for each
8077 // constructor or constructor template of X, the set of constructors or
8078 // constructor templates that results from omitting any ellipsis parameter
8079 // specification and successively omitting parameters with a default
8080 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00008081 unsigned MinParams = minParamsToInherit(Ctor);
8082 unsigned Params = Ctor->getNumParams();
8083 if (Params >= MinParams) {
8084 do
8085 declareCtor(UsingLoc, Ctor,
8086 SemaRef.Context.getFunctionType(
8087 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8088 while (Params > MinParams &&
8089 Ctor->getParamDecl(--Params)->hasDefaultArg());
8090 }
Richard Smith4841ca52013-04-10 05:48:59 +00008091 }
8092
8093 /// Find the using-declaration which specified that we should inherit the
8094 /// constructors of \p Base.
8095 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8096 // No fancy lookup required; just look for the base constructor name
8097 // directly within the derived class.
8098 ASTContext &Context = SemaRef.Context;
8099 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8100 Context.getCanonicalType(Context.getRecordType(Base)));
8101 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8102 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8103 }
8104
8105 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8106 // C++11 [class.inhctor]p3:
8107 // [F]or each constructor template in the candidate set of inherited
8108 // constructors, a constructor template is implicitly declared
8109 if (Ctor->getDescribedFunctionTemplate())
8110 return 0;
8111
8112 // For each non-template constructor in the candidate set of inherited
8113 // constructors other than a constructor having no parameters or a
8114 // copy/move constructor having a single parameter, a constructor is
8115 // implicitly declared [...]
8116 if (Ctor->getNumParams() == 0)
8117 return 1;
8118 if (Ctor->isCopyOrMoveConstructor())
8119 return 2;
8120
8121 // Per discussion on core reflector, never inherit a constructor which
8122 // would become a default, copy, or move constructor of Derived either.
8123 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8124 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8125 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8126 }
8127
8128 /// Declare a single inheriting constructor, inheriting the specified
8129 /// constructor, with the given type.
8130 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8131 QualType DerivedType) {
8132 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8133
8134 // C++11 [class.inhctor]p3:
8135 // ... a constructor is implicitly declared with the same constructor
8136 // characteristics unless there is a user-declared constructor with
8137 // the same signature in the class where the using-declaration appears
8138 if (Entry.DeclaredInDerived)
8139 return;
8140
8141 // C++11 [class.inhctor]p7:
8142 // If two using-declarations declare inheriting constructors with the
8143 // same signature, the program is ill-formed
8144 if (Entry.DerivedCtor) {
8145 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8146 // Only diagnose this once per constructor.
8147 if (Entry.DerivedCtor->isInvalidDecl())
8148 return;
8149 Entry.DerivedCtor->setInvalidDecl();
8150
8151 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8152 SemaRef.Diag(BaseCtor->getLocation(),
8153 diag::note_using_decl_constructor_conflict_current_ctor);
8154 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8155 diag::note_using_decl_constructor_conflict_previous_ctor);
8156 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8157 diag::note_using_decl_constructor_conflict_previous_using);
8158 } else {
8159 // Core issue (no number): if the same inheriting constructor is
8160 // produced by multiple base class constructors from the same base
8161 // class, the inheriting constructor is defined as deleted.
8162 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8163 }
8164
8165 return;
8166 }
8167
8168 ASTContext &Context = SemaRef.Context;
8169 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8170 Context.getCanonicalType(Context.getRecordType(Derived)));
8171 DeclarationNameInfo NameInfo(Name, UsingLoc);
8172
8173 TemplateParameterList *TemplateParams = 0;
8174 if (const FunctionTemplateDecl *FTD =
8175 BaseCtor->getDescribedFunctionTemplate()) {
8176 TemplateParams = FTD->getTemplateParameters();
8177 // We're reusing template parameters from a different DeclContext. This
8178 // is questionable at best, but works out because the template depth in
8179 // both places is guaranteed to be 0.
8180 // FIXME: Rebuild the template parameters in the new context, and
8181 // transform the function type to refer to them.
8182 }
8183
8184 // Build type source info pointing at the using-declaration. This is
8185 // required by template instantiation.
8186 TypeSourceInfo *TInfo =
8187 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8188 FunctionProtoTypeLoc ProtoLoc =
8189 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8190
8191 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8192 Context, Derived, UsingLoc, NameInfo, DerivedType,
8193 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8194 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8195
8196 // Build an unevaluated exception specification for this constructor.
8197 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8198 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8199 EPI.ExceptionSpecType = EST_Unevaluated;
8200 EPI.ExceptionSpecDecl = DerivedCtor;
8201 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8202 FPT->getArgTypes(), EPI));
8203
8204 // Build the parameter declarations.
8205 SmallVector<ParmVarDecl *, 16> ParamDecls;
8206 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8207 TypeSourceInfo *TInfo =
8208 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8209 ParmVarDecl *PD = ParmVarDecl::Create(
8210 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8211 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8212 PD->setScopeInfo(0, I);
8213 PD->setImplicit();
8214 ParamDecls.push_back(PD);
8215 ProtoLoc.setArg(I, PD);
8216 }
8217
8218 // Set up the new constructor.
8219 DerivedCtor->setAccess(BaseCtor->getAccess());
8220 DerivedCtor->setParams(ParamDecls);
8221 DerivedCtor->setInheritedConstructor(BaseCtor);
8222 if (BaseCtor->isDeleted())
8223 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8224
8225 // If this is a constructor template, build the template declaration.
8226 if (TemplateParams) {
8227 FunctionTemplateDecl *DerivedTemplate =
8228 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8229 TemplateParams, DerivedCtor);
8230 DerivedTemplate->setAccess(BaseCtor->getAccess());
8231 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8232 Derived->addDecl(DerivedTemplate);
8233 } else {
8234 Derived->addDecl(DerivedCtor);
8235 }
8236
8237 Entry.BaseCtor = BaseCtor;
8238 Entry.DerivedCtor = DerivedCtor;
8239 }
8240
8241 Sema &SemaRef;
8242 CXXRecordDecl *Derived;
8243 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8244 MapType Map;
8245};
8246}
8247
8248void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8249 // Defer declaring the inheriting constructors until the class is
8250 // instantiated.
8251 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008252 return;
8253
Richard Smith4841ca52013-04-10 05:48:59 +00008254 // Find base classes from which we might inherit constructors.
8255 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8256 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8257 BaseE = ClassDecl->bases_end();
8258 BaseIt != BaseE; ++BaseIt)
8259 if (BaseIt->getInheritConstructors())
8260 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008261
Richard Smith4841ca52013-04-10 05:48:59 +00008262 // Go no further if we're not inheriting any constructors.
8263 if (InheritedBases.empty())
8264 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008265
Richard Smith4841ca52013-04-10 05:48:59 +00008266 // Declare the inherited constructors.
8267 InheritingConstructorInfo ICI(*this, ClassDecl);
8268 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8269 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008270}
8271
Richard Smith07b0fdc2013-03-18 21:12:30 +00008272void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8273 CXXConstructorDecl *Constructor) {
8274 CXXRecordDecl *ClassDecl = Constructor->getParent();
8275 assert(Constructor->getInheritedConstructor() &&
8276 !Constructor->doesThisDeclarationHaveABody() &&
8277 !Constructor->isDeleted());
8278
8279 SynthesizedFunctionScope Scope(*this, Constructor);
8280 DiagnosticErrorTrap Trap(Diags);
8281 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8282 Trap.hasErrorOccurred()) {
8283 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8284 << Context.getTagDeclType(ClassDecl);
8285 Constructor->setInvalidDecl();
8286 return;
8287 }
8288
8289 SourceLocation Loc = Constructor->getLocation();
8290 Constructor->setBody(new (Context) CompoundStmt(Loc));
8291
8292 Constructor->setUsed();
8293 MarkVTableUsed(CurrentLocation, ClassDecl);
8294
8295 if (ASTMutationListener *L = getASTMutationListener()) {
8296 L->CompletedImplicitDefinition(Constructor);
8297 }
8298}
8299
8300
Sean Huntcb45a0f2011-05-12 22:46:25 +00008301Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008302Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8303 CXXRecordDecl *ClassDecl = MD->getParent();
8304
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008305 // C++ [except.spec]p14:
8306 // An implicitly declared special member function (Clause 12) shall have
8307 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008308 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008309 if (ClassDecl->isInvalidDecl())
8310 return ExceptSpec;
8311
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008312 // Direct base-class destructors.
8313 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8314 BEnd = ClassDecl->bases_end();
8315 B != BEnd; ++B) {
8316 if (B->isVirtual()) // Handled below.
8317 continue;
8318
8319 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008320 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008321 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008322 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008323
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008324 // Virtual base-class destructors.
8325 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8326 BEnd = ClassDecl->vbases_end();
8327 B != BEnd; ++B) {
8328 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008329 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008330 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008331 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008332
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008333 // Field destructors.
8334 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8335 FEnd = ClassDecl->field_end();
8336 F != FEnd; ++F) {
8337 if (const RecordType *RecordTy
8338 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008339 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008340 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008341 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008342
Sean Huntcb45a0f2011-05-12 22:46:25 +00008343 return ExceptSpec;
8344}
8345
8346CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8347 // C++ [class.dtor]p2:
8348 // If a class has no user-declared destructor, a destructor is
8349 // declared implicitly. An implicitly-declared destructor is an
8350 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008351 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008352
Richard Smithafb49182012-11-29 01:34:07 +00008353 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8354 if (DSM.isAlreadyBeingDeclared())
8355 return 0;
8356
Douglas Gregor4923aa22010-07-02 20:37:36 +00008357 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008358 CanQualType ClassType
8359 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008360 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008361 DeclarationName Name
8362 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008363 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008364 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008365 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8366 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008367 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008368 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008369 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008370 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008371
8372 // Build an exception specification pointing back at this destructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008373 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008374 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008375
Richard Smithbc2a35d2012-12-08 08:32:28 +00008376 AddOverriddenMethods(ClassDecl, Destructor);
8377
8378 // We don't need to use SpecialMemberIsTrivial here; triviality for
8379 // destructors is easy to compute.
8380 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8381
8382 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008383 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008384
Douglas Gregor4923aa22010-07-02 20:37:36 +00008385 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008386 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008387
Douglas Gregor4923aa22010-07-02 20:37:36 +00008388 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008389 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008390 PushOnScopeChains(Destructor, S, false);
8391 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008392
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008393 return Destructor;
8394}
8395
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008396void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008397 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008398 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008399 !Destructor->doesThisDeclarationHaveABody() &&
8400 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008401 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008402 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008403 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008404
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008405 if (Destructor->isInvalidDecl())
8406 return;
8407
Eli Friedman9a14db32012-10-18 20:14:08 +00008408 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008409
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008410 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008411 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8412 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008413
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008414 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008415 Diag(CurrentLocation, diag::note_member_synthesized_at)
8416 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8417
8418 Destructor->setInvalidDecl();
8419 return;
8420 }
8421
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008422 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008423 Destructor->setBody(new (Context) CompoundStmt(Loc));
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008424 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008425 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008426
8427 if (ASTMutationListener *L = getASTMutationListener()) {
8428 L->CompletedImplicitDefinition(Destructor);
8429 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008430}
8431
Richard Smitha4156b82012-04-21 18:42:51 +00008432/// \brief Perform any semantic analysis which needs to be delayed until all
8433/// pending class member declarations have been parsed.
8434void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008435 // If the context is an invalid C++ class, just suppress these checks.
8436 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8437 if (Record->isInvalidDecl()) {
8438 DelayedDestructorExceptionSpecChecks.clear();
8439 return;
8440 }
8441 }
8442
Richard Smitha4156b82012-04-21 18:42:51 +00008443 // Perform any deferred checking of exception specifications for virtual
8444 // destructors.
8445 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8446 i != e; ++i) {
8447 const CXXDestructorDecl *Dtor =
8448 DelayedDestructorExceptionSpecChecks[i].first;
8449 assert(!Dtor->getParent()->isDependentType() &&
8450 "Should not ever add destructors of templates into the list.");
8451 CheckOverridingFunctionExceptionSpec(Dtor,
8452 DelayedDestructorExceptionSpecChecks[i].second);
8453 }
8454 DelayedDestructorExceptionSpecChecks.clear();
8455}
8456
Richard Smithb9d0b762012-07-27 04:22:15 +00008457void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8458 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008459 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008460 "adjusting dtor exception specs was introduced in c++11");
8461
Sebastian Redl0ee33912011-05-19 05:13:44 +00008462 // C++11 [class.dtor]p3:
8463 // A declaration of a destructor that does not have an exception-
8464 // specification is implicitly considered to have the same exception-
8465 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008466 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008467 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008468 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008469 return;
8470
Chandler Carruth3f224b22011-09-20 04:55:26 +00008471 // Replace the destructor's type, building off the existing one. Fortunately,
8472 // the only thing of interest in the destructor type is its extended info.
8473 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008474 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8475 EPI.ExceptionSpecType = EST_Unevaluated;
8476 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008477 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008478
Sebastian Redl0ee33912011-05-19 05:13:44 +00008479 // FIXME: If the destructor has a body that could throw, and the newly created
8480 // spec doesn't allow exceptions, we should emit a warning, because this
8481 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008482 // However, we don't have a body or an exception specification yet, so it
8483 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008484}
8485
Pavel Labath66ea35d2013-08-30 08:52:28 +00008486namespace {
8487/// \brief An abstract base class for all helper classes used in building the
8488// copy/move operators. These classes serve as factory functions and help us
8489// avoid using the same Expr* in the AST twice.
8490class ExprBuilder {
8491 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8492 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8493
8494protected:
8495 static Expr *assertNotNull(Expr *E) {
8496 assert(E && "Expression construction must not fail.");
8497 return E;
8498 }
8499
8500public:
8501 ExprBuilder() {}
8502 virtual ~ExprBuilder() {}
8503
8504 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8505};
8506
8507class RefBuilder: public ExprBuilder {
8508 VarDecl *Var;
8509 QualType VarType;
8510
8511public:
8512 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8513 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8514 }
8515
8516 RefBuilder(VarDecl *Var, QualType VarType)
8517 : Var(Var), VarType(VarType) {}
8518};
8519
8520class ThisBuilder: public ExprBuilder {
8521public:
8522 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8523 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8524 }
8525};
8526
8527class CastBuilder: public ExprBuilder {
8528 const ExprBuilder &Builder;
8529 QualType Type;
8530 ExprValueKind Kind;
8531 const CXXCastPath &Path;
8532
8533public:
8534 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8535 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8536 CK_UncheckedDerivedToBase, Kind,
8537 &Path).take());
8538 }
8539
8540 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8541 const CXXCastPath &Path)
8542 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8543};
8544
8545class DerefBuilder: public ExprBuilder {
8546 const ExprBuilder &Builder;
8547
8548public:
8549 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8550 return assertNotNull(
8551 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8552 }
8553
8554 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8555};
8556
8557class MemberBuilder: public ExprBuilder {
8558 const ExprBuilder &Builder;
8559 QualType Type;
8560 CXXScopeSpec SS;
8561 bool IsArrow;
8562 LookupResult &MemberLookup;
8563
8564public:
8565 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8566 return assertNotNull(S.BuildMemberReferenceExpr(
8567 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8568 MemberLookup, 0).take());
8569 }
8570
8571 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8572 LookupResult &MemberLookup)
8573 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8574 MemberLookup(MemberLookup) {}
8575};
8576
8577class MoveCastBuilder: public ExprBuilder {
8578 const ExprBuilder &Builder;
8579
8580public:
8581 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8582 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8583 }
8584
8585 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8586};
8587
8588class LvalueConvBuilder: public ExprBuilder {
8589 const ExprBuilder &Builder;
8590
8591public:
8592 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8593 return assertNotNull(
8594 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8595 }
8596
8597 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8598};
8599
8600class SubscriptBuilder: public ExprBuilder {
8601 const ExprBuilder &Base;
8602 const ExprBuilder &Index;
8603
8604public:
8605 virtual Expr *build(Sema &S, SourceLocation Loc) const
8606 LLVM_OVERRIDE {
8607 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8608 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8609 }
8610
8611 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8612 : Base(Base), Index(Index) {}
8613};
8614
8615} // end anonymous namespace
8616
Richard Smith8c889532012-11-14 00:50:40 +00008617/// When generating a defaulted copy or move assignment operator, if a field
8618/// should be copied with __builtin_memcpy rather than via explicit assignments,
8619/// do so. This optimization only applies for arrays of scalars, and for arrays
8620/// of class type where the selected copy/move-assignment operator is trivial.
8621static StmtResult
8622buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008623 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith8c889532012-11-14 00:50:40 +00008624 // Compute the size of the memory buffer to be copied.
8625 QualType SizeType = S.Context.getSizeType();
8626 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8627 S.Context.getTypeSizeInChars(T).getQuantity());
8628
8629 // Take the address of the field references for "from" and "to". We
8630 // directly construct UnaryOperators here because semantic analysis
8631 // does not permit us to take the address of an xvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00008632 Expr *From = FromB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008633 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8634 S.Context.getPointerType(From->getType()),
8635 VK_RValue, OK_Ordinary, Loc);
Pavel Labath66ea35d2013-08-30 08:52:28 +00008636 Expr *To = ToB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008637 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8638 S.Context.getPointerType(To->getType()),
8639 VK_RValue, OK_Ordinary, Loc);
8640
8641 const Type *E = T->getBaseElementTypeUnsafe();
8642 bool NeedsCollectableMemCpy =
8643 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8644
8645 // Create a reference to the __builtin_objc_memmove_collectable function
8646 StringRef MemCpyName = NeedsCollectableMemCpy ?
8647 "__builtin_objc_memmove_collectable" :
8648 "__builtin_memcpy";
8649 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8650 Sema::LookupOrdinaryName);
8651 S.LookupName(R, S.TUScope, true);
8652
8653 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8654 if (!MemCpy)
8655 // Something went horribly wrong earlier, and we will have complained
8656 // about it.
8657 return StmtError();
8658
8659 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8660 VK_RValue, Loc, 0);
8661 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8662
8663 Expr *CallArgs[] = {
8664 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8665 };
8666 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8667 Loc, CallArgs, Loc);
8668
8669 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8670 return S.Owned(Call.takeAs<Stmt>());
8671}
8672
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008673/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008674/// \c To.
8675///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008676/// This routine is used to copy/move the members of a class with an
8677/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008678/// copied are arrays, this routine builds for loops to copy them.
8679///
8680/// \param S The Sema object used for type-checking.
8681///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008682/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008683///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008684/// \param T The type of the expressions being copied/moved. Both expressions
8685/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008686///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008687/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008688///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008689/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008690///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008691/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008692/// Otherwise, it's a non-static member subobject.
8693///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008694/// \param Copying Whether we're copying or moving.
8695///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008696/// \param Depth Internal parameter recording the depth of the recursion.
8697///
Richard Smith8c889532012-11-14 00:50:40 +00008698/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8699/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008700static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008701buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008702 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00008703 bool CopyingBaseSubobject, bool Copying,
8704 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008705 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008706 // Each subobject is assigned in the manner appropriate to its type:
8707 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008708 // - if the subobject is of class type, as if by a call to operator= with
8709 // the subobject as the object expression and the corresponding
8710 // subobject of x as a single function argument (as if by explicit
8711 // qualification; that is, ignoring any possible virtual overriding
8712 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008713 //
8714 // C++03 [class.copy]p13:
8715 // - if the subobject is of class type, the copy assignment operator for
8716 // the class is used (as if by explicit qualification; that is,
8717 // ignoring any possible virtual overriding functions in more derived
8718 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008719 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8720 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008721
Douglas Gregor06a9f362010-05-01 20:49:11 +00008722 // Look for operator=.
8723 DeclarationName Name
8724 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8725 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8726 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008727
Richard Smith044c8aa2012-11-13 00:54:12 +00008728 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8729 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008730 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008731 LookupResult::Filter F = OpLookup.makeFilter();
8732 while (F.hasNext()) {
8733 NamedDecl *D = F.next();
8734 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8735 if (Method->isCopyAssignmentOperator() ||
8736 (!Copying && Method->isMoveAssignmentOperator()))
8737 continue;
8738
8739 F.erase();
8740 }
8741 F.done();
John McCallb0207482010-03-16 06:11:48 +00008742 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008743
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008744 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008745 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008746 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008747 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008748 // ambiguities), we need to cast "this" to that subobject type; to
8749 // ensure that we don't go through the virtual call mechanism, we need
8750 // to qualify the operator= name with the base class (see below). However,
8751 // this means that if the base class has a protected copy assignment
8752 // operator, the protected member access check will fail. So, we
8753 // rewrite "protected" access to "public" access in this case, since we
8754 // know by construction that we're calling from a derived class.
8755 if (CopyingBaseSubobject) {
8756 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8757 L != LEnd; ++L) {
8758 if (L.getAccess() == AS_protected)
8759 L.setAccess(AS_public);
8760 }
8761 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008762
Douglas Gregor06a9f362010-05-01 20:49:11 +00008763 // Create the nested-name-specifier that will be used to qualify the
8764 // reference to operator=; this is required to suppress the virtual
8765 // call mechanism.
8766 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008767 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008768 SS.MakeTrivial(S.Context,
8769 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008770 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008771 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008772
Douglas Gregor06a9f362010-05-01 20:49:11 +00008773 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008774 ExprResult OpEqualRef
Pavel Labath66ea35d2013-08-30 08:52:28 +00008775 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
8776 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008777 /*FirstQualifierInScope=*/0,
8778 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008779 /*TemplateArgs=*/0,
8780 /*SuppressQualifierCheck=*/true);
8781 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008782 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008783
Douglas Gregor06a9f362010-05-01 20:49:11 +00008784 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008785
Pavel Labath66ea35d2013-08-30 08:52:28 +00008786 Expr *FromInst = From.build(S, Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008787 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008788 OpEqualRef.takeAs<Expr>(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00008789 Loc, FromInst, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008790 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008791 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008792
Richard Smith8c889532012-11-14 00:50:40 +00008793 // If we built a call to a trivial 'operator=' while copying an array,
8794 // bail out. We'll replace the whole shebang with a memcpy.
8795 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8796 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8797 return StmtResult((Stmt*)0);
8798
Richard Smith044c8aa2012-11-13 00:54:12 +00008799 // Convert to an expression-statement, and clean up any produced
8800 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008801 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008802 }
John McCallb0207482010-03-16 06:11:48 +00008803
Richard Smith044c8aa2012-11-13 00:54:12 +00008804 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008805 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008806 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008807 if (!ArrayTy) {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008808 ExprResult Assignment = S.CreateBuiltinBinOp(
8809 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008810 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008811 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008812 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008813 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008814
8815 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008816 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008817
Douglas Gregor06a9f362010-05-01 20:49:11 +00008818 // Construct a loop over the array bounds, e.g.,
8819 //
8820 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8821 //
8822 // that will copy each of the array elements.
8823 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008824
Douglas Gregor06a9f362010-05-01 20:49:11 +00008825 // Create the iteration variable.
8826 IdentifierInfo *IterationVarName = 0;
8827 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008828 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008829 llvm::raw_svector_ostream OS(Str);
8830 OS << "__i" << Depth;
8831 IterationVarName = &S.Context.Idents.get(OS.str());
8832 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008833 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008834 IterationVarName, SizeType,
8835 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008836 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008837
Douglas Gregor06a9f362010-05-01 20:49:11 +00008838 // Initialize the iteration variable to zero.
8839 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008840 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008841
Pavel Labath66ea35d2013-08-30 08:52:28 +00008842 // Creates a reference to the iteration variable.
8843 RefBuilder IterationVarRef(IterationVar, SizeType);
8844 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman8c382062012-01-23 02:35:22 +00008845
Douglas Gregor06a9f362010-05-01 20:49:11 +00008846 // Create the DeclStmt that holds the iteration variable.
8847 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008848
Douglas Gregor06a9f362010-05-01 20:49:11 +00008849 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath66ea35d2013-08-30 08:52:28 +00008850 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
8851 MoveCastBuilder FromIndexMove(FromIndexCopy);
8852 const ExprBuilder *FromIndex;
8853 if (Copying)
8854 FromIndex = &FromIndexCopy;
8855 else
8856 FromIndex = &FromIndexMove;
8857
8858 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008859
8860 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008861 StmtResult Copy =
8862 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00008863 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith8c889532012-11-14 00:50:40 +00008864 Copying, Depth + 1);
8865 // Bail out if copying fails or if we determined that we should use memcpy.
8866 if (Copy.isInvalid() || !Copy.get())
8867 return Copy;
8868
8869 // Create the comparison against the array bound.
8870 llvm::APInt Upper
8871 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8872 Expr *Comparison
Pavel Labath66ea35d2013-08-30 08:52:28 +00008873 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith8c889532012-11-14 00:50:40 +00008874 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8875 BO_NE, S.Context.BoolTy,
8876 VK_RValue, OK_Ordinary, Loc, false);
8877
8878 // Create the pre-increment of the iteration variable.
8879 Expr *Increment
Pavel Labath66ea35d2013-08-30 08:52:28 +00008880 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
8881 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008882
Douglas Gregor06a9f362010-05-01 20:49:11 +00008883 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008884 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008885 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008886 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008887 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008888}
8889
Richard Smith8c889532012-11-14 00:50:40 +00008890static StmtResult
8891buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008892 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00008893 bool CopyingBaseSubobject, bool Copying) {
8894 // Maybe we should use a memcpy?
8895 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8896 T.isTriviallyCopyableType(S.Context))
8897 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8898
8899 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8900 CopyingBaseSubobject,
8901 Copying, 0));
8902
8903 // If we ended up picking a trivial assignment operator for an array of a
8904 // non-trivially-copyable class type, just emit a memcpy.
8905 if (!Result.isInvalid() && !Result.get())
8906 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8907
8908 return Result;
8909}
8910
Richard Smithb9d0b762012-07-27 04:22:15 +00008911Sema::ImplicitExceptionSpecification
8912Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8913 CXXRecordDecl *ClassDecl = MD->getParent();
8914
8915 ImplicitExceptionSpecification ExceptSpec(*this);
8916 if (ClassDecl->isInvalidDecl())
8917 return ExceptSpec;
8918
8919 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8920 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8921 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8922
Douglas Gregorb87786f2010-07-01 17:48:08 +00008923 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008924 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008925 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008926
8927 // It is unspecified whether or not an implicit copy assignment operator
8928 // attempts to deduplicate calls to assignment operators of virtual bases are
8929 // made. As such, this exception specification is effectively unspecified.
8930 // Based on a similar decision made for constness in C++0x, we're erring on
8931 // the side of assuming such calls to be made regardless of whether they
8932 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008933 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8934 BaseEnd = ClassDecl->bases_end();
8935 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008936 if (Base->isVirtual())
8937 continue;
8938
Douglas Gregora376d102010-07-02 21:50:04 +00008939 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008940 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008941 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8942 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008943 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008944 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008945
8946 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8947 BaseEnd = ClassDecl->vbases_end();
8948 Base != BaseEnd; ++Base) {
8949 CXXRecordDecl *BaseClassDecl
8950 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8951 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8952 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008953 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008954 }
8955
Douglas Gregorb87786f2010-07-01 17:48:08 +00008956 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8957 FieldEnd = ClassDecl->field_end();
8958 Field != FieldEnd;
8959 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008960 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008961 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8962 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008963 LookupCopyingAssignment(FieldClassDecl,
8964 ArgQuals | FieldType.getCVRQualifiers(),
8965 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008966 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008967 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008968 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008969
Richard Smithb9d0b762012-07-27 04:22:15 +00008970 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008971}
8972
8973CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8974 // Note: The following rules are largely analoguous to the copy
8975 // constructor rules. Note that virtual bases are not taken into account
8976 // for determining the argument type of the operator. Note also that
8977 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008978 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008979
Richard Smithafb49182012-11-29 01:34:07 +00008980 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8981 if (DSM.isAlreadyBeingDeclared())
8982 return 0;
8983
Sean Hunt30de05c2011-05-14 05:23:20 +00008984 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8985 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00008986 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
8987 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00008988 ArgType = ArgType.withConst();
8989 ArgType = Context.getLValueReferenceType(ArgType);
8990
Richard Smitha8942d72013-05-07 03:19:20 +00008991 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8992 CXXCopyAssignment,
8993 Const);
8994
Douglas Gregord3c35902010-07-01 16:36:15 +00008995 // An implicitly-declared copy assignment operator is an inline public
8996 // member of its class.
8997 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008998 SourceLocation ClassLoc = ClassDecl->getLocation();
8999 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009000 CXXMethodDecl *CopyAssignment =
9001 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9002 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9003 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00009004 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00009005 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00009006 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00009007
9008 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009009 FunctionProtoType::ExtProtoInfo EPI =
9010 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009011 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009012
Douglas Gregord3c35902010-07-01 16:36:15 +00009013 // Add the parameter to the operator.
9014 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009015 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00009016 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009017 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009018 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00009019
Richard Smithbc2a35d2012-12-08 08:32:28 +00009020 AddOverriddenMethods(ClassDecl, CopyAssignment);
9021
9022 CopyAssignment->setTrivial(
9023 ClassDecl->needsOverloadResolutionForCopyAssignment()
9024 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9025 : ClassDecl->hasTrivialCopyAssignment());
9026
Richard Smitha8942d72013-05-07 03:19:20 +00009027 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00009028 // .... If the class definition does not explicitly declare a copy
9029 // assignment operator, there is no user-declared move constructor, and
9030 // there is no user-declared move assignment operator, a copy assignment
9031 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009032 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009033 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009034
Richard Smithbc2a35d2012-12-08 08:32:28 +00009035 // Note that we have added this copy-assignment operator.
9036 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9037
9038 if (Scope *S = getScopeForContext(ClassDecl))
9039 PushOnScopeChains(CopyAssignment, S, false);
9040 ClassDecl->addDecl(CopyAssignment);
9041
Douglas Gregord3c35902010-07-01 16:36:15 +00009042 return CopyAssignment;
9043}
9044
Richard Smith36155c12013-06-13 03:23:42 +00009045/// Diagnose an implicit copy operation for a class which is odr-used, but
9046/// which is deprecated because the class has a user-declared copy constructor,
9047/// copy assignment operator, or destructor.
9048static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9049 SourceLocation UseLoc) {
9050 assert(CopyOp->isImplicit());
9051
9052 CXXRecordDecl *RD = CopyOp->getParent();
9053 CXXMethodDecl *UserDeclaredOperation = 0;
9054
9055 // In Microsoft mode, assignment operations don't affect constructors and
9056 // vice versa.
9057 if (RD->hasUserDeclaredDestructor()) {
9058 UserDeclaredOperation = RD->getDestructor();
9059 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9060 RD->hasUserDeclaredCopyConstructor() &&
9061 !S.getLangOpts().MicrosoftMode) {
9062 // Find any user-declared copy constructor.
9063 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9064 E = RD->ctor_end(); I != E; ++I) {
9065 if (I->isCopyConstructor()) {
9066 UserDeclaredOperation = *I;
9067 break;
9068 }
9069 }
9070 assert(UserDeclaredOperation);
9071 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9072 RD->hasUserDeclaredCopyAssignment() &&
9073 !S.getLangOpts().MicrosoftMode) {
9074 // Find any user-declared move assignment operator.
9075 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9076 E = RD->method_end(); I != E; ++I) {
9077 if (I->isCopyAssignmentOperator()) {
9078 UserDeclaredOperation = *I;
9079 break;
9080 }
9081 }
9082 assert(UserDeclaredOperation);
9083 }
9084
9085 if (UserDeclaredOperation) {
9086 S.Diag(UserDeclaredOperation->getLocation(),
9087 diag::warn_deprecated_copy_operation)
9088 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9089 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9090 S.Diag(UseLoc, diag::note_member_synthesized_at)
9091 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9092 : Sema::CXXCopyAssignment)
9093 << RD;
9094 }
9095}
9096
Douglas Gregor06a9f362010-05-01 20:49:11 +00009097void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9098 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00009099 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009100 CopyAssignOperator->isOverloadedOperator() &&
9101 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009102 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9103 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009104 "DefineImplicitCopyAssignment called for wrong function");
9105
9106 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9107
9108 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9109 CopyAssignOperator->setInvalidDecl();
9110 return;
9111 }
Richard Smith36155c12013-06-13 03:23:42 +00009112
9113 // C++11 [class.copy]p18:
9114 // The [definition of an implicitly declared copy assignment operator] is
9115 // deprecated if the class has a user-declared copy constructor or a
9116 // user-declared destructor.
9117 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9118 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9119
Douglas Gregor06a9f362010-05-01 20:49:11 +00009120 CopyAssignOperator->setUsed();
9121
Eli Friedman9a14db32012-10-18 20:14:08 +00009122 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009123 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009124
9125 // C++0x [class.copy]p30:
9126 // The implicitly-defined or explicitly-defaulted copy assignment operator
9127 // for a non-union class X performs memberwise copy assignment of its
9128 // subobjects. The direct base classes of X are assigned first, in the
9129 // order of their declaration in the base-specifier-list, and then the
9130 // immediate non-static data members of X are assigned, in the order in
9131 // which they were declared in the class definition.
9132
9133 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009134 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009135
9136 // The parameter for the "other" object, which we are copying from.
9137 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9138 Qualifiers OtherQuals = Other->getType().getQualifiers();
9139 QualType OtherRefType = Other->getType();
9140 if (const LValueReferenceType *OtherRef
9141 = OtherRefType->getAs<LValueReferenceType>()) {
9142 OtherRefType = OtherRef->getPointeeType();
9143 OtherQuals = OtherRefType.getQualifiers();
9144 }
9145
9146 // Our location for everything implicitly-generated.
9147 SourceLocation Loc = CopyAssignOperator->getLocation();
9148
Pavel Labath66ea35d2013-08-30 08:52:28 +00009149 // Builds a DeclRefExpr for the "other" object.
9150 RefBuilder OtherRef(Other, OtherRefType);
9151
9152 // Builds the "this" pointer.
9153 ThisBuilder This;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009154
9155 // Assign base classes.
9156 bool Invalid = false;
9157 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9158 E = ClassDecl->bases_end(); Base != E; ++Base) {
9159 // Form the assignment:
9160 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9161 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009162 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009163 Invalid = true;
9164 continue;
9165 }
9166
John McCallf871d0c2010-08-07 06:22:56 +00009167 CXXCastPath BasePath;
9168 BasePath.push_back(Base);
9169
Douglas Gregor06a9f362010-05-01 20:49:11 +00009170 // Construct the "from" expression, which is an implicit cast to the
9171 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009172 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9173 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009174
9175 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009176 DerefBuilder DerefThis(This);
9177 CastBuilder To(DerefThis,
9178 Context.getCVRQualifiedType(
9179 BaseType, CopyAssignOperator->getTypeQualifiers()),
9180 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009181
9182 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00009183 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009184 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009185 /*CopyingBaseSubobject=*/true,
9186 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009187 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009188 Diag(CurrentLocation, diag::note_member_synthesized_at)
9189 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9190 CopyAssignOperator->setInvalidDecl();
9191 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009192 }
9193
9194 // Success! Record the copy.
9195 Statements.push_back(Copy.takeAs<Expr>());
9196 }
9197
Douglas Gregor06a9f362010-05-01 20:49:11 +00009198 // Assign non-static members.
9199 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9200 FieldEnd = ClassDecl->field_end();
9201 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009202 if (Field->isUnnamedBitfield())
9203 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00009204
9205 if (Field->isInvalidDecl()) {
9206 Invalid = true;
9207 continue;
9208 }
9209
Douglas Gregor06a9f362010-05-01 20:49:11 +00009210 // Check for members of reference type; we can't copy those.
9211 if (Field->getType()->isReferenceType()) {
9212 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9213 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9214 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009215 Diag(CurrentLocation, diag::note_member_synthesized_at)
9216 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009217 Invalid = true;
9218 continue;
9219 }
9220
9221 // Check for members of const-qualified, non-class type.
9222 QualType BaseType = Context.getBaseElementType(Field->getType());
9223 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9224 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9225 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9226 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009227 Diag(CurrentLocation, diag::note_member_synthesized_at)
9228 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009229 Invalid = true;
9230 continue;
9231 }
John McCallb77115d2011-06-17 00:18:42 +00009232
9233 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009234 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9235 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009236
9237 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009238 if (FieldType->isIncompleteArrayType()) {
9239 assert(ClassDecl->hasFlexibleArrayMember() &&
9240 "Incomplete array type is not valid");
9241 continue;
9242 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009243
9244 // Build references to the field in the object we're copying from and to.
9245 CXXScopeSpec SS; // Intentionally empty
9246 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9247 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009248 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009249 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009250
9251 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9252
9253 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009254
Douglas Gregor06a9f362010-05-01 20:49:11 +00009255 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009256 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009257 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009258 /*CopyingBaseSubobject=*/false,
9259 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009260 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009261 Diag(CurrentLocation, diag::note_member_synthesized_at)
9262 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9263 CopyAssignOperator->setInvalidDecl();
9264 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009265 }
9266
9267 // Success! Record the copy.
9268 Statements.push_back(Copy.takeAs<Stmt>());
9269 }
9270
9271 if (!Invalid) {
9272 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009273 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009274
John McCall60d7b3a2010-08-24 06:29:42 +00009275 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009276 if (Return.isInvalid())
9277 Invalid = true;
9278 else {
9279 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009280
9281 if (Trap.hasErrorOccurred()) {
9282 Diag(CurrentLocation, diag::note_member_synthesized_at)
9283 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9284 Invalid = true;
9285 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009286 }
9287 }
9288
9289 if (Invalid) {
9290 CopyAssignOperator->setInvalidDecl();
9291 return;
9292 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009293
9294 StmtResult Body;
9295 {
9296 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009297 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009298 /*isStmtExpr=*/false);
9299 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9300 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009301 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009302
9303 if (ASTMutationListener *L = getASTMutationListener()) {
9304 L->CompletedImplicitDefinition(CopyAssignOperator);
9305 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009306}
9307
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009308Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009309Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9310 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009311
Richard Smithb9d0b762012-07-27 04:22:15 +00009312 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009313 if (ClassDecl->isInvalidDecl())
9314 return ExceptSpec;
9315
9316 // C++0x [except.spec]p14:
9317 // An implicitly declared special member function (Clause 12) shall have an
9318 // exception-specification. [...]
9319
9320 // It is unspecified whether or not an implicit move assignment operator
9321 // attempts to deduplicate calls to assignment operators of virtual bases are
9322 // made. As such, this exception specification is effectively unspecified.
9323 // Based on a similar decision made for constness in C++0x, we're erring on
9324 // the side of assuming such calls to be made regardless of whether they
9325 // actually happen.
9326 // Note that a move constructor is not implicitly declared when there are
9327 // virtual bases, but it can still be user-declared and explicitly defaulted.
9328 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9329 BaseEnd = ClassDecl->bases_end();
9330 Base != BaseEnd; ++Base) {
9331 if (Base->isVirtual())
9332 continue;
9333
9334 CXXRecordDecl *BaseClassDecl
9335 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9336 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009337 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009338 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009339 }
9340
9341 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9342 BaseEnd = ClassDecl->vbases_end();
9343 Base != BaseEnd; ++Base) {
9344 CXXRecordDecl *BaseClassDecl
9345 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9346 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009347 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009348 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009349 }
9350
9351 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9352 FieldEnd = ClassDecl->field_end();
9353 Field != FieldEnd;
9354 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009355 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009356 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009357 if (CXXMethodDecl *MoveAssign =
9358 LookupMovingAssignment(FieldClassDecl,
9359 FieldType.getCVRQualifiers(),
9360 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009361 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009362 }
9363 }
9364
9365 return ExceptSpec;
9366}
9367
Richard Smith1c931be2012-04-02 18:40:40 +00009368/// Determine whether the class type has any direct or indirect virtual base
9369/// classes which have a non-trivial move assignment operator.
9370static bool
9371hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9372 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9373 BaseEnd = ClassDecl->vbases_end();
9374 Base != BaseEnd; ++Base) {
9375 CXXRecordDecl *BaseClass =
9376 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9377
9378 // Try to declare the move assignment. If it would be deleted, then the
9379 // class does not have a non-trivial move assignment.
9380 if (BaseClass->needsImplicitMoveAssignment())
9381 S.DeclareImplicitMoveAssignment(BaseClass);
9382
Richard Smith426391c2012-11-16 00:53:38 +00009383 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009384 return true;
9385 }
9386
9387 return false;
9388}
9389
9390/// Determine whether the given type either has a move constructor or is
9391/// trivially copyable.
9392static bool
9393hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9394 Type = S.Context.getBaseElementType(Type);
9395
9396 // FIXME: Technically, non-trivially-copyable non-class types, such as
9397 // reference types, are supposed to return false here, but that appears
9398 // to be a standard defect.
9399 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009400 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009401 return true;
9402
9403 if (Type.isTriviallyCopyableType(S.Context))
9404 return true;
9405
9406 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009407 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9408 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009409 if (ClassDecl->needsImplicitMoveConstructor())
9410 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009411 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009412 }
9413
Richard Smithe5411b72012-12-01 02:35:44 +00009414 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9415 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009416 if (ClassDecl->needsImplicitMoveAssignment())
9417 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009418 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009419}
9420
9421/// Determine whether all non-static data members and direct or virtual bases
9422/// of class \p ClassDecl have either a move operation, or are trivially
9423/// copyable.
9424static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9425 bool IsConstructor) {
9426 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9427 BaseEnd = ClassDecl->bases_end();
9428 Base != BaseEnd; ++Base) {
9429 if (Base->isVirtual())
9430 continue;
9431
9432 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9433 return false;
9434 }
9435
9436 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9437 BaseEnd = ClassDecl->vbases_end();
9438 Base != BaseEnd; ++Base) {
9439 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9440 return false;
9441 }
9442
9443 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9444 FieldEnd = ClassDecl->field_end();
9445 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009446 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009447 return false;
9448 }
9449
9450 return true;
9451}
9452
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009453CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009454 // C++11 [class.copy]p20:
9455 // If the definition of a class X does not explicitly declare a move
9456 // assignment operator, one will be implicitly declared as defaulted
9457 // if and only if:
9458 //
9459 // - [first 4 bullets]
9460 assert(ClassDecl->needsImplicitMoveAssignment());
9461
Richard Smithafb49182012-11-29 01:34:07 +00009462 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9463 if (DSM.isAlreadyBeingDeclared())
9464 return 0;
9465
Richard Smith1c931be2012-04-02 18:40:40 +00009466 // [Checked after we build the declaration]
9467 // - the move assignment operator would not be implicitly defined as
9468 // deleted,
9469
9470 // [DR1402]:
9471 // - X has no direct or indirect virtual base class with a non-trivial
9472 // move assignment operator, and
9473 // - each of X's non-static data members and direct or virtual base classes
9474 // has a type that either has a move assignment operator or is trivially
9475 // copyable.
9476 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9477 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9478 ClassDecl->setFailedImplicitMoveAssignment();
9479 return 0;
9480 }
9481
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009482 // Note: The following rules are largely analoguous to the move
9483 // constructor rules.
9484
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009485 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9486 QualType RetType = Context.getLValueReferenceType(ArgType);
9487 ArgType = Context.getRValueReferenceType(ArgType);
9488
Richard Smitha8942d72013-05-07 03:19:20 +00009489 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9490 CXXMoveAssignment,
9491 false);
9492
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009493 // An implicitly-declared move assignment operator is an inline public
9494 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009495 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9496 SourceLocation ClassLoc = ClassDecl->getLocation();
9497 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009498 CXXMethodDecl *MoveAssignment =
9499 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9500 /*TInfo=*/0, /*StorageClass=*/SC_None,
9501 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009502 MoveAssignment->setAccess(AS_public);
9503 MoveAssignment->setDefaulted();
9504 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009505
Richard Smithb9d0b762012-07-27 04:22:15 +00009506 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009507 FunctionProtoType::ExtProtoInfo EPI =
9508 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009509 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009510
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009511 // Add the parameter to the operator.
9512 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9513 ClassLoc, ClassLoc, /*Id=*/0,
9514 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009515 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009516 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009517
Richard Smithbc2a35d2012-12-08 08:32:28 +00009518 AddOverriddenMethods(ClassDecl, MoveAssignment);
9519
9520 MoveAssignment->setTrivial(
9521 ClassDecl->needsOverloadResolutionForMoveAssignment()
9522 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9523 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009524
9525 // C++0x [class.copy]p9:
9526 // If the definition of a class X does not explicitly declare a move
9527 // assignment operator, one will be implicitly declared as defaulted if and
9528 // only if:
9529 // [...]
9530 // - the move assignment operator would not be implicitly defined as
9531 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009532 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009533 // Cache this result so that we don't try to generate this over and over
9534 // on every lookup, leaking memory and wasting time.
9535 ClassDecl->setFailedImplicitMoveAssignment();
9536 return 0;
9537 }
9538
Richard Smithbc2a35d2012-12-08 08:32:28 +00009539 // Note that we have added this copy-assignment operator.
9540 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9541
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009542 if (Scope *S = getScopeForContext(ClassDecl))
9543 PushOnScopeChains(MoveAssignment, S, false);
9544 ClassDecl->addDecl(MoveAssignment);
9545
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009546 return MoveAssignment;
9547}
9548
9549void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9550 CXXMethodDecl *MoveAssignOperator) {
9551 assert((MoveAssignOperator->isDefaulted() &&
9552 MoveAssignOperator->isOverloadedOperator() &&
9553 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009554 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9555 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009556 "DefineImplicitMoveAssignment called for wrong function");
9557
9558 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9559
9560 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9561 MoveAssignOperator->setInvalidDecl();
9562 return;
9563 }
9564
9565 MoveAssignOperator->setUsed();
9566
Eli Friedman9a14db32012-10-18 20:14:08 +00009567 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009568 DiagnosticErrorTrap Trap(Diags);
9569
9570 // C++0x [class.copy]p28:
9571 // The implicitly-defined or move assignment operator for a non-union class
9572 // X performs memberwise move assignment of its subobjects. The direct base
9573 // classes of X are assigned first, in the order of their declaration in the
9574 // base-specifier-list, and then the immediate non-static data members of X
9575 // are assigned, in the order in which they were declared in the class
9576 // definition.
9577
9578 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009579 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009580
9581 // The parameter for the "other" object, which we are move from.
9582 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9583 QualType OtherRefType = Other->getType()->
9584 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009585 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009586 "Bad argument type of defaulted move assignment");
9587
9588 // Our location for everything implicitly-generated.
9589 SourceLocation Loc = MoveAssignOperator->getLocation();
9590
Pavel Labath66ea35d2013-08-30 08:52:28 +00009591 // Builds a reference to the "other" object.
9592 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009593 // Cast to rvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009594 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009595
Pavel Labath66ea35d2013-08-30 08:52:28 +00009596 // Builds the "this" pointer.
9597 ThisBuilder This;
Richard Smith1c931be2012-04-02 18:40:40 +00009598
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009599 // Assign base classes.
9600 bool Invalid = false;
9601 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9602 E = ClassDecl->bases_end(); Base != E; ++Base) {
9603 // Form the assignment:
9604 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9605 QualType BaseType = Base->getType().getUnqualifiedType();
9606 if (!BaseType->isRecordType()) {
9607 Invalid = true;
9608 continue;
9609 }
9610
9611 CXXCastPath BasePath;
9612 BasePath.push_back(Base);
9613
9614 // Construct the "from" expression, which is an implicit cast to the
9615 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009616 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009617
9618 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009619 DerefBuilder DerefThis(This);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009620
9621 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009622 CastBuilder To(DerefThis,
9623 Context.getCVRQualifiedType(
9624 BaseType, MoveAssignOperator->getTypeQualifiers()),
9625 VK_LValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009626
9627 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009628 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009629 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009630 /*CopyingBaseSubobject=*/true,
9631 /*Copying=*/false);
9632 if (Move.isInvalid()) {
9633 Diag(CurrentLocation, diag::note_member_synthesized_at)
9634 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9635 MoveAssignOperator->setInvalidDecl();
9636 return;
9637 }
9638
9639 // Success! Record the move.
9640 Statements.push_back(Move.takeAs<Expr>());
9641 }
9642
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009643 // Assign non-static members.
9644 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9645 FieldEnd = ClassDecl->field_end();
9646 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009647 if (Field->isUnnamedBitfield())
9648 continue;
9649
Eli Friedman8150da32013-06-07 01:48:56 +00009650 if (Field->isInvalidDecl()) {
9651 Invalid = true;
9652 continue;
9653 }
9654
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009655 // Check for members of reference type; we can't move those.
9656 if (Field->getType()->isReferenceType()) {
9657 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9658 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9659 Diag(Field->getLocation(), diag::note_declared_at);
9660 Diag(CurrentLocation, diag::note_member_synthesized_at)
9661 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9662 Invalid = true;
9663 continue;
9664 }
9665
9666 // Check for members of const-qualified, non-class type.
9667 QualType BaseType = Context.getBaseElementType(Field->getType());
9668 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9669 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9670 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9671 Diag(Field->getLocation(), diag::note_declared_at);
9672 Diag(CurrentLocation, diag::note_member_synthesized_at)
9673 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9674 Invalid = true;
9675 continue;
9676 }
9677
9678 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009679 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9680 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009681
9682 QualType FieldType = Field->getType().getNonReferenceType();
9683 if (FieldType->isIncompleteArrayType()) {
9684 assert(ClassDecl->hasFlexibleArrayMember() &&
9685 "Incomplete array type is not valid");
9686 continue;
9687 }
9688
9689 // Build references to the field in the object we're copying from and to.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009690 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9691 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009692 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009693 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009694 MemberBuilder From(MoveOther, OtherRefType,
9695 /*IsArrow=*/false, MemberLookup);
9696 MemberBuilder To(This, getCurrentThisType(),
9697 /*IsArrow=*/true, MemberLookup);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009698
Pavel Labath66ea35d2013-08-30 08:52:28 +00009699 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009700 "Member reference with rvalue base must be rvalue except for reference "
9701 "members, which aren't allowed for move assignment.");
9702
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009703 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009704 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009705 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009706 /*CopyingBaseSubobject=*/false,
9707 /*Copying=*/false);
9708 if (Move.isInvalid()) {
9709 Diag(CurrentLocation, diag::note_member_synthesized_at)
9710 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9711 MoveAssignOperator->setInvalidDecl();
9712 return;
9713 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009714
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009715 // Success! Record the copy.
9716 Statements.push_back(Move.takeAs<Stmt>());
9717 }
9718
9719 if (!Invalid) {
9720 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009721 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009722
9723 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9724 if (Return.isInvalid())
9725 Invalid = true;
9726 else {
9727 Statements.push_back(Return.takeAs<Stmt>());
9728
9729 if (Trap.hasErrorOccurred()) {
9730 Diag(CurrentLocation, diag::note_member_synthesized_at)
9731 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9732 Invalid = true;
9733 }
9734 }
9735 }
9736
9737 if (Invalid) {
9738 MoveAssignOperator->setInvalidDecl();
9739 return;
9740 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009741
9742 StmtResult Body;
9743 {
9744 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009745 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009746 /*isStmtExpr=*/false);
9747 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9748 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009749 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9750
9751 if (ASTMutationListener *L = getASTMutationListener()) {
9752 L->CompletedImplicitDefinition(MoveAssignOperator);
9753 }
9754}
9755
Richard Smithb9d0b762012-07-27 04:22:15 +00009756Sema::ImplicitExceptionSpecification
9757Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9758 CXXRecordDecl *ClassDecl = MD->getParent();
9759
9760 ImplicitExceptionSpecification ExceptSpec(*this);
9761 if (ClassDecl->isInvalidDecl())
9762 return ExceptSpec;
9763
9764 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9765 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9766 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9767
Douglas Gregor0d405db2010-07-01 20:59:04 +00009768 // C++ [except.spec]p14:
9769 // An implicitly declared special member function (Clause 12) shall have an
9770 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009771 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9772 BaseEnd = ClassDecl->bases_end();
9773 Base != BaseEnd;
9774 ++Base) {
9775 // Virtual bases are handled below.
9776 if (Base->isVirtual())
9777 continue;
9778
Douglas Gregor22584312010-07-02 23:41:54 +00009779 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009780 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009781 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009782 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009783 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009784 }
9785 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9786 BaseEnd = ClassDecl->vbases_end();
9787 Base != BaseEnd;
9788 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009789 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009790 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009791 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009792 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009793 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009794 }
9795 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9796 FieldEnd = ClassDecl->field_end();
9797 Field != FieldEnd;
9798 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009799 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009800 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9801 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009802 LookupCopyingConstructor(FieldClassDecl,
9803 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009804 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009805 }
9806 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009807
Richard Smithb9d0b762012-07-27 04:22:15 +00009808 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009809}
9810
9811CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9812 CXXRecordDecl *ClassDecl) {
9813 // C++ [class.copy]p4:
9814 // If the class definition does not explicitly declare a copy
9815 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009816 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009817
Richard Smithafb49182012-11-29 01:34:07 +00009818 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9819 if (DSM.isAlreadyBeingDeclared())
9820 return 0;
9821
Sean Hunt49634cf2011-05-13 06:10:58 +00009822 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9823 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009824 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009825 if (Const)
9826 ArgType = ArgType.withConst();
9827 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009828
Richard Smith7756afa2012-06-10 05:43:50 +00009829 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9830 CXXCopyConstructor,
9831 Const);
9832
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009833 DeclarationName Name
9834 = Context.DeclarationNames.getCXXConstructorName(
9835 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009836 SourceLocation ClassLoc = ClassDecl->getLocation();
9837 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009838
9839 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009840 // member of its class.
9841 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009842 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009843 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009844 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009845 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009846 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009847
Richard Smithb9d0b762012-07-27 04:22:15 +00009848 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009849 FunctionProtoType::ExtProtoInfo EPI =
9850 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +00009851 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009852 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009853
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009854 // Add the parameter to the constructor.
9855 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009856 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009857 /*IdentifierInfo=*/0,
9858 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009859 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009860 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009861
Richard Smithbc2a35d2012-12-08 08:32:28 +00009862 CopyConstructor->setTrivial(
9863 ClassDecl->needsOverloadResolutionForCopyConstructor()
9864 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9865 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009866
Nico Weberafcc96a2012-01-23 03:19:29 +00009867 // C++11 [class.copy]p8:
9868 // ... If the class definition does not explicitly declare a copy
9869 // constructor, there is no user-declared move constructor, and there is no
9870 // user-declared move assignment operator, a copy constructor is implicitly
9871 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009872 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009873 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009874
Richard Smithbc2a35d2012-12-08 08:32:28 +00009875 // Note that we have declared this constructor.
9876 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9877
9878 if (Scope *S = getScopeForContext(ClassDecl))
9879 PushOnScopeChains(CopyConstructor, S, false);
9880 ClassDecl->addDecl(CopyConstructor);
9881
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009882 return CopyConstructor;
9883}
9884
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009885void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009886 CXXConstructorDecl *CopyConstructor) {
9887 assert((CopyConstructor->isDefaulted() &&
9888 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009889 !CopyConstructor->doesThisDeclarationHaveABody() &&
9890 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009891 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009892
Anders Carlsson63010a72010-04-23 16:24:12 +00009893 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009894 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009895
Richard Smith36155c12013-06-13 03:23:42 +00009896 // C++11 [class.copy]p7:
9897 // The [definition of an implicitly declared copy constructro] is
9898 // deprecated if the class has a user-declared copy assignment operator
9899 // or a user-declared destructor.
9900 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
9901 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
9902
Eli Friedman9a14db32012-10-18 20:14:08 +00009903 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009904 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009905
David Blaikie93c86172013-01-17 05:26:25 +00009906 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009907 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009908 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009909 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009910 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009911 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009912 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +00009913 CopyConstructor->setBody(ActOnCompoundStmt(
9914 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
9915 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009916 }
Robert Wilhelmc895f4d2013-08-19 20:51:20 +00009917
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009918 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009919 if (ASTMutationListener *L = getASTMutationListener()) {
9920 L->CompletedImplicitDefinition(CopyConstructor);
9921 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009922}
9923
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009924Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009925Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9926 CXXRecordDecl *ClassDecl = MD->getParent();
9927
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009928 // C++ [except.spec]p14:
9929 // An implicitly declared special member function (Clause 12) shall have an
9930 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009931 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009932 if (ClassDecl->isInvalidDecl())
9933 return ExceptSpec;
9934
9935 // Direct base-class constructors.
9936 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9937 BEnd = ClassDecl->bases_end();
9938 B != BEnd; ++B) {
9939 if (B->isVirtual()) // Handled below.
9940 continue;
9941
9942 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9943 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009944 CXXConstructorDecl *Constructor =
9945 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009946 // If this is a deleted function, add it anyway. This might be conformant
9947 // with the standard. This might not. I'm not sure. It might not matter.
9948 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009949 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009950 }
9951 }
9952
9953 // Virtual base-class constructors.
9954 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9955 BEnd = ClassDecl->vbases_end();
9956 B != BEnd; ++B) {
9957 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9958 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009959 CXXConstructorDecl *Constructor =
9960 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009961 // If this is a deleted function, add it anyway. This might be conformant
9962 // with the standard. This might not. I'm not sure. It might not matter.
9963 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009964 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009965 }
9966 }
9967
9968 // Field constructors.
9969 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9970 FEnd = ClassDecl->field_end();
9971 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009972 QualType FieldType = Context.getBaseElementType(F->getType());
9973 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9974 CXXConstructorDecl *Constructor =
9975 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009976 // If this is a deleted function, add it anyway. This might be conformant
9977 // with the standard. This might not. I'm not sure. It might not matter.
9978 // In particular, the problem is that this function never gets called. It
9979 // might just be ill-formed because this function attempts to refer to
9980 // a deleted function here.
9981 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009982 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009983 }
9984 }
9985
9986 return ExceptSpec;
9987}
9988
9989CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9990 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009991 // C++11 [class.copy]p9:
9992 // If the definition of a class X does not explicitly declare a move
9993 // constructor, one will be implicitly declared as defaulted if and only if:
9994 //
9995 // - [first 4 bullets]
9996 assert(ClassDecl->needsImplicitMoveConstructor());
9997
Richard Smithafb49182012-11-29 01:34:07 +00009998 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9999 if (DSM.isAlreadyBeingDeclared())
10000 return 0;
10001
Richard Smith1c931be2012-04-02 18:40:40 +000010002 // [Checked after we build the declaration]
10003 // - the move assignment operator would not be implicitly defined as
10004 // deleted,
10005
10006 // [DR1402]:
10007 // - each of X's non-static data members and direct or virtual base classes
10008 // has a type that either has a move constructor or is trivially copyable.
10009 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
10010 ClassDecl->setFailedImplicitMoveConstructor();
10011 return 0;
10012 }
10013
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010014 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10015 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010016
Richard Smith7756afa2012-06-10 05:43:50 +000010017 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10018 CXXMoveConstructor,
10019 false);
10020
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010021 DeclarationName Name
10022 = Context.DeclarationNames.getCXXConstructorName(
10023 Context.getCanonicalType(ClassType));
10024 SourceLocation ClassLoc = ClassDecl->getLocation();
10025 DeclarationNameInfo NameInfo(Name, ClassLoc);
10026
Richard Smitha8942d72013-05-07 03:19:20 +000010027 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010028 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010029 // member of its class.
10030 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +000010031 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +000010032 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010033 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010034 MoveConstructor->setAccess(AS_public);
10035 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010036
Richard Smithb9d0b762012-07-27 04:22:15 +000010037 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010038 FunctionProtoType::ExtProtoInfo EPI =
10039 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010040 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010041 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010042
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010043 // Add the parameter to the constructor.
10044 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10045 ClassLoc, ClassLoc,
10046 /*IdentifierInfo=*/0,
10047 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010048 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +000010049 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010050
Richard Smithbc2a35d2012-12-08 08:32:28 +000010051 MoveConstructor->setTrivial(
10052 ClassDecl->needsOverloadResolutionForMoveConstructor()
10053 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10054 : ClassDecl->hasTrivialMoveConstructor());
10055
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010056 // C++0x [class.copy]p9:
10057 // If the definition of a class X does not explicitly declare a move
10058 // constructor, one will be implicitly declared as defaulted if and only if:
10059 // [...]
10060 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +000010061 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010062 // Cache this result so that we don't try to generate this over and over
10063 // on every lookup, leaking memory and wasting time.
10064 ClassDecl->setFailedImplicitMoveConstructor();
10065 return 0;
10066 }
10067
10068 // Note that we have declared this constructor.
10069 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10070
10071 if (Scope *S = getScopeForContext(ClassDecl))
10072 PushOnScopeChains(MoveConstructor, S, false);
10073 ClassDecl->addDecl(MoveConstructor);
10074
10075 return MoveConstructor;
10076}
10077
10078void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10079 CXXConstructorDecl *MoveConstructor) {
10080 assert((MoveConstructor->isDefaulted() &&
10081 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010082 !MoveConstructor->doesThisDeclarationHaveABody() &&
10083 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010084 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10085
10086 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10087 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10088
Eli Friedman9a14db32012-10-18 20:14:08 +000010089 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010090 DiagnosticErrorTrap Trap(Diags);
10091
David Blaikie93c86172013-01-17 05:26:25 +000010092 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010093 Trap.hasErrorOccurred()) {
10094 Diag(CurrentLocation, diag::note_member_synthesized_at)
10095 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10096 MoveConstructor->setInvalidDecl();
10097 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010098 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010099 MoveConstructor->setBody(ActOnCompoundStmt(
10100 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10101 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010102 }
10103
10104 MoveConstructor->setUsed();
10105
10106 if (ASTMutationListener *L = getASTMutationListener()) {
10107 L->CompletedImplicitDefinition(MoveConstructor);
10108 }
10109}
10110
Douglas Gregore4e68d42012-02-15 19:33:52 +000010111bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanc4ef9482013-07-18 23:29:14 +000010112 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010113}
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010114
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010115/// \brief Mark the call operator of the given lambda closure type as "used".
10116static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
10117 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +000010118 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +000010119 Lambda->lookup(
10120 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010121 CallOperator->setReferenced();
10122 CallOperator->setUsed();
10123}
10124
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010125void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10126 SourceLocation CurrentLocation,
10127 CXXConversionDecl *Conv)
10128{
Manuel Klimek152b4e42013-08-22 12:12:24 +000010129 CXXRecordDecl *Lambda = Conv->getParent();
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010130
10131 // Make sure that the lambda call operator is marked used.
Manuel Klimek152b4e42013-08-22 12:12:24 +000010132 markLambdaCallOperatorUsed(*this, Lambda);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010133
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010134 Conv->setUsed();
10135
Eli Friedman9a14db32012-10-18 20:14:08 +000010136 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010137 DiagnosticErrorTrap Trap(Diags);
10138
Manuel Klimek152b4e42013-08-22 12:12:24 +000010139 // Return the address of the __invoke function.
10140 DeclarationName InvokeName = &Context.Idents.get("__invoke");
10141 CXXMethodDecl *Invoke
10142 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010143 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
10144 VK_LValue, Conv->getLocation()).take();
Manuel Klimek152b4e42013-08-22 12:12:24 +000010145 assert(FunctionRef && "Can't refer to __invoke function?");
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010146 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +000010147 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010148 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010149 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010150
Manuel Klimek152b4e42013-08-22 12:12:24 +000010151 // Fill in the __invoke function with a dummy implementation. IR generation
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010152 // will fill in the actual details.
10153 Invoke->setUsed();
10154 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +000010155 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010156
10157 if (ASTMutationListener *L = getASTMutationListener()) {
10158 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010159 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010160 }
10161}
10162
10163void Sema::DefineImplicitLambdaToBlockPointerConversion(
10164 SourceLocation CurrentLocation,
10165 CXXConversionDecl *Conv)
10166{
10167 Conv->setUsed();
10168
Eli Friedman9a14db32012-10-18 20:14:08 +000010169 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010170 DiagnosticErrorTrap Trap(Diags);
10171
Douglas Gregorac1303e2012-02-22 05:02:47 +000010172 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010173 Expr *This = ActOnCXXThis(CurrentLocation).take();
10174 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010175
Eli Friedman23f02672012-03-01 04:01:32 +000010176 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10177 Conv->getLocation(),
10178 Conv, DerefThis);
10179
10180 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10181 // behavior. Note that only the general conversion function does this
10182 // (since it's unusable otherwise); in the case where we inline the
10183 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000010184 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000010185 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10186 CK_CopyAndAutoreleaseBlockObject,
10187 BuildBlock.get(), 0, VK_RValue);
10188
10189 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010190 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000010191 Conv->setInvalidDecl();
10192 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010193 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010194
Douglas Gregorac1303e2012-02-22 05:02:47 +000010195 // Create the return statement that returns the block from the conversion
10196 // function.
Eli Friedman23f02672012-03-01 04:01:32 +000010197 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010198 if (Return.isInvalid()) {
10199 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10200 Conv->setInvalidDecl();
10201 return;
10202 }
10203
10204 // Set the body of the conversion function.
10205 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010206 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010207 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010208 Conv->getLocation()));
10209
Douglas Gregorac1303e2012-02-22 05:02:47 +000010210 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010211 if (ASTMutationListener *L = getASTMutationListener()) {
10212 L->CompletedImplicitDefinition(Conv);
10213 }
10214}
10215
Douglas Gregorf52757d2012-03-10 06:53:13 +000010216/// \brief Determine whether the given list arguments contains exactly one
10217/// "real" (non-default) argument.
10218static bool hasOneRealArgument(MultiExprArg Args) {
10219 switch (Args.size()) {
10220 case 0:
10221 return false;
10222
10223 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010224 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010225 return false;
10226
10227 // fall through
10228 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010229 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010230 }
10231
10232 return false;
10233}
10234
John McCall60d7b3a2010-08-24 06:29:42 +000010235ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010236Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010237 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010238 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010239 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010240 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010241 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010242 unsigned ConstructKind,
10243 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010244 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010245
Douglas Gregor2f599792010-04-02 18:24:57 +000010246 // C++0x [class.copy]p34:
10247 // When certain criteria are met, an implementation is allowed to
10248 // omit the copy/move construction of a class object, even if the
10249 // copy/move constructor and/or destructor for the object have
10250 // side effects. [...]
10251 // - when a temporary class object that has not been bound to a
10252 // reference (12.2) would be copied/moved to a class object
10253 // with the same cv-unqualified type, the copy/move operation
10254 // can be omitted by constructing the temporary object
10255 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010256 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010257 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010258 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010259 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010260 }
Mike Stump1eb44332009-09-09 15:08:12 +000010261
10262 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010263 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010264 IsListInitialization, RequiresZeroInit,
10265 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010266}
10267
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010268/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10269/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010270ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010271Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10272 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010273 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010274 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010275 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010276 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010277 unsigned ConstructKind,
10278 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010279 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010280 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010281 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010282 HadMultipleCandidates,
10283 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010284 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10285 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010286}
10287
John McCall68c6c9a2010-02-02 09:10:11 +000010288void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010289 if (VD->isInvalidDecl()) return;
10290
John McCall68c6c9a2010-02-02 09:10:11 +000010291 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010292 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010293 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010294 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010295
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010296 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010297 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010298 CheckDestructorAccess(VD->getLocation(), Destructor,
10299 PDiag(diag::err_access_dtor_var)
10300 << VD->getDeclName()
10301 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010302 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010303
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010304 if (!VD->hasGlobalStorage()) return;
10305
10306 // Emit warning for non-trivial dtor in global scope (a real global,
10307 // class-static, function-static).
10308 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10309
10310 // TODO: this should be re-enabled for static locals by !CXAAtExit
10311 if (!VD->isStaticLocal())
10312 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010313}
10314
Douglas Gregor39da0b82009-09-09 23:08:42 +000010315/// \brief Given a constructor and the set of arguments provided for the
10316/// constructor, convert the arguments and add any required default arguments
10317/// to form a proper call to this constructor.
10318///
10319/// \returns true if an error occurred, false otherwise.
10320bool
10321Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10322 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010323 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010324 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010325 bool AllowExplicit,
10326 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010327 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10328 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010329 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010330
10331 const FunctionProtoType *Proto
10332 = Constructor->getType()->getAs<FunctionProtoType>();
10333 assert(Proto && "Constructor without a prototype?");
10334 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010335
10336 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010337 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010338 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010339 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010340 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010341
10342 VariadicCallType CallType =
10343 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010344 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010345 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010346 Proto, 0,
10347 llvm::makeArrayRef(Args, NumArgs),
10348 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010349 CallType, AllowExplicit,
10350 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010351 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010352
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010353 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010354
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010355 CheckConstructorCall(Constructor,
10356 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10357 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010358 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010359
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010360 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010361}
10362
Anders Carlsson20d45d22009-12-12 00:32:00 +000010363static inline bool
10364CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10365 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010366 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010367 if (isa<NamespaceDecl>(DC)) {
10368 return SemaRef.Diag(FnDecl->getLocation(),
10369 diag::err_operator_new_delete_declared_in_namespace)
10370 << FnDecl->getDeclName();
10371 }
10372
10373 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010374 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010375 return SemaRef.Diag(FnDecl->getLocation(),
10376 diag::err_operator_new_delete_declared_static)
10377 << FnDecl->getDeclName();
10378 }
10379
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010380 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010381}
10382
Anders Carlsson156c78e2009-12-13 17:53:43 +000010383static inline bool
10384CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10385 CanQualType ExpectedResultType,
10386 CanQualType ExpectedFirstParamType,
10387 unsigned DependentParamTypeDiag,
10388 unsigned InvalidParamTypeDiag) {
10389 QualType ResultType =
10390 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10391
10392 // Check that the result type is not dependent.
10393 if (ResultType->isDependentType())
10394 return SemaRef.Diag(FnDecl->getLocation(),
10395 diag::err_operator_new_delete_dependent_result_type)
10396 << FnDecl->getDeclName() << ExpectedResultType;
10397
10398 // Check that the result type is what we expect.
10399 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10400 return SemaRef.Diag(FnDecl->getLocation(),
10401 diag::err_operator_new_delete_invalid_result_type)
10402 << FnDecl->getDeclName() << ExpectedResultType;
10403
10404 // A function template must have at least 2 parameters.
10405 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10406 return SemaRef.Diag(FnDecl->getLocation(),
10407 diag::err_operator_new_delete_template_too_few_parameters)
10408 << FnDecl->getDeclName();
10409
10410 // The function decl must have at least 1 parameter.
10411 if (FnDecl->getNumParams() == 0)
10412 return SemaRef.Diag(FnDecl->getLocation(),
10413 diag::err_operator_new_delete_too_few_parameters)
10414 << FnDecl->getDeclName();
10415
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010416 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010417 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10418 if (FirstParamType->isDependentType())
10419 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10420 << FnDecl->getDeclName() << ExpectedFirstParamType;
10421
10422 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010423 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010424 ExpectedFirstParamType)
10425 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10426 << FnDecl->getDeclName() << ExpectedFirstParamType;
10427
10428 return false;
10429}
10430
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010431static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010432CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010433 // C++ [basic.stc.dynamic.allocation]p1:
10434 // A program is ill-formed if an allocation function is declared in a
10435 // namespace scope other than global scope or declared static in global
10436 // scope.
10437 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10438 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010439
10440 CanQualType SizeTy =
10441 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10442
10443 // C++ [basic.stc.dynamic.allocation]p1:
10444 // The return type shall be void*. The first parameter shall have type
10445 // std::size_t.
10446 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10447 SizeTy,
10448 diag::err_operator_new_dependent_param_type,
10449 diag::err_operator_new_param_type))
10450 return true;
10451
10452 // C++ [basic.stc.dynamic.allocation]p1:
10453 // The first parameter shall not have an associated default argument.
10454 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010455 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010456 diag::err_operator_new_default_arg)
10457 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10458
10459 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010460}
10461
10462static bool
Richard Smith444d3842012-10-20 08:26:51 +000010463CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010464 // C++ [basic.stc.dynamic.deallocation]p1:
10465 // A program is ill-formed if deallocation functions are declared in a
10466 // namespace scope other than global scope or declared static in global
10467 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010468 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10469 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010470
10471 // C++ [basic.stc.dynamic.deallocation]p2:
10472 // Each deallocation function shall return void and its first parameter
10473 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010474 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10475 SemaRef.Context.VoidPtrTy,
10476 diag::err_operator_delete_dependent_param_type,
10477 diag::err_operator_delete_param_type))
10478 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010479
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010480 return false;
10481}
10482
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010483/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10484/// of this overloaded operator is well-formed. If so, returns false;
10485/// otherwise, emits appropriate diagnostics and returns true.
10486bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010487 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010488 "Expected an overloaded operator declaration");
10489
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010490 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10491
Mike Stump1eb44332009-09-09 15:08:12 +000010492 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010493 // The allocation and deallocation functions, operator new,
10494 // operator new[], operator delete and operator delete[], are
10495 // described completely in 3.7.3. The attributes and restrictions
10496 // found in the rest of this subclause do not apply to them unless
10497 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010498 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010499 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010500
Anders Carlssona3ccda52009-12-12 00:26:23 +000010501 if (Op == OO_New || Op == OO_Array_New)
10502 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010503
10504 // C++ [over.oper]p6:
10505 // An operator function shall either be a non-static member
10506 // function or be a non-member function and have at least one
10507 // parameter whose type is a class, a reference to a class, an
10508 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010509 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10510 if (MethodDecl->isStatic())
10511 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010512 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010513 } else {
10514 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010515 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10516 ParamEnd = FnDecl->param_end();
10517 Param != ParamEnd; ++Param) {
10518 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010519 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10520 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010521 ClassOrEnumParam = true;
10522 break;
10523 }
10524 }
10525
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010526 if (!ClassOrEnumParam)
10527 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010528 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010529 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010530 }
10531
10532 // C++ [over.oper]p8:
10533 // An operator function cannot have default arguments (8.3.6),
10534 // except where explicitly stated below.
10535 //
Mike Stump1eb44332009-09-09 15:08:12 +000010536 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010537 // (C++ [over.call]p1).
10538 if (Op != OO_Call) {
10539 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10540 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010541 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010542 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010543 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010544 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010545 }
10546 }
10547
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010548 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10549 { false, false, false }
10550#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10551 , { Unary, Binary, MemberOnly }
10552#include "clang/Basic/OperatorKinds.def"
10553 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010554
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010555 bool CanBeUnaryOperator = OperatorUses[Op][0];
10556 bool CanBeBinaryOperator = OperatorUses[Op][1];
10557 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010558
10559 // C++ [over.oper]p8:
10560 // [...] Operator functions cannot have more or fewer parameters
10561 // than the number required for the corresponding operator, as
10562 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010563 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010564 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010565 if (Op != OO_Call &&
10566 ((NumParams == 1 && !CanBeUnaryOperator) ||
10567 (NumParams == 2 && !CanBeBinaryOperator) ||
10568 (NumParams < 1) || (NumParams > 2))) {
10569 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010570 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010571 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010572 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010573 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010574 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010575 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010576 assert(CanBeBinaryOperator &&
10577 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010578 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010579 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010580
Chris Lattner416e46f2008-11-21 07:57:12 +000010581 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010582 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010583 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010584
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010585 // Overloaded operators other than operator() cannot be variadic.
10586 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010587 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010588 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010589 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010590 }
10591
10592 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010593 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10594 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010595 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010596 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010597 }
10598
10599 // C++ [over.inc]p1:
10600 // The user-defined function called operator++ implements the
10601 // prefix and postfix ++ operator. If this function is a member
10602 // function with no parameters, or a non-member function with one
10603 // parameter of class or enumeration type, it defines the prefix
10604 // increment operator ++ for objects of that type. If the function
10605 // is a member function with one parameter (which shall be of type
10606 // int) or a non-member function with two parameters (the second
10607 // of which shall be of type int), it defines the postfix
10608 // increment operator ++ for objects of that type.
10609 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10610 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10611 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010612 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010613 ParamIsInt = BT->getKind() == BuiltinType::Int;
10614
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010615 if (!ParamIsInt)
10616 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010617 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010618 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010619 }
10620
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010621 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010622}
Chris Lattner5a003a42008-12-17 07:09:26 +000010623
Sean Hunta6c058d2010-01-13 09:01:02 +000010624/// CheckLiteralOperatorDeclaration - Check whether the declaration
10625/// of this literal operator function is well-formed. If so, returns
10626/// false; otherwise, emits appropriate diagnostics and returns true.
10627bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010628 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010629 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10630 << FnDecl->getDeclName();
10631 return true;
10632 }
10633
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010634 if (FnDecl->isExternC()) {
10635 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10636 return true;
10637 }
10638
Sean Hunta6c058d2010-01-13 09:01:02 +000010639 bool Valid = false;
10640
Richard Smith36f5cfe2012-03-09 08:00:36 +000010641 // This might be the definition of a literal operator template.
10642 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10643 // This might be a specialization of a literal operator template.
10644 if (!TpDecl)
10645 TpDecl = FnDecl->getPrimaryTemplate();
10646
Sean Hunt216c2782010-04-07 23:11:06 +000010647 // template <char...> type operator "" name() is the only valid template
10648 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010649 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010650 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010651 // Must have only one template parameter
10652 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10653 if (Params->size() == 1) {
10654 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010655 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010656
Sean Hunt216c2782010-04-07 23:11:06 +000010657 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010658 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10659 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10660 Valid = true;
10661 }
10662 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010663 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010664 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010665 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10666
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010667 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010668
Sean Hunt30019c02010-04-07 22:57:35 +000010669 // unsigned long long int, long double, and any character type are allowed
10670 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010671 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10672 Context.hasSameType(T, Context.LongDoubleTy) ||
10673 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010674 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010675 Context.hasSameType(T, Context.Char16Ty) ||
10676 Context.hasSameType(T, Context.Char32Ty)) {
10677 if (++Param == FnDecl->param_end())
10678 Valid = true;
10679 goto FinishedParams;
10680 }
10681
Sean Hunt30019c02010-04-07 22:57:35 +000010682 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010683 const PointerType *PT = T->getAs<PointerType>();
10684 if (!PT)
10685 goto FinishedParams;
10686 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010687 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010688 goto FinishedParams;
10689 T = T.getUnqualifiedType();
10690
10691 // Move on to the second parameter;
10692 ++Param;
10693
10694 // If there is no second parameter, the first must be a const char *
10695 if (Param == FnDecl->param_end()) {
10696 if (Context.hasSameType(T, Context.CharTy))
10697 Valid = true;
10698 goto FinishedParams;
10699 }
10700
10701 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10702 // are allowed as the first parameter to a two-parameter function
10703 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010704 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010705 Context.hasSameType(T, Context.Char16Ty) ||
10706 Context.hasSameType(T, Context.Char32Ty)))
10707 goto FinishedParams;
10708
10709 // The second and final parameter must be an std::size_t
10710 T = (*Param)->getType().getUnqualifiedType();
10711 if (Context.hasSameType(T, Context.getSizeType()) &&
10712 ++Param == FnDecl->param_end())
10713 Valid = true;
10714 }
10715
10716 // FIXME: This diagnostic is absolutely terrible.
10717FinishedParams:
10718 if (!Valid) {
10719 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10720 << FnDecl->getDeclName();
10721 return true;
10722 }
10723
Richard Smitha9e88b22012-03-09 08:16:22 +000010724 // A parameter-declaration-clause containing a default argument is not
10725 // equivalent to any of the permitted forms.
10726 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10727 ParamEnd = FnDecl->param_end();
10728 Param != ParamEnd; ++Param) {
10729 if ((*Param)->hasDefaultArg()) {
10730 Diag((*Param)->getDefaultArgRange().getBegin(),
10731 diag::err_literal_operator_default_argument)
10732 << (*Param)->getDefaultArgRange();
10733 break;
10734 }
10735 }
10736
Richard Smith2fb4ae32012-03-08 02:39:21 +000010737 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010738 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10739 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010740 // C++11 [usrlit.suffix]p1:
10741 // Literal suffix identifiers that do not start with an underscore
10742 // are reserved for future standardization.
Richard Smith4ac537b2013-07-23 08:14:48 +000010743 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10744 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor1155c422011-08-30 22:40:35 +000010745 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010746
Sean Hunta6c058d2010-01-13 09:01:02 +000010747 return false;
10748}
10749
Douglas Gregor074149e2009-01-05 19:45:36 +000010750/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10751/// linkage specification, including the language and (if present)
10752/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10753/// the location of the language string literal, which is provided
10754/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10755/// the '{' brace. Otherwise, this linkage specification does not
10756/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010757Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10758 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010759 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010760 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010761 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010762 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010763 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010764 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010765 Language = LinkageSpecDecl::lang_cxx;
10766 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010767 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010768 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010769 }
Mike Stump1eb44332009-09-09 15:08:12 +000010770
Chris Lattnercc98eac2008-12-17 07:13:27 +000010771 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010772
Douglas Gregor074149e2009-01-05 19:45:36 +000010773 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010774 ExternLoc, LangLoc, Language,
10775 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010776 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010777 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010778 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010779}
10780
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010781/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010782/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10783/// valid, it's the position of the closing '}' brace in a linkage
10784/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010785Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010786 Decl *LinkageSpec,
10787 SourceLocation RBraceLoc) {
10788 if (LinkageSpec) {
10789 if (RBraceLoc.isValid()) {
10790 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10791 LSDecl->setRBraceLoc(RBraceLoc);
10792 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010793 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010794 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010795 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010796}
10797
Michael Han684aa732013-02-22 17:15:32 +000010798Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10799 AttributeList *AttrList,
10800 SourceLocation SemiLoc) {
10801 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10802 // Attribute declarations appertain to empty declaration so we handle
10803 // them here.
10804 if (AttrList)
10805 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010806
Michael Han684aa732013-02-22 17:15:32 +000010807 CurContext->addDecl(ED);
10808 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010809}
10810
Douglas Gregord308e622009-05-18 20:51:54 +000010811/// \brief Perform semantic analysis for the variable declaration that
10812/// occurs within a C++ catch clause, returning the newly-created
10813/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010814VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010815 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010816 SourceLocation StartLoc,
10817 SourceLocation Loc,
10818 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010819 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010820 QualType ExDeclType = TInfo->getType();
10821
Sebastian Redl4b07b292008-12-22 19:15:10 +000010822 // Arrays and functions decay.
10823 if (ExDeclType->isArrayType())
10824 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10825 else if (ExDeclType->isFunctionType())
10826 ExDeclType = Context.getPointerType(ExDeclType);
10827
10828 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10829 // The exception-declaration shall not denote a pointer or reference to an
10830 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010831 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010832 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010833 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010834 Invalid = true;
10835 }
Douglas Gregord308e622009-05-18 20:51:54 +000010836
Sebastian Redl4b07b292008-12-22 19:15:10 +000010837 QualType BaseType = ExDeclType;
10838 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010839 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010840 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010841 BaseType = Ptr->getPointeeType();
10842 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010843 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010844 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010845 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010846 BaseType = Ref->getPointeeType();
10847 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010848 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010849 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010850 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010851 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010852 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010853
Mike Stump1eb44332009-09-09 15:08:12 +000010854 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010855 RequireNonAbstractType(Loc, ExDeclType,
10856 diag::err_abstract_type_in_decl,
10857 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010858 Invalid = true;
10859
John McCall5a180392010-07-24 00:37:23 +000010860 // Only the non-fragile NeXT runtime currently supports C++ catches
10861 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010862 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010863 QualType T = ExDeclType;
10864 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10865 T = RT->getPointeeType();
10866
10867 if (T->isObjCObjectType()) {
10868 Diag(Loc, diag::err_objc_object_catch);
10869 Invalid = true;
10870 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010871 // FIXME: should this be a test for macosx-fragile specifically?
10872 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010873 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010874 }
10875 }
10876
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010877 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010878 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010879 ExDecl->setExceptionVariable(true);
10880
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010881 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010882 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010883 Invalid = true;
10884
Douglas Gregorc41b8782011-07-06 18:14:43 +000010885 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010886 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010887 // Insulate this from anything else we might currently be parsing.
10888 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10889
Douglas Gregor6d182892010-03-05 23:38:39 +000010890 // C++ [except.handle]p16:
10891 // The object declared in an exception-declaration or, if the
10892 // exception-declaration does not specify a name, a temporary (12.2) is
10893 // copy-initialized (8.5) from the exception object. [...]
10894 // The object is destroyed when the handler exits, after the destruction
10895 // of any automatic objects initialized within the handler.
10896 //
10897 // We just pretend to initialize the object with itself, then make sure
10898 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010899 QualType initType = ExDeclType;
10900
10901 InitializedEntity entity =
10902 InitializedEntity::InitializeVariable(ExDecl);
10903 InitializationKind initKind =
10904 InitializationKind::CreateCopy(Loc, SourceLocation());
10905
10906 Expr *opaqueValue =
10907 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000010908 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10909 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000010910 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010911 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010912 else {
10913 // If the constructor used was non-trivial, set this as the
10914 // "initializer".
10915 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10916 if (!construct->getConstructor()->isTrivial()) {
10917 Expr *init = MaybeCreateExprWithCleanups(construct);
10918 ExDecl->setInit(init);
10919 }
10920
10921 // And make sure it's destructable.
10922 FinalizeVarWithDestructor(ExDecl, recordType);
10923 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010924 }
10925 }
10926
Douglas Gregord308e622009-05-18 20:51:54 +000010927 if (Invalid)
10928 ExDecl->setInvalidDecl();
10929
10930 return ExDecl;
10931}
10932
10933/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10934/// handler.
John McCalld226f652010-08-21 09:40:31 +000010935Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010936 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010937 bool Invalid = D.isInvalidType();
10938
10939 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010940 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10941 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010942 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10943 D.getIdentifierLoc());
10944 Invalid = true;
10945 }
10946
Sebastian Redl4b07b292008-12-22 19:15:10 +000010947 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010948 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010949 LookupOrdinaryName,
10950 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010951 // The scope should be freshly made just for us. There is just no way
10952 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010953 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010954 if (PrevDecl->isTemplateParameter()) {
10955 // Maybe we will complain about the shadowed template parameter.
10956 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010957 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010958 }
10959 }
10960
Chris Lattnereaaebc72009-04-25 08:06:05 +000010961 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010962 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10963 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010964 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010965 }
10966
Douglas Gregor83cb9422010-09-09 17:09:21 +000010967 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010968 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010969 D.getIdentifierLoc(),
10970 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010971 if (Invalid)
10972 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010973
Sebastian Redl4b07b292008-12-22 19:15:10 +000010974 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010975 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010976 PushOnScopeChains(ExDecl, S);
10977 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010978 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010979
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010980 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010981 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010982}
Anders Carlssonfb311762009-03-14 00:25:26 +000010983
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010984Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010985 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010986 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010987 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010988 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010989
Richard Smithe3f470a2012-07-11 22:37:56 +000010990 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10991 return 0;
10992
10993 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10994 AssertMessage, RParenLoc, false);
10995}
10996
10997Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10998 Expr *AssertExpr,
10999 StringLiteral *AssertMessage,
11000 SourceLocation RParenLoc,
11001 bool Failed) {
11002 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11003 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000011004 // In a static_assert-declaration, the constant-expression shall be a
11005 // constant expression that can be contextually converted to bool.
11006 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11007 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011008 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000011009
Richard Smithdaaefc52011-12-14 23:32:26 +000011010 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000011011 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011012 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000011013 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011014 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000011015
Richard Smithe3f470a2012-07-11 22:37:56 +000011016 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011017 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000011018 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000011019 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011020 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000011021 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000011022 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000011023 }
Anders Carlssonc3082412009-03-14 00:33:21 +000011024 }
Mike Stump1eb44332009-09-09 15:08:12 +000011025
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011026 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000011027 AssertExpr, AssertMessage, RParenLoc,
11028 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000011029
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011030 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000011031 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000011032}
Sebastian Redl50de12f2009-03-24 22:27:57 +000011033
Douglas Gregor1d869352010-04-07 16:53:43 +000011034/// \brief Perform semantic analysis of the given friend type declaration.
11035///
11036/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000011037FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000011038 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011039 TypeSourceInfo *TSInfo) {
11040 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11041
11042 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000011043 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000011044
Richard Smith6b130222011-10-18 21:39:00 +000011045 // C++03 [class.friend]p2:
11046 // An elaborated-type-specifier shall be used in a friend declaration
11047 // for a class.*
11048 //
11049 // * The class-key of the elaborated-type-specifier is required.
11050 if (!ActiveTemplateInstantiations.empty()) {
11051 // Do not complain about the form of friend template types during
11052 // template instantiation; we will already have complained when the
11053 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011054 } else {
11055 if (!T->isElaboratedTypeSpecifier()) {
11056 // If we evaluated the type to a record type, suggest putting
11057 // a tag in front.
11058 if (const RecordType *RT = T->getAs<RecordType>()) {
11059 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000011060
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011061 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000011062
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011063 Diag(TypeRange.getBegin(),
11064 getLangOpts().CPlusPlus11 ?
11065 diag::warn_cxx98_compat_unelaborated_friend_type :
11066 diag::ext_unelaborated_friend_type)
11067 << (unsigned) RD->getTagKind()
11068 << T
11069 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11070 InsertionText);
11071 } else {
11072 Diag(FriendLoc,
11073 getLangOpts().CPlusPlus11 ?
11074 diag::warn_cxx98_compat_nonclass_type_friend :
11075 diag::ext_nonclass_type_friend)
11076 << T
11077 << TypeRange;
11078 }
11079 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000011080 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000011081 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011082 diag::warn_cxx98_compat_enum_friend :
11083 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000011084 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000011085 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000011086 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011087
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011088 // C++11 [class.friend]p3:
11089 // A friend declaration that does not declare a function shall have one
11090 // of the following forms:
11091 // friend elaborated-type-specifier ;
11092 // friend simple-type-specifier ;
11093 // friend typename-specifier ;
11094 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11095 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11096 }
Richard Smithd6f80da2012-09-20 01:31:00 +000011097
Douglas Gregor06245bf2010-04-07 17:57:12 +000011098 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000011099 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000011100 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000011101 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000011102}
11103
John McCall9a34edb2010-10-19 01:40:49 +000011104/// Handle a friend tag declaration where the scope specifier was
11105/// templated.
11106Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11107 unsigned TagSpec, SourceLocation TagLoc,
11108 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011109 IdentifierInfo *Name,
11110 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000011111 AttributeList *Attr,
11112 MultiTemplateParamsArg TempParamLists) {
11113 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11114
11115 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000011116 bool Invalid = false;
11117
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000011118 if (TemplateParameterList *TemplateParams =
11119 MatchTemplateParametersToScopeSpecifier(
11120 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11121 isExplicitSpecialization, Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000011122 if (TemplateParams->size() > 0) {
11123 // This is a declaration of a class template.
11124 if (Invalid)
11125 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000011126
Eric Christopher4110e132011-07-21 05:34:24 +000011127 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11128 SS, Name, NameLoc, Attr,
11129 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000011130 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000011131 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011132 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000011133 } else {
11134 // The "template<>" header is extraneous.
11135 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11136 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11137 isExplicitSpecialization = true;
11138 }
11139 }
11140
11141 if (Invalid) return 0;
11142
John McCall9a34edb2010-10-19 01:40:49 +000011143 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000011144 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011145 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000011146 isAllExplicitSpecializations = false;
11147 break;
11148 }
11149 }
11150
11151 // FIXME: don't ignore attributes.
11152
11153 // If it's explicit specializations all the way down, just forget
11154 // about the template header and build an appropriate non-templated
11155 // friend. TODO: for source fidelity, remember the headers.
11156 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011157 if (SS.isEmpty()) {
11158 bool Owned = false;
11159 bool IsDependent = false;
11160 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11161 Attr, AS_public,
11162 /*ModulePrivateLoc=*/SourceLocation(),
11163 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000011164 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011165 /*ScopedEnumUsesClassTag=*/false,
11166 /*UnderlyingType=*/TypeResult());
11167 }
11168
Douglas Gregor2494dd02011-03-01 01:34:45 +000011169 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000011170 ElaboratedTypeKeyword Keyword
11171 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011172 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000011173 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011174 if (T.isNull())
11175 return 0;
11176
11177 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11178 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000011179 DependentNameTypeLoc TL =
11180 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011181 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011182 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011183 TL.setNameLoc(NameLoc);
11184 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000011185 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011186 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000011187 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000011188 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011189 }
11190
11191 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011192 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011193 Friend->setAccess(AS_public);
11194 CurContext->addDecl(Friend);
11195 return Friend;
11196 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011197
11198 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11199
11200
John McCall9a34edb2010-10-19 01:40:49 +000011201
11202 // Handle the case of a templated-scope friend class. e.g.
11203 // template <class T> class A<T>::B;
11204 // FIXME: we don't support these right now.
11205 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11206 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11207 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011208 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011209 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011210 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011211 TL.setNameLoc(NameLoc);
11212
11213 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011214 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011215 Friend->setAccess(AS_public);
11216 Friend->setUnsupportedFriend(true);
11217 CurContext->addDecl(Friend);
11218 return Friend;
11219}
11220
11221
John McCalldd4a3b02009-09-16 22:47:08 +000011222/// Handle a friend type declaration. This works in tandem with
11223/// ActOnTag.
11224///
11225/// Notes on friend class templates:
11226///
11227/// We generally treat friend class declarations as if they were
11228/// declaring a class. So, for example, the elaborated type specifier
11229/// in a friend declaration is required to obey the restrictions of a
11230/// class-head (i.e. no typedefs in the scope chain), template
11231/// parameters are required to match up with simple template-ids, &c.
11232/// However, unlike when declaring a template specialization, it's
11233/// okay to refer to a template specialization without an empty
11234/// template parameter declaration, e.g.
11235/// friend class A<T>::B<unsigned>;
11236/// We permit this as a special case; if there are any template
11237/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011238/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011239Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011240 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011241 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011242
11243 assert(DS.isFriendSpecified());
11244 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11245
John McCalldd4a3b02009-09-16 22:47:08 +000011246 // Try to convert the decl specifier to a type. This works for
11247 // friend templates because ActOnTag never produces a ClassTemplateDecl
11248 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011249 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011250 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11251 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011252 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011253 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011254
Douglas Gregor6ccab972010-12-16 01:14:37 +000011255 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11256 return 0;
11257
John McCalldd4a3b02009-09-16 22:47:08 +000011258 // This is definitely an error in C++98. It's probably meant to
11259 // be forbidden in C++0x, too, but the specification is just
11260 // poorly written.
11261 //
11262 // The problem is with declarations like the following:
11263 // template <T> friend A<T>::foo;
11264 // where deciding whether a class C is a friend or not now hinges
11265 // on whether there exists an instantiation of A that causes
11266 // 'foo' to equal C. There are restrictions on class-heads
11267 // (which we declare (by fiat) elaborated friend declarations to
11268 // be) that makes this tractable.
11269 //
11270 // FIXME: handle "template <> friend class A<T>;", which
11271 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011272 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011273 Diag(Loc, diag::err_tagless_friend_type_template)
11274 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011275 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011276 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011277
John McCall02cace72009-08-28 07:59:38 +000011278 // C++98 [class.friend]p1: A friend of a class is a function
11279 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011280 // This is fixed in DR77, which just barely didn't make the C++03
11281 // deadline. It's also a very silly restriction that seriously
11282 // affects inner classes and which nobody else seems to implement;
11283 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011284 //
11285 // But note that we could warn about it: it's always useless to
11286 // friend one of your own members (it's not, however, worthless to
11287 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011288
John McCalldd4a3b02009-09-16 22:47:08 +000011289 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011290 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011291 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011292 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011293 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011294 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011295 DS.getFriendSpecLoc());
11296 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011297 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011298
11299 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011300 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011301
John McCalldd4a3b02009-09-16 22:47:08 +000011302 D->setAccess(AS_public);
11303 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011304
John McCalld226f652010-08-21 09:40:31 +000011305 return D;
John McCall02cace72009-08-28 07:59:38 +000011306}
11307
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011308NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11309 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011310 const DeclSpec &DS = D.getDeclSpec();
11311
11312 assert(DS.isFriendSpecified());
11313 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11314
11315 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011316 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011317
11318 // C++ [class.friend]p1
11319 // A friend of a class is a function or class....
11320 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011321 // It *doesn't* see through dependent types, which is correct
11322 // according to [temp.arg.type]p3:
11323 // If a declaration acquires a function type through a
11324 // type dependent on a template-parameter and this causes
11325 // a declaration that does not use the syntactic form of a
11326 // function declarator to have a function type, the program
11327 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011328 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011329 Diag(Loc, diag::err_unexpected_friend);
11330
11331 // It might be worthwhile to try to recover by creating an
11332 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011333 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011334 }
11335
11336 // C++ [namespace.memdef]p3
11337 // - If a friend declaration in a non-local class first declares a
11338 // class or function, the friend class or function is a member
11339 // of the innermost enclosing namespace.
11340 // - The name of the friend is not found by simple name lookup
11341 // until a matching declaration is provided in that namespace
11342 // scope (either before or after the class declaration granting
11343 // friendship).
11344 // - If a friend function is called, its name may be found by the
11345 // name lookup that considers functions from namespaces and
11346 // classes associated with the types of the function arguments.
11347 // - When looking for a prior declaration of a class or a function
11348 // declared as a friend, scopes outside the innermost enclosing
11349 // namespace scope are not considered.
11350
John McCall337ec3d2010-10-12 23:13:28 +000011351 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011352 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11353 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011354 assert(Name);
11355
Douglas Gregor6ccab972010-12-16 01:14:37 +000011356 // Check for unexpanded parameter packs.
11357 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11358 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11359 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11360 return 0;
11361
John McCall67d1a672009-08-06 02:15:43 +000011362 // The context we found the declaration in, or in which we should
11363 // create the declaration.
11364 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011365 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011366 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011367 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011368
Richard Smith4e9686b2013-08-09 04:35:01 +000011369 // There are five cases here.
11370 // - There's no scope specifier and we're in a local class. Only look
11371 // for functions declared in the immediately-enclosing block scope.
11372 // We recover from invalid scope qualifiers as if they just weren't there.
11373 FunctionDecl *FunctionContainingLocalClass = 0;
11374 if ((SS.isInvalid() || !SS.isSet()) &&
11375 (FunctionContainingLocalClass =
11376 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11377 // C++11 [class.friend]p11:
John McCall29ae6e52010-10-13 05:45:15 +000011378 // If a friend declaration appears in a local class and the name
11379 // specified is an unqualified name, a prior declaration is
11380 // looked up without considering scopes that are outside the
11381 // innermost enclosing non-class scope. For a friend function
11382 // declaration, if there is no prior declaration, the program is
11383 // ill-formed.
Richard Smith4e9686b2013-08-09 04:35:01 +000011384
11385 // Find the innermost enclosing non-class scope. This is the block
11386 // scope containing the local class definition (or for a nested class,
11387 // the outer local class).
11388 DCScope = S->getFnParent();
11389
11390 // Look up the function name in the scope.
11391 Previous.clear(LookupLocalFriendName);
11392 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11393
11394 if (!Previous.empty()) {
11395 // All possible previous declarations must have the same context:
11396 // either they were declared at block scope or they are members of
11397 // one of the enclosing local classes.
11398 DC = Previous.getRepresentativeDecl()->getDeclContext();
11399 } else {
11400 // This is ill-formed, but provide the context that we would have
11401 // declared the function in, if we were permitted to, for error recovery.
11402 DC = FunctionContainingLocalClass;
11403 }
11404
11405 // C++ [class.friend]p6:
11406 // A function can be defined in a friend declaration of a class if and
11407 // only if the class is a non-local class (9.8), the function name is
11408 // unqualified, and the function has namespace scope.
11409 if (D.isFunctionDefinition()) {
11410 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11411 }
11412
11413 // - There's no scope specifier, in which case we just go to the
11414 // appropriate scope and look for a function or function template
11415 // there as appropriate.
11416 } else if (SS.isInvalid() || !SS.isSet()) {
11417 // C++11 [namespace.memdef]p3:
11418 // If the name in a friend declaration is neither qualified nor
11419 // a template-id and the declaration is a function or an
11420 // elaborated-type-specifier, the lookup to determine whether
11421 // the entity has been previously declared shall not consider
11422 // any scopes outside the innermost enclosing namespace.
John McCall8a407372010-10-14 22:22:28 +000011423 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011424
John McCall29ae6e52010-10-13 05:45:15 +000011425 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011426 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011427
Rafael Espindola11dc6342013-04-25 20:12:36 +000011428 // Skip class contexts. If someone can cite chapter and verse
11429 // for this behavior, that would be nice --- it's what GCC and
11430 // EDG do, and it seems like a reasonable intent, but the spec
11431 // really only says that checks for unqualified existing
11432 // declarations should stop at the nearest enclosing namespace,
11433 // not that they should only consider the nearest enclosing
11434 // namespace.
11435 while (DC->isRecord())
11436 DC = DC->getParent();
11437
11438 DeclContext *LookupDC = DC;
11439 while (LookupDC->isTransparentContext())
11440 LookupDC = LookupDC->getParent();
11441
11442 while (true) {
11443 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011444
Rafael Espindola11dc6342013-04-25 20:12:36 +000011445 if (!Previous.empty()) {
11446 DC = LookupDC;
11447 break;
John McCall8a407372010-10-14 22:22:28 +000011448 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011449
11450 if (isTemplateId) {
11451 if (isa<TranslationUnitDecl>(LookupDC)) break;
11452 } else {
11453 if (LookupDC->isFileContext()) break;
11454 }
11455 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011456 }
11457
John McCall380aaa42010-10-13 06:22:15 +000011458 DCScope = getScopeForDeclContext(S, DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011459
John McCall337ec3d2010-10-12 23:13:28 +000011460 // - There's a non-dependent scope specifier, in which case we
11461 // compute it and do a previous lookup there for a function
11462 // or function template.
11463 } else if (!SS.getScopeRep()->isDependent()) {
11464 DC = computeDeclContext(SS);
11465 if (!DC) return 0;
11466
11467 if (RequireCompleteDeclContext(SS, DC)) return 0;
11468
11469 LookupQualifiedName(Previous, DC);
11470
11471 // Ignore things found implicitly in the wrong scope.
11472 // TODO: better diagnostics for this case. Suggesting the right
11473 // qualified scope would be nice...
11474 LookupResult::Filter F = Previous.makeFilter();
11475 while (F.hasNext()) {
11476 NamedDecl *D = F.next();
11477 if (!DC->InEnclosingNamespaceSetOf(
11478 D->getDeclContext()->getRedeclContext()))
11479 F.erase();
11480 }
11481 F.done();
11482
11483 if (Previous.empty()) {
11484 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011485 Diag(Loc, diag::err_qualified_friend_not_found)
11486 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011487 return 0;
11488 }
11489
11490 // C++ [class.friend]p1: A friend of a class is a function or
11491 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011492 if (DC->Equals(CurContext))
11493 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011494 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011495 diag::warn_cxx98_compat_friend_is_member :
11496 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011497
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011498 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011499 // C++ [class.friend]p6:
11500 // A function can be defined in a friend declaration of a class if and
11501 // only if the class is a non-local class (9.8), the function name is
11502 // unqualified, and the function has namespace scope.
11503 SemaDiagnosticBuilder DB
11504 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11505
11506 DB << SS.getScopeRep();
11507 if (DC->isFileContext())
11508 DB << FixItHint::CreateRemoval(SS.getRange());
11509 SS.clear();
11510 }
John McCall337ec3d2010-10-12 23:13:28 +000011511
11512 // - There's a scope specifier that does not match any template
11513 // parameter lists, in which case we use some arbitrary context,
11514 // create a method or method template, and wait for instantiation.
11515 // - There's a scope specifier that does match some template
11516 // parameter lists, which we don't handle right now.
11517 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011518 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011519 // C++ [class.friend]p6:
11520 // A function can be defined in a friend declaration of a class if and
11521 // only if the class is a non-local class (9.8), the function name is
11522 // unqualified, and the function has namespace scope.
11523 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11524 << SS.getScopeRep();
11525 }
11526
John McCall337ec3d2010-10-12 23:13:28 +000011527 DC = CurContext;
11528 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011529 }
Douglas Gregor883af832011-10-10 01:11:59 +000011530
John McCall29ae6e52010-10-13 05:45:15 +000011531 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011532 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011533 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11534 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11535 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011536 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011537 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11538 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011539 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011540 }
John McCall67d1a672009-08-06 02:15:43 +000011541 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011542
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011543 // FIXME: This is an egregious hack to cope with cases where the scope stack
11544 // does not contain the declaration context, i.e., in an out-of-line
11545 // definition of a class.
11546 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11547 if (!DCScope) {
11548 FakeDCScope.setEntity(DC);
11549 DCScope = &FakeDCScope;
11550 }
Richard Smith4e9686b2013-08-09 04:35:01 +000011551
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011552 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011553 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011554 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011555 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011556
Douglas Gregor182ddf02009-09-28 00:08:27 +000011557 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011558
Richard Smith4e9686b2013-08-09 04:35:01 +000011559 // If we performed typo correction, we might have added a scope specifier
11560 // and changed the decl context.
11561 DC = ND->getDeclContext();
11562
John McCallab88d972009-08-31 22:39:49 +000011563 // Add the function declaration to the appropriate lookup tables,
11564 // adjusting the redeclarations list as necessary. We don't
11565 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011566 //
John McCallab88d972009-08-31 22:39:49 +000011567 // Also update the scope-based lookup if the target context's
11568 // lookup context is in lexical scope.
11569 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011570 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011571 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011572 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011573 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011574 }
John McCall02cace72009-08-28 07:59:38 +000011575
11576 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011577 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011578 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011579 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011580 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011581
John McCall1f2e1a92012-08-10 03:15:35 +000011582 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011583 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011584 } else {
11585 if (DC->isRecord()) CheckFriendAccess(ND);
11586
John McCall6102ca12010-10-16 06:59:13 +000011587 FunctionDecl *FD;
11588 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11589 FD = FTD->getTemplatedDecl();
11590 else
11591 FD = cast<FunctionDecl>(ND);
11592
David Majnemerf6a144f2013-06-25 23:09:30 +000011593 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11594 // default argument expression, that declaration shall be a definition
11595 // and shall be the only declaration of the function or function
11596 // template in the translation unit.
11597 if (functionDeclHasDefaultArgument(FD)) {
11598 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11599 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11600 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11601 } else if (!D.isFunctionDefinition())
11602 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11603 }
11604
John McCall6102ca12010-10-16 06:59:13 +000011605 // Mark templated-scope function declarations as unsupported.
11606 if (FD->getNumTemplateParameterLists())
11607 FrD->setUnsupportedFriend(true);
11608 }
John McCall337ec3d2010-10-12 23:13:28 +000011609
John McCalld226f652010-08-21 09:40:31 +000011610 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011611}
11612
John McCalld226f652010-08-21 09:40:31 +000011613void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11614 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011615
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011616 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011617 if (!Fn) {
11618 Diag(DelLoc, diag::err_deleted_non_function);
11619 return;
11620 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011621
Douglas Gregoref96ee02012-01-14 16:38:05 +000011622 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011623 // Don't consider the implicit declaration we generate for explicit
11624 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011625 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11626 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011627 Diag(DelLoc, diag::err_deleted_decl_not_first);
11628 Diag(Prev->getLocation(), diag::note_previous_declaration);
11629 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011630 // If the declaration wasn't the first, we delete the function anyway for
11631 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011632 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011633 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011634
11635 if (Fn->isDeleted())
11636 return;
11637
11638 // See if we're deleting a function which is already known to override a
11639 // non-deleted virtual function.
11640 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11641 bool IssuedDiagnostic = false;
11642 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11643 E = MD->end_overridden_methods();
11644 I != E; ++I) {
11645 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11646 if (!IssuedDiagnostic) {
11647 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11648 IssuedDiagnostic = true;
11649 }
11650 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11651 }
11652 }
11653 }
11654
Sean Hunt10620eb2011-05-06 20:44:56 +000011655 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011656}
Sebastian Redl13e88542009-04-27 21:33:24 +000011657
Sean Hunte4246a62011-05-12 06:15:49 +000011658void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011659 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011660
11661 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011662 if (MD->getParent()->isDependentType()) {
11663 MD->setDefaulted();
11664 MD->setExplicitlyDefaulted();
11665 return;
11666 }
11667
Sean Hunte4246a62011-05-12 06:15:49 +000011668 CXXSpecialMember Member = getSpecialMember(MD);
11669 if (Member == CXXInvalid) {
Eli Friedmanfcb5a252013-07-11 23:55:07 +000011670 if (!MD->isInvalidDecl())
11671 Diag(DefaultLoc, diag::err_default_special_members);
Sean Hunte4246a62011-05-12 06:15:49 +000011672 return;
11673 }
11674
11675 MD->setDefaulted();
11676 MD->setExplicitlyDefaulted();
11677
Sean Huntcd10dec2011-05-23 23:14:04 +000011678 // If this definition appears within the record, do the checking when
11679 // the record is complete.
11680 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011681 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011682 // Find the uninstantiated declaration that actually had the '= default'
11683 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011684 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011685
Richard Smith12fef492013-03-27 00:22:47 +000011686 // If the method was defaulted on its first declaration, we will have
11687 // already performed the checking in CheckCompletedCXXClass. Such a
11688 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011689 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011690 return;
11691
Richard Smithb9d0b762012-07-27 04:22:15 +000011692 CheckExplicitlyDefaultedSpecialMember(MD);
11693
Richard Smith1d28caf2012-12-11 01:14:52 +000011694 // The exception specification is needed because we are defining the
11695 // function.
11696 ResolveExceptionSpec(DefaultLoc,
11697 MD->getType()->castAs<FunctionProtoType>());
11698
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011699 if (MD->isInvalidDecl())
11700 return;
11701
Sean Hunte4246a62011-05-12 06:15:49 +000011702 switch (Member) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011703 case CXXDefaultConstructor:
11704 DefineImplicitDefaultConstructor(DefaultLoc,
11705 cast<CXXConstructorDecl>(MD));
Sean Hunt49634cf2011-05-13 06:10:58 +000011706 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011707 case CXXCopyConstructor:
11708 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunte4246a62011-05-12 06:15:49 +000011709 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011710 case CXXCopyAssignment:
11711 DefineImplicitCopyAssignment(DefaultLoc, MD);
Sean Hunt2b188082011-05-14 05:23:28 +000011712 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011713 case CXXDestructor:
11714 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Sean Huntcb45a0f2011-05-12 22:46:25 +000011715 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011716 case CXXMoveConstructor:
11717 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunt82713172011-05-25 23:16:36 +000011718 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011719 case CXXMoveAssignment:
11720 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011721 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011722 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011723 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011724 }
11725 } else {
11726 Diag(DefaultLoc, diag::err_default_special_members);
11727 }
11728}
11729
Sebastian Redl13e88542009-04-27 21:33:24 +000011730static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011731 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011732 Stmt *SubStmt = *CI;
11733 if (!SubStmt)
11734 continue;
11735 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011736 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011737 diag::err_return_in_constructor_handler);
11738 if (!isa<Expr>(SubStmt))
11739 SearchForReturnInStmt(Self, SubStmt);
11740 }
11741}
11742
11743void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11744 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11745 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11746 SearchForReturnInStmt(*this, Handler);
11747 }
11748}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011749
David Blaikie299adab2013-01-18 23:03:15 +000011750bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011751 const CXXMethodDecl *Old) {
11752 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11753 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11754
11755 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11756
11757 // If the calling conventions match, everything is fine
11758 if (NewCC == OldCC)
11759 return false;
11760
Reid Kleckneref072032013-08-27 23:08:25 +000011761 Diag(New->getLocation(),
11762 diag::err_conflicting_overriding_cc_attributes)
11763 << New->getDeclName() << New->getType() << Old->getType();
11764 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11765 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011766}
11767
Mike Stump1eb44332009-09-09 15:08:12 +000011768bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011769 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011770 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11771 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011772
Chandler Carruth73857792010-02-15 11:53:20 +000011773 if (Context.hasSameType(NewTy, OldTy) ||
11774 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011775 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011776
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011777 // Check if the return types are covariant
11778 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011779
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011780 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011781 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11782 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011783 NewClassTy = NewPT->getPointeeType();
11784 OldClassTy = OldPT->getPointeeType();
11785 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011786 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11787 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11788 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11789 NewClassTy = NewRT->getPointeeType();
11790 OldClassTy = OldRT->getPointeeType();
11791 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011792 }
11793 }
Mike Stump1eb44332009-09-09 15:08:12 +000011794
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011795 // The return types aren't either both pointers or references to a class type.
11796 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011797 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011798 diag::err_different_return_type_for_overriding_virtual_function)
11799 << New->getDeclName() << NewTy << OldTy;
11800 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011801
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011802 return true;
11803 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011804
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011805 // C++ [class.virtual]p6:
11806 // If the return type of D::f differs from the return type of B::f, the
11807 // class type in the return type of D::f shall be complete at the point of
11808 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011809 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11810 if (!RT->isBeingDefined() &&
11811 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011812 diag::err_covariant_return_incomplete,
11813 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011814 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011815 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011816
Douglas Gregora4923eb2009-11-16 21:35:15 +000011817 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011818 // Check if the new class derives from the old class.
11819 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11820 Diag(New->getLocation(),
11821 diag::err_covariant_return_not_derived)
11822 << New->getDeclName() << NewTy << OldTy;
11823 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11824 return true;
11825 }
Mike Stump1eb44332009-09-09 15:08:12 +000011826
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011827 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011828 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011829 diag::err_covariant_return_inaccessible_base,
11830 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11831 // FIXME: Should this point to the return type?
11832 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011833 // FIXME: this note won't trigger for delayed access control
11834 // diagnostics, and it's impossible to get an undelayed error
11835 // here from access control during the original parse because
11836 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011837 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11838 return true;
11839 }
11840 }
Mike Stump1eb44332009-09-09 15:08:12 +000011841
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011842 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011843 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011844 Diag(New->getLocation(),
11845 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011846 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011847 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11848 return true;
11849 };
Mike Stump1eb44332009-09-09 15:08:12 +000011850
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011851
11852 // The new class type must have the same or less qualifiers as the old type.
11853 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11854 Diag(New->getLocation(),
11855 diag::err_covariant_return_type_class_type_more_qualified)
11856 << New->getDeclName() << NewTy << OldTy;
11857 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11858 return true;
11859 };
Mike Stump1eb44332009-09-09 15:08:12 +000011860
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011861 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011862}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011863
Douglas Gregor4ba31362009-12-01 17:24:26 +000011864/// \brief Mark the given method pure.
11865///
11866/// \param Method the method to be marked pure.
11867///
11868/// \param InitRange the source range that covers the "0" initializer.
11869bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011870 SourceLocation EndLoc = InitRange.getEnd();
11871 if (EndLoc.isValid())
11872 Method->setRangeEnd(EndLoc);
11873
Douglas Gregor4ba31362009-12-01 17:24:26 +000011874 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11875 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011876 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011877 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011878
11879 if (!Method->isInvalidDecl())
11880 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11881 << Method->getDeclName() << InitRange;
11882 return true;
11883}
11884
Douglas Gregor552e2992012-02-21 02:22:07 +000011885/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011886static bool isStaticDataMember(const Decl *D) {
11887 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
11888 return Var->isStaticDataMember();
11889
11890 return false;
Douglas Gregor552e2992012-02-21 02:22:07 +000011891}
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011892
John McCall731ad842009-12-19 09:28:58 +000011893/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11894/// an initializer for the out-of-line declaration 'Dcl'. The scope
11895/// is a fresh scope pushed for just this purpose.
11896///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011897/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11898/// static data member of class X, names should be looked up in the scope of
11899/// class X.
John McCalld226f652010-08-21 09:40:31 +000011900void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011901 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011902 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011903
John McCall731ad842009-12-19 09:28:58 +000011904 // We should only get called for declarations with scope specifiers, like:
11905 // int foo::bar;
11906 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011907 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011908
11909 // If we are parsing the initializer for a static data member, push a
11910 // new expression evaluation context that is associated with this static
11911 // data member.
11912 if (isStaticDataMember(D))
11913 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011914}
11915
11916/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011917/// initializer for the out-of-line declaration 'D'.
11918void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011919 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011920 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011921
Douglas Gregor552e2992012-02-21 02:22:07 +000011922 if (isStaticDataMember(D))
11923 PopExpressionEvaluationContext();
11924
John McCall731ad842009-12-19 09:28:58 +000011925 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011926 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011927}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011928
11929/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11930/// C++ if/switch/while/for statement.
11931/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011932DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011933 // C++ 6.4p2:
11934 // The declarator shall not specify a function or an array.
11935 // The type-specifier-seq shall not contain typedef and shall not declare a
11936 // new class or enumeration.
11937 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11938 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011939
11940 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011941 if (!Dcl)
11942 return true;
11943
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011944 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11945 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011946 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011947 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011948 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011949
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011950 return Dcl;
11951}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011952
Douglas Gregordfe65432011-07-28 19:11:31 +000011953void Sema::LoadExternalVTableUses() {
11954 if (!ExternalSource)
11955 return;
11956
11957 SmallVector<ExternalVTableUse, 4> VTables;
11958 ExternalSource->ReadUsedVTables(VTables);
11959 SmallVector<VTableUse, 4> NewUses;
11960 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11961 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11962 = VTablesUsed.find(VTables[I].Record);
11963 // Even if a definition wasn't required before, it may be required now.
11964 if (Pos != VTablesUsed.end()) {
11965 if (!Pos->second && VTables[I].DefinitionRequired)
11966 Pos->second = true;
11967 continue;
11968 }
11969
11970 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11971 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11972 }
11973
11974 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11975}
11976
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011977void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11978 bool DefinitionRequired) {
11979 // Ignore any vtable uses in unevaluated operands or for classes that do
11980 // not have a vtable.
11981 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000011982 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011983 return;
11984
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011985 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011986 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011987 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11988 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11989 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11990 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011991 // If we already had an entry, check to see if we are promoting this vtable
11992 // to required a definition. If so, we need to reappend to the VTableUses
11993 // list, since we may have already processed the first entry.
11994 if (DefinitionRequired && !Pos.first->second) {
11995 Pos.first->second = true;
11996 } else {
11997 // Otherwise, we can early exit.
11998 return;
11999 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012000 }
12001
12002 // Local classes need to have their virtual members marked
12003 // immediately. For all other classes, we mark their virtual members
12004 // at the end of the translation unit.
12005 if (Class->isLocalClass())
12006 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000012007 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012008 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000012009}
12010
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012011bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000012012 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012013 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000012014 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000012015
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012016 // Note: The VTableUses vector could grow as a result of marking
12017 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000012018 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012019 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000012020 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012021 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000012022 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012023 if (!Class)
12024 continue;
12025
12026 SourceLocation Loc = VTableUses[I].second;
12027
Richard Smithb9d0b762012-07-27 04:22:15 +000012028 bool DefineVTable = true;
12029
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012030 // If this class has a key function, but that key function is
12031 // defined in another translation unit, we don't need to emit the
12032 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000012033 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000012034 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolafc218132013-08-26 23:23:21 +000012035 // The key function is in another translation unit.
12036 DefineVTable = false;
12037 TemplateSpecializationKind TSK =
12038 KeyFunction->getTemplateSpecializationKind();
12039 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12040 TSK != TSK_ImplicitInstantiation &&
12041 "Instantiations don't have key functions");
12042 (void)TSK;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012043 } else if (!KeyFunction) {
12044 // If we have a class with no key function that is the subject
12045 // of an explicit instantiation declaration, suppress the
12046 // vtable; it will live with the explicit instantiation
12047 // definition.
12048 bool IsExplicitInstantiationDeclaration
12049 = Class->getTemplateSpecializationKind()
12050 == TSK_ExplicitInstantiationDeclaration;
12051 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
12052 REnd = Class->redecls_end();
12053 R != REnd; ++R) {
12054 TemplateSpecializationKind TSK
12055 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
12056 if (TSK == TSK_ExplicitInstantiationDeclaration)
12057 IsExplicitInstantiationDeclaration = true;
12058 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12059 IsExplicitInstantiationDeclaration = false;
12060 break;
12061 }
12062 }
12063
12064 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000012065 DefineVTable = false;
12066 }
12067
12068 // The exception specifications for all virtual members may be needed even
12069 // if we are not providing an authoritative form of the vtable in this TU.
12070 // We may choose to emit it available_externally anyway.
12071 if (!DefineVTable) {
12072 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12073 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012074 }
12075
12076 // Mark all of the virtual members of this class as referenced, so
12077 // that we can build a vtable. Then, tell the AST consumer that a
12078 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000012079 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012080 MarkVirtualMembersReferenced(Loc, Class);
12081 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12082 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12083
12084 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000012085 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012086 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000012087 const FunctionDecl *KeyFunctionDef = 0;
12088 if (!KeyFunction ||
12089 (KeyFunction->hasBody(KeyFunctionDef) &&
12090 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000012091 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12092 TSK_ExplicitInstantiationDefinition
12093 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12094 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012095 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012096 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012097 VTableUses.clear();
12098
Douglas Gregor78844032011-04-22 22:25:37 +000012099 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012100}
Anders Carlssond6a637f2009-12-07 08:24:59 +000012101
Richard Smithb9d0b762012-07-27 04:22:15 +000012102void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12103 const CXXRecordDecl *RD) {
12104 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12105 E = RD->method_end(); I != E; ++I)
12106 if ((*I)->isVirtual() && !(*I)->isPure())
12107 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12108}
12109
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012110void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12111 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000012112 // Mark all functions which will appear in RD's vtable as used.
12113 CXXFinalOverriderMap FinalOverriders;
12114 RD->getFinalOverriders(FinalOverriders);
12115 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12116 E = FinalOverriders.end();
12117 I != E; ++I) {
12118 for (OverridingMethods::const_iterator OI = I->second.begin(),
12119 OE = I->second.end();
12120 OI != OE; ++OI) {
12121 assert(OI->second.size() > 0 && "no final overrider");
12122 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000012123
Richard Smithff817f72012-07-07 06:59:51 +000012124 // C++ [basic.def.odr]p2:
12125 // [...] A virtual member function is used if it is not pure. [...]
12126 if (!Overrider->isPure())
12127 MarkFunctionReferenced(Loc, Overrider);
12128 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012129 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012130
12131 // Only classes that have virtual bases need a VTT.
12132 if (RD->getNumVBases() == 0)
12133 return;
12134
12135 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12136 e = RD->bases_end(); i != e; ++i) {
12137 const CXXRecordDecl *Base =
12138 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012139 if (Base->getNumVBases() == 0)
12140 continue;
12141 MarkVirtualMembersReferenced(Loc, Base);
12142 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012143}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012144
12145/// SetIvarInitializers - This routine builds initialization ASTs for the
12146/// Objective-C implementation whose ivars need be initialized.
12147void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012148 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012149 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000012150 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000012151 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012152 CollectIvarsToConstructOrDestruct(OID, ivars);
12153 if (ivars.empty())
12154 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000012155 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012156 for (unsigned i = 0; i < ivars.size(); i++) {
12157 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012158 if (Field->isInvalidDecl())
12159 continue;
12160
Sean Huntcbb67482011-01-08 20:30:50 +000012161 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012162 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12163 InitializationKind InitKind =
12164 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000012165
12166 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12167 ExprResult MemberInit =
12168 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000012169 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012170 // Note, MemberInit could actually come back empty if no initialization
12171 // is required (e.g., because it would call a trivial default constructor)
12172 if (!MemberInit.get() || MemberInit.isInvalid())
12173 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000012174
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012175 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000012176 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12177 SourceLocation(),
12178 MemberInit.takeAs<Expr>(),
12179 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012180 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012181
12182 // Be sure that the destructor is accessible and is marked as referenced.
12183 if (const RecordType *RecordTy
12184 = Context.getBaseElementType(Field->getType())
12185 ->getAs<RecordType>()) {
12186 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000012187 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012188 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012189 CheckDestructorAccess(Field->getLocation(), Destructor,
12190 PDiag(diag::err_access_dtor_ivar)
12191 << Context.getBaseElementType(Field->getType()));
12192 }
12193 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012194 }
12195 ObjCImplementation->setIvarInitializers(Context,
12196 AllToInit.data(), AllToInit.size());
12197 }
12198}
Sean Huntfe57eef2011-05-04 05:57:24 +000012199
Sean Huntebcbe1d2011-05-04 23:29:54 +000012200static
12201void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12202 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12203 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12204 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12205 Sema &S) {
Sean Huntebcbe1d2011-05-04 23:29:54 +000012206 if (Ctor->isInvalidDecl())
12207 return;
12208
Richard Smitha8eaf002012-08-23 06:16:52 +000012209 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12210
12211 // Target may not be determinable yet, for instance if this is a dependent
12212 // call in an uninstantiated template.
12213 if (Target) {
12214 const FunctionDecl *FNTarget = 0;
12215 (void)Target->hasBody(FNTarget);
12216 Target = const_cast<CXXConstructorDecl*>(
12217 cast_or_null<CXXConstructorDecl>(FNTarget));
12218 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012219
12220 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12221 // Avoid dereferencing a null pointer here.
12222 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12223
12224 if (!Current.insert(Canonical))
12225 return;
12226
12227 // We know that beyond here, we aren't chaining into a cycle.
12228 if (!Target || !Target->isDelegatingConstructor() ||
12229 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012230 Valid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012231 Current.clear();
12232 // We've hit a cycle.
12233 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12234 Current.count(TCanonical)) {
12235 // If we haven't diagnosed this cycle yet, do so now.
12236 if (!Invalid.count(TCanonical)) {
12237 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012238 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012239 << Ctor;
12240
Richard Smitha8eaf002012-08-23 06:16:52 +000012241 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012242 if (TCanonical != Canonical)
12243 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12244
12245 CXXConstructorDecl *C = Target;
12246 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012247 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012248 (void)C->getTargetConstructor()->hasBody(FNTarget);
12249 assert(FNTarget && "Ctor cycle through bodiless function");
12250
Richard Smitha8eaf002012-08-23 06:16:52 +000012251 C = const_cast<CXXConstructorDecl*>(
12252 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012253 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12254 }
12255 }
12256
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012257 Invalid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012258 Current.clear();
12259 } else {
12260 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12261 }
12262}
12263
12264
Sean Huntfe57eef2011-05-04 05:57:24 +000012265void Sema::CheckDelegatingCtorCycles() {
12266 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12267
Douglas Gregor0129b562011-07-27 21:57:17 +000012268 for (DelegatingCtorDeclsType::iterator
12269 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012270 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012271 I != E; ++I)
12272 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012273
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012274 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12275 CE = Invalid.end();
12276 CI != CE; ++CI)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012277 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012278}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012279
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012280namespace {
12281 /// \brief AST visitor that finds references to the 'this' expression.
12282 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12283 Sema &S;
12284
12285 public:
12286 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12287
12288 bool VisitCXXThisExpr(CXXThisExpr *E) {
12289 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12290 << E->isImplicit();
12291 return false;
12292 }
12293 };
12294}
12295
12296bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12297 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12298 if (!TSInfo)
12299 return false;
12300
12301 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012302 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012303 if (!ProtoTL)
12304 return false;
12305
12306 // C++11 [expr.prim.general]p3:
12307 // [The expression this] shall not appear before the optional
12308 // cv-qualifier-seq and it shall not appear within the declaration of a
12309 // static member function (although its type and value category are defined
12310 // within a static member function as they are within a non-static member
12311 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012312 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012313 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012314 FindCXXThisExpr Finder(*this);
12315
12316 // If the return type came after the cv-qualifier-seq, check it now.
12317 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012318 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012319 return true;
12320
12321 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012322 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12323 return true;
12324
12325 return checkThisInStaticMemberFunctionAttributes(Method);
12326}
12327
12328bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12329 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12330 if (!TSInfo)
12331 return false;
12332
12333 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012334 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012335 if (!ProtoTL)
12336 return false;
12337
David Blaikie39e6ab42013-02-18 22:06:02 +000012338 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012339 FindCXXThisExpr Finder(*this);
12340
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012341 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012342 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012343 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012344 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012345 case EST_DynamicNone:
12346 case EST_MSAny:
12347 case EST_None:
12348 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012349
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012350 case EST_ComputedNoexcept:
12351 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12352 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012353
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012354 case EST_Dynamic:
12355 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012356 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012357 E != EEnd; ++E) {
12358 if (!Finder.TraverseType(*E))
12359 return true;
12360 }
12361 break;
12362 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012363
12364 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012365}
12366
12367bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12368 FindCXXThisExpr Finder(*this);
12369
12370 // Check attributes.
12371 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12372 A != AEnd; ++A) {
12373 // FIXME: This should be emitted by tblgen.
12374 Expr *Arg = 0;
12375 ArrayRef<Expr *> Args;
12376 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12377 Arg = G->getArg();
12378 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12379 Arg = G->getArg();
12380 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12381 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12382 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12383 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12384 else if (ExclusiveLockFunctionAttr *ELF
12385 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12386 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12387 else if (SharedLockFunctionAttr *SLF
12388 = dyn_cast<SharedLockFunctionAttr>(*A))
12389 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12390 else if (ExclusiveTrylockFunctionAttr *ETLF
12391 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12392 Arg = ETLF->getSuccessValue();
12393 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12394 } else if (SharedTrylockFunctionAttr *STLF
12395 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12396 Arg = STLF->getSuccessValue();
12397 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12398 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12399 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12400 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12401 Arg = LR->getArg();
12402 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12403 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12404 else if (ExclusiveLocksRequiredAttr *ELR
12405 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12406 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12407 else if (SharedLocksRequiredAttr *SLR
12408 = dyn_cast<SharedLocksRequiredAttr>(*A))
12409 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12410
12411 if (Arg && !Finder.TraverseStmt(Arg))
12412 return true;
12413
12414 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12415 if (!Finder.TraverseStmt(Args[I]))
12416 return true;
12417 }
12418 }
12419
12420 return false;
12421}
12422
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012423void
12424Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12425 ArrayRef<ParsedType> DynamicExceptions,
12426 ArrayRef<SourceRange> DynamicExceptionRanges,
12427 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012428 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012429 FunctionProtoType::ExtProtoInfo &EPI) {
12430 Exceptions.clear();
12431 EPI.ExceptionSpecType = EST;
12432 if (EST == EST_Dynamic) {
12433 Exceptions.reserve(DynamicExceptions.size());
12434 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12435 // FIXME: Preserve type source info.
12436 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12437
12438 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12439 collectUnexpandedParameterPacks(ET, Unexpanded);
12440 if (!Unexpanded.empty()) {
12441 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12442 UPPC_ExceptionType,
12443 Unexpanded);
12444 continue;
12445 }
12446
12447 // Check that the type is valid for an exception spec, and
12448 // drop it if not.
12449 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12450 Exceptions.push_back(ET);
12451 }
12452 EPI.NumExceptions = Exceptions.size();
12453 EPI.Exceptions = Exceptions.data();
12454 return;
12455 }
12456
12457 if (EST == EST_ComputedNoexcept) {
12458 // If an error occurred, there's no expression here.
12459 if (NoexceptExpr) {
12460 assert((NoexceptExpr->isTypeDependent() ||
12461 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12462 Context.BoolTy) &&
12463 "Parser should have made sure that the expression is boolean");
12464 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12465 EPI.ExceptionSpecType = EST_BasicNoexcept;
12466 return;
12467 }
12468
12469 if (!NoexceptExpr->isValueDependent())
12470 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012471 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012472 /*AllowFold*/ false).take();
12473 EPI.NoexceptExpr = NoexceptExpr;
12474 }
12475 return;
12476 }
12477}
12478
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012479/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12480Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12481 // Implicitly declared functions (e.g. copy constructors) are
12482 // __host__ __device__
12483 if (D->isImplicit())
12484 return CFT_HostDevice;
12485
12486 if (D->hasAttr<CUDAGlobalAttr>())
12487 return CFT_Global;
12488
12489 if (D->hasAttr<CUDADeviceAttr>()) {
12490 if (D->hasAttr<CUDAHostAttr>())
12491 return CFT_HostDevice;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012492 return CFT_Device;
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012493 }
12494
12495 return CFT_Host;
12496}
12497
12498bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12499 CUDAFunctionTarget CalleeTarget) {
12500 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12501 // Callable from the device only."
12502 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12503 return true;
12504
12505 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12506 // Callable from the host only."
12507 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12508 // Callable from the host only."
12509 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12510 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12511 return true;
12512
12513 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12514 return true;
12515
12516 return false;
12517}
John McCall76da55d2013-04-16 07:28:30 +000012518
12519/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12520///
12521MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12522 SourceLocation DeclStart,
12523 Declarator &D, Expr *BitWidth,
12524 InClassInitStyle InitStyle,
12525 AccessSpecifier AS,
12526 AttributeList *MSPropertyAttr) {
12527 IdentifierInfo *II = D.getIdentifier();
12528 if (!II) {
12529 Diag(DeclStart, diag::err_anonymous_property);
12530 return NULL;
12531 }
12532 SourceLocation Loc = D.getIdentifierLoc();
12533
12534 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12535 QualType T = TInfo->getType();
12536 if (getLangOpts().CPlusPlus) {
12537 CheckExtraCXXDefaultArguments(D);
12538
12539 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12540 UPPC_DataMemberType)) {
12541 D.setInvalidType();
12542 T = Context.IntTy;
12543 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12544 }
12545 }
12546
12547 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12548
12549 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12550 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12551 diag::err_invalid_thread)
12552 << DeclSpec::getSpecifierName(TSCS);
12553
12554 // Check to see if this name was declared as a member previously
12555 NamedDecl *PrevDecl = 0;
12556 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12557 LookupName(Previous, S);
12558 switch (Previous.getResultKind()) {
12559 case LookupResult::Found:
12560 case LookupResult::FoundUnresolvedValue:
12561 PrevDecl = Previous.getAsSingle<NamedDecl>();
12562 break;
12563
12564 case LookupResult::FoundOverloaded:
12565 PrevDecl = Previous.getRepresentativeDecl();
12566 break;
12567
12568 case LookupResult::NotFound:
12569 case LookupResult::NotFoundInCurrentInstantiation:
12570 case LookupResult::Ambiguous:
12571 break;
12572 }
12573
12574 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12575 // Maybe we will complain about the shadowed template parameter.
12576 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12577 // Just pretend that we didn't see the previous declaration.
12578 PrevDecl = 0;
12579 }
12580
12581 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12582 PrevDecl = 0;
12583
12584 SourceLocation TSSL = D.getLocStart();
12585 MSPropertyDecl *NewPD;
12586 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12587 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12588 II, T, TInfo, TSSL,
12589 Data.GetterId, Data.SetterId);
12590 ProcessDeclAttributes(TUScope, NewPD, D);
12591 NewPD->setAccess(AS);
12592
12593 if (NewPD->isInvalidDecl())
12594 Record->setInvalidDecl();
12595
12596 if (D.getDeclSpec().isModulePrivateSpecified())
12597 NewPD->setModulePrivate();
12598
12599 if (NewPD->isInvalidDecl() && PrevDecl) {
12600 // Don't introduce NewFD into scope; there's already something
12601 // with the same name in the same scope.
12602 } else if (II) {
12603 PushOnScopeChains(NewPD, S);
12604 } else
12605 Record->addDecl(NewPD);
12606
12607 return NewPD;
12608}