blob: 3df0472df6b9e7cf5d5359251436dcc4cfe83e8a [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,
954 llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
955 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
1252 Current = Queue.back();
1253 Queue.pop_back();
1254 }
1255
1256 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001257}
1258
Mike Stump1eb44332009-09-09 15:08:12 +00001259/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001260///
1261/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1262/// and returns NULL otherwise.
1263CXXBaseSpecifier *
1264Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1265 SourceRange SpecifierRange,
1266 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001267 TypeSourceInfo *TInfo,
1268 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001269 QualType BaseType = TInfo->getType();
1270
Douglas Gregor2943aed2009-03-03 04:44:36 +00001271 // C++ [class.union]p1:
1272 // A union shall not have base classes.
1273 if (Class->isUnion()) {
1274 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1275 << SpecifierRange;
1276 return 0;
1277 }
1278
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001279 if (EllipsisLoc.isValid() &&
1280 !TInfo->getType()->containsUnexpandedParameterPack()) {
1281 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1282 << TInfo->getTypeLoc().getSourceRange();
1283 EllipsisLoc = SourceLocation();
1284 }
Douglas Gregord777e282012-11-10 01:18:17 +00001285
1286 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1287
1288 if (BaseType->isDependentType()) {
1289 // Make sure that we don't have circular inheritance among our dependent
1290 // bases. For non-dependent bases, the check for completeness below handles
1291 // this.
1292 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1293 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1294 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001295 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001296 Diag(BaseLoc, diag::err_circular_inheritance)
1297 << BaseType << Context.getTypeDeclType(Class);
1298
1299 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1300 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1301 << BaseType;
1302
1303 return 0;
1304 }
1305 }
1306
Mike Stump1eb44332009-09-09 15:08:12 +00001307 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001308 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001309 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001310 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001311
1312 // Base specifiers must be record types.
1313 if (!BaseType->isRecordType()) {
1314 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1315 return 0;
1316 }
1317
1318 // C++ [class.union]p1:
1319 // A union shall not be used as a base class.
1320 if (BaseType->isUnionType()) {
1321 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1322 return 0;
1323 }
1324
1325 // C++ [class.derived]p2:
1326 // The class-name in a base-specifier shall not be an incompletely
1327 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001328 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001329 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001330 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001331 return 0;
John McCall572fc622010-08-17 07:23:57 +00001332 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001333
Eli Friedman1d954f62009-08-15 21:55:26 +00001334 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001335 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001336 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001337 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001338 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer2f686692013-06-22 06:43:58 +00001339 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001340 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001341
Anders Carlsson1d209272011-03-25 14:55:14 +00001342 // C++ [class]p3:
1343 // If a class is marked final and it appears as a base-type-specifier in
1344 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001345 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001346 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1347 << CXXBaseDecl->getDeclName();
1348 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1349 << CXXBaseDecl->getDeclName();
1350 return 0;
1351 }
1352
John McCall572fc622010-08-17 07:23:57 +00001353 if (BaseDecl->isInvalidDecl())
1354 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001355
1356 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001357 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001358 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001359 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001360}
1361
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001362/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1363/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001364/// example:
1365/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001366/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001367BaseResult
John McCalld226f652010-08-21 09:40:31 +00001368Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001369 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001370 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001371 ParsedType basetype, SourceLocation BaseLoc,
1372 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001373 if (!classdecl)
1374 return true;
1375
Douglas Gregor40808ce2009-03-09 23:48:35 +00001376 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001377 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001378 if (!Class)
1379 return true;
1380
Richard Smith05321402013-02-19 23:47:15 +00001381 // We do not support any C++11 attributes on base-specifiers yet.
1382 // Diagnose any attributes we see.
1383 if (!Attributes.empty()) {
1384 for (AttributeList *Attr = Attributes.getList(); Attr;
1385 Attr = Attr->getNext()) {
1386 if (Attr->isInvalid() ||
1387 Attr->getKind() == AttributeList::IgnoredAttribute)
1388 continue;
1389 Diag(Attr->getLoc(),
1390 Attr->getKind() == AttributeList::UnknownAttribute
1391 ? diag::warn_unknown_attribute_ignored
1392 : diag::err_base_specifier_attribute)
1393 << Attr->getName();
1394 }
1395 }
1396
Nick Lewycky56062202010-07-26 16:56:01 +00001397 TypeSourceInfo *TInfo = 0;
1398 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001399
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001400 if (EllipsisLoc.isInvalid() &&
1401 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001402 UPPC_BaseType))
1403 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001404
Douglas Gregor2943aed2009-03-03 04:44:36 +00001405 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001406 Virtual, Access, TInfo,
1407 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001408 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001409 else
1410 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Douglas Gregor2943aed2009-03-03 04:44:36 +00001412 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001413}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001414
Douglas Gregor2943aed2009-03-03 04:44:36 +00001415/// \brief Performs the actual work of attaching the given base class
1416/// specifiers to a C++ class.
1417bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1418 unsigned NumBases) {
1419 if (NumBases == 0)
1420 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001421
1422 // Used to keep track of which base types we have already seen, so
1423 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001424 // that the key is always the unqualified canonical type of the base
1425 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001426 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1427
1428 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001429 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001430 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001431 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001432 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001433 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001434 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001435
1436 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1437 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001438 // C++ [class.mi]p3:
1439 // A class shall not be specified as a direct base class of a
1440 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001441 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001442 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001443 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001444 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001445
1446 // Delete the duplicate base class specifier; we're going to
1447 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001448 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001449
1450 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001451 } else {
1452 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001453 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001454 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001455 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1456 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1457 if (Class->isInterface() &&
1458 (!RD->isInterface() ||
1459 KnownBase->getAccessSpecifier() != AS_public)) {
1460 // The Microsoft extension __interface does not permit bases that
1461 // are not themselves public interfaces.
1462 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1463 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1464 << RD->getSourceRange();
1465 Invalid = true;
1466 }
1467 if (RD->hasAttr<WeakAttr>())
1468 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1469 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001470 }
1471 }
1472
1473 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001474 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001475
1476 // Delete the remaining (good) base class specifiers, since their
1477 // data has been copied into the CXXRecordDecl.
1478 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001479 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001480
1481 return Invalid;
1482}
1483
1484/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1485/// class, after checking whether there are any duplicate base
1486/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001487void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001488 unsigned NumBases) {
1489 if (!ClassDecl || !Bases || !NumBases)
1490 return;
1491
1492 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelm0d317a02013-07-22 05:04:01 +00001493 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001494}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001495
Douglas Gregora8f32e02009-10-06 17:59:45 +00001496/// \brief Determine whether the type \p Derived is a C++ class that is
1497/// derived from the type \p Base.
1498bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001499 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001500 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001501
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001502 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001503 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001504 return false;
1505
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001506 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001507 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001508 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001509
1510 // If either the base or the derived type is invalid, don't try to
1511 // check whether one is derived from the other.
1512 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1513 return false;
1514
John McCall86ff3082010-02-04 22:26:26 +00001515 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1516 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001517}
1518
1519/// \brief Determine whether the type \p Derived is a C++ class that is
1520/// derived from the type \p Base.
1521bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001522 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001523 return false;
1524
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001525 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001526 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001527 return false;
1528
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001529 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001530 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001531 return false;
1532
Douglas Gregora8f32e02009-10-06 17:59:45 +00001533 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1534}
1535
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001536void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001537 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001538 assert(BasePathArray.empty() && "Base path array must be empty!");
1539 assert(Paths.isRecordingPaths() && "Must record paths!");
1540
1541 const CXXBasePath &Path = Paths.front();
1542
1543 // We first go backward and check if we have a virtual base.
1544 // FIXME: It would be better if CXXBasePath had the base specifier for
1545 // the nearest virtual base.
1546 unsigned Start = 0;
1547 for (unsigned I = Path.size(); I != 0; --I) {
1548 if (Path[I - 1].Base->isVirtual()) {
1549 Start = I - 1;
1550 break;
1551 }
1552 }
1553
1554 // Now add all bases.
1555 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001556 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001557}
1558
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001559/// \brief Determine whether the given base path includes a virtual
1560/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001561bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1562 for (CXXCastPath::const_iterator B = BasePath.begin(),
1563 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001564 B != BEnd; ++B)
1565 if ((*B)->isVirtual())
1566 return true;
1567
1568 return false;
1569}
1570
Douglas Gregora8f32e02009-10-06 17:59:45 +00001571/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1572/// conversion (where Derived and Base are class types) is
1573/// well-formed, meaning that the conversion is unambiguous (and
1574/// that all of the base classes are accessible). Returns true
1575/// and emits a diagnostic if the code is ill-formed, returns false
1576/// otherwise. Loc is the location where this routine should point to
1577/// if there is an error, and Range is the source range to highlight
1578/// if there is an error.
1579bool
1580Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001581 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001582 unsigned AmbigiousBaseConvID,
1583 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001584 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001585 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001586 // First, determine whether the path from Derived to Base is
1587 // ambiguous. This is slightly more expensive than checking whether
1588 // the Derived to Base conversion exists, because here we need to
1589 // explore multiple paths to determine if there is an ambiguity.
1590 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1591 /*DetectVirtual=*/false);
1592 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1593 assert(DerivationOkay &&
1594 "Can only be used with a derived-to-base conversion");
1595 (void)DerivationOkay;
1596
1597 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001598 if (InaccessibleBaseID) {
1599 // Check that the base class can be accessed.
1600 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1601 InaccessibleBaseID)) {
1602 case AR_inaccessible:
1603 return true;
1604 case AR_accessible:
1605 case AR_dependent:
1606 case AR_delayed:
1607 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001608 }
John McCall6b2accb2010-02-10 09:31:12 +00001609 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001610
1611 // Build a base path if necessary.
1612 if (BasePath)
1613 BuildBasePathArray(Paths, *BasePath);
1614 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001615 }
1616
David Majnemer2f686692013-06-22 06:43:58 +00001617 if (AmbigiousBaseConvID) {
1618 // We know that the derived-to-base conversion is ambiguous, and
1619 // we're going to produce a diagnostic. Perform the derived-to-base
1620 // search just one more time to compute all of the possible paths so
1621 // that we can print them out. This is more expensive than any of
1622 // the previous derived-to-base checks we've done, but at this point
1623 // performance isn't as much of an issue.
1624 Paths.clear();
1625 Paths.setRecordingPaths(true);
1626 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1627 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1628 (void)StillOkay;
1629
1630 // Build up a textual representation of the ambiguous paths, e.g.,
1631 // D -> B -> A, that will be used to illustrate the ambiguous
1632 // conversions in the diagnostic. We only print one of the paths
1633 // to each base class subobject.
1634 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1635
1636 Diag(Loc, AmbigiousBaseConvID)
1637 << Derived << Base << PathDisplayStr << Range << Name;
1638 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001639 return true;
1640}
1641
1642bool
1643Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001644 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001645 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001646 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001647 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001648 IgnoreAccess ? 0
1649 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001650 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001651 Loc, Range, DeclarationName(),
1652 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001653}
1654
1655
1656/// @brief Builds a string representing ambiguous paths from a
1657/// specific derived class to different subobjects of the same base
1658/// class.
1659///
1660/// This function builds a string that can be used in error messages
1661/// to show the different paths that one can take through the
1662/// inheritance hierarchy to go from the derived class to different
1663/// subobjects of a base class. The result looks something like this:
1664/// @code
1665/// struct D -> struct B -> struct A
1666/// struct D -> struct C -> struct A
1667/// @endcode
1668std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1669 std::string PathDisplayStr;
1670 std::set<unsigned> DisplayedPaths;
1671 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1672 Path != Paths.end(); ++Path) {
1673 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1674 // We haven't displayed a path to this particular base
1675 // class subobject yet.
1676 PathDisplayStr += "\n ";
1677 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1678 for (CXXBasePath::const_iterator Element = Path->begin();
1679 Element != Path->end(); ++Element)
1680 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1681 }
1682 }
1683
1684 return PathDisplayStr;
1685}
1686
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001687//===----------------------------------------------------------------------===//
1688// C++ class member Handling
1689//===----------------------------------------------------------------------===//
1690
Abramo Bagnara6206d532010-06-05 05:09:32 +00001691/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001692bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1693 SourceLocation ASLoc,
1694 SourceLocation ColonLoc,
1695 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001696 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001697 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001698 ASLoc, ColonLoc);
1699 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001700 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001701}
1702
Richard Smitha4b39652012-08-06 03:25:17 +00001703/// CheckOverrideControl - Check C++11 override control semantics.
1704void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001705 if (D->isInvalidDecl())
1706 return;
1707
Chris Lattner5f9e2722011-07-23 10:55:15 +00001708 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001709
Richard Smitha4b39652012-08-06 03:25:17 +00001710 // Do we know which functions this declaration might be overriding?
1711 bool OverridesAreKnown = !MD ||
1712 (!MD->getParent()->hasAnyDependentBases() &&
1713 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001714
Richard Smitha4b39652012-08-06 03:25:17 +00001715 if (!MD || !MD->isVirtual()) {
1716 if (OverridesAreKnown) {
1717 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1718 Diag(OA->getLocation(),
1719 diag::override_keyword_only_allowed_on_virtual_member_functions)
1720 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1721 D->dropAttr<OverrideAttr>();
1722 }
1723 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1724 Diag(FA->getLocation(),
1725 diag::override_keyword_only_allowed_on_virtual_member_functions)
1726 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1727 D->dropAttr<FinalAttr>();
1728 }
1729 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001730 return;
1731 }
Richard Smitha4b39652012-08-06 03:25:17 +00001732
1733 if (!OverridesAreKnown)
1734 return;
1735
1736 // C++11 [class.virtual]p5:
1737 // If a virtual function is marked with the virt-specifier override and
1738 // does not override a member function of a base class, the program is
1739 // ill-formed.
1740 bool HasOverriddenMethods =
1741 MD->begin_overridden_methods() != MD->end_overridden_methods();
1742 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1743 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1744 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001745}
1746
Richard Smitha4b39652012-08-06 03:25:17 +00001747/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001748/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001749/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001750bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1751 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001752 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001753 return false;
1754
1755 Diag(New->getLocation(), diag::err_final_function_overridden)
1756 << New->getDeclName();
1757 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1758 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001759}
1760
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001761static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001762 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1763 // FIXME: Destruction of ObjC lifetime types has side-effects.
1764 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1765 return !RD->isCompleteDefinition() ||
1766 !RD->hasTrivialDefaultConstructor() ||
1767 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001768 return false;
1769}
1770
John McCall76da55d2013-04-16 07:28:30 +00001771static AttributeList *getMSPropertyAttr(AttributeList *list) {
1772 for (AttributeList* it = list; it != 0; it = it->getNext())
1773 if (it->isDeclspecPropertyAttribute())
1774 return it;
1775 return 0;
1776}
1777
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001778/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1779/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001780/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001781/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1782/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001783NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001784Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001785 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001786 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001787 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001788 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001789 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1790 DeclarationName Name = NameInfo.getName();
1791 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001792
1793 // For anonymous bitfields, the location should point to the type.
1794 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001795 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001796
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001797 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001798
John McCall4bde1e12010-06-04 08:34:12 +00001799 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001800 assert(!DS.isFriendSpecified());
1801
Richard Smith1ab0d902011-06-25 02:28:38 +00001802 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001803
John McCalle402e722012-09-25 07:32:39 +00001804 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1805 // The Microsoft extension __interface only permits public member functions
1806 // and prohibits constructors, destructors, operators, non-public member
1807 // functions, static methods and data members.
1808 unsigned InvalidDecl;
1809 bool ShowDeclName = true;
1810 if (!isFunc)
1811 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1812 else if (AS != AS_public)
1813 InvalidDecl = 2;
1814 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1815 InvalidDecl = 3;
1816 else switch (Name.getNameKind()) {
1817 case DeclarationName::CXXConstructorName:
1818 InvalidDecl = 4;
1819 ShowDeclName = false;
1820 break;
1821
1822 case DeclarationName::CXXDestructorName:
1823 InvalidDecl = 5;
1824 ShowDeclName = false;
1825 break;
1826
1827 case DeclarationName::CXXOperatorName:
1828 case DeclarationName::CXXConversionFunctionName:
1829 InvalidDecl = 6;
1830 break;
1831
1832 default:
1833 InvalidDecl = 0;
1834 break;
1835 }
1836
1837 if (InvalidDecl) {
1838 if (ShowDeclName)
1839 Diag(Loc, diag::err_invalid_member_in_interface)
1840 << (InvalidDecl-1) << Name;
1841 else
1842 Diag(Loc, diag::err_invalid_member_in_interface)
1843 << (InvalidDecl-1) << "";
1844 return 0;
1845 }
1846 }
1847
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001848 // C++ 9.2p6: A member shall not be declared to have automatic storage
1849 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001850 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1851 // data members and cannot be applied to names declared const or static,
1852 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001853 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001854 case DeclSpec::SCS_unspecified:
1855 case DeclSpec::SCS_typedef:
1856 case DeclSpec::SCS_static:
1857 break;
1858 case DeclSpec::SCS_mutable:
1859 if (isFunc) {
1860 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Richard Smithec642442013-04-12 22:46:28 +00001862 // FIXME: It would be nicer if the keyword was ignored only for this
1863 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001864 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001865 }
1866 break;
1867 default:
1868 Diag(DS.getStorageClassSpecLoc(),
1869 diag::err_storageclass_invalid_for_member);
1870 D.getMutableDeclSpec().ClearStorageClassSpecs();
1871 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001872 }
1873
Sebastian Redl669d5d72008-11-14 23:42:31 +00001874 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1875 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001876 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001877
David Blaikie1d87fba2013-01-30 01:22:18 +00001878 if (DS.isConstexprSpecified() && isInstField) {
1879 SemaDiagnosticBuilder B =
1880 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1881 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1882 if (InitStyle == ICIS_NoInit) {
1883 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1884 D.getMutableDeclSpec().ClearConstexprSpec();
1885 const char *PrevSpec;
1886 unsigned DiagID;
1887 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1888 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001889 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001890 assert(!Failed && "Making a constexpr member const shouldn't fail");
1891 } else {
1892 B << 1;
1893 const char *PrevSpec;
1894 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001895 if (D.getMutableDeclSpec().SetStorageClassSpec(
1896 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001897 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001898 "This is the only DeclSpec that should fail to be applied");
1899 B << 1;
1900 } else {
1901 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1902 isInstField = false;
1903 }
1904 }
1905 }
1906
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001907 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001908 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001909 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001910
1911 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001912 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001913 Diag(Loc, diag::err_bad_variable_name)
1914 << Name;
1915 return 0;
1916 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001917
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001918 IdentifierInfo *II = Name.getAsIdentifierInfo();
1919
Douglas Gregorf2503652011-09-21 14:40:46 +00001920 // Member field could not be with "template" keyword.
1921 // So TemplateParameterLists should be empty in this case.
1922 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001923 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001924 if (TemplateParams->size()) {
1925 // There is no such thing as a member field template.
1926 Diag(D.getIdentifierLoc(), diag::err_template_member)
1927 << II
1928 << SourceRange(TemplateParams->getTemplateLoc(),
1929 TemplateParams->getRAngleLoc());
1930 } else {
1931 // There is an extraneous 'template<>' for this member.
1932 Diag(TemplateParams->getTemplateLoc(),
1933 diag::err_template_member_noparams)
1934 << II
1935 << SourceRange(TemplateParams->getTemplateLoc(),
1936 TemplateParams->getRAngleLoc());
1937 }
1938 return 0;
1939 }
1940
Douglas Gregor922fff22010-10-13 22:19:53 +00001941 if (SS.isSet() && !SS.isInvalid()) {
1942 // The user provided a superfluous scope specifier inside a class
1943 // definition:
1944 //
1945 // class X {
1946 // int X::member;
1947 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001948 if (DeclContext *DC = computeDeclContext(SS, false))
1949 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001950 else
1951 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1952 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001953
Douglas Gregor922fff22010-10-13 22:19:53 +00001954 SS.clear();
1955 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001956
John McCall76da55d2013-04-16 07:28:30 +00001957 AttributeList *MSPropertyAttr =
1958 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanb26f0122013-06-28 20:48:34 +00001959 if (MSPropertyAttr) {
1960 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1961 BitWidth, InitStyle, AS, MSPropertyAttr);
1962 if (!Member)
1963 return 0;
1964 isInstField = false;
1965 } else {
1966 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1967 BitWidth, InitStyle, AS);
1968 assert(Member && "HandleField never returns null");
1969 }
1970 } else {
1971 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
1972
1973 Member = HandleDeclarator(S, D, TemplateParameterLists);
1974 if (!Member)
1975 return 0;
1976
1977 // Non-instance-fields can't have a bitfield.
1978 if (BitWidth) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001979 if (Member->isInvalidDecl()) {
1980 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001981 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001982 // C++ 9.6p3: A bit-field shall not be a static member.
1983 // "static member 'A' cannot be a bit-field"
1984 Diag(Loc, diag::err_static_not_bitfield)
1985 << Name << BitWidth->getSourceRange();
1986 } else if (isa<TypedefDecl>(Member)) {
1987 // "typedef member 'x' cannot be a bit-field"
1988 Diag(Loc, diag::err_typedef_not_bitfield)
1989 << Name << BitWidth->getSourceRange();
1990 } else {
1991 // A function typedef ("typedef int f(); f a;").
1992 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1993 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001994 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001995 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001996 }
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Chris Lattner8b963ef2009-03-05 23:01:03 +00001998 BitWidth = 0;
1999 Member->setInvalidDecl();
2000 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00002001
2002 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Douglas Gregor37b372b2009-08-20 22:52:58 +00002004 // If we have declared a member function template, set the access of the
2005 // templated declaration as well.
2006 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2007 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00002008 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002009
Richard Smitha4b39652012-08-06 03:25:17 +00002010 if (VS.isOverrideSpecified())
2011 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2012 if (VS.isFinalSpecified())
2013 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00002014
Douglas Gregorf5251602011-03-08 17:10:18 +00002015 if (VS.getLastLocation().isValid()) {
2016 // Update the end location of a method that has a virt-specifiers.
2017 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2018 MD->setRangeEnd(VS.getLastLocation());
2019 }
Richard Smitha4b39652012-08-06 03:25:17 +00002020
Anders Carlsson4ebf1602011-01-20 06:29:02 +00002021 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00002022
Douglas Gregor10bd3682008-11-17 22:58:34 +00002023 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002024
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002025 if (isInstField) {
2026 FieldDecl *FD = cast<FieldDecl>(Member);
2027 FieldCollector->Add(FD);
2028
2029 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2030 FD->getLocation())
2031 != DiagnosticsEngine::Ignored) {
2032 // Remember all explicit private FieldDecls that have a name, no side
2033 // effects and are not part of a dependent type declaration.
2034 if (!FD->isImplicit() && FD->getDeclName() &&
2035 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002036 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002037 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002038 !InitializationHasSideEffects(*FD))
2039 UnusedPrivateFields.insert(FD);
2040 }
2041 }
2042
John McCalld226f652010-08-21 09:40:31 +00002043 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002044}
2045
Hans Wennborg471f9852012-09-18 15:58:06 +00002046namespace {
2047 class UninitializedFieldVisitor
2048 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2049 Sema &S;
2050 ValueDecl *VD;
2051 public:
2052 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2053 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002054 S(S) {
2055 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2056 this->VD = IFD->getAnonField();
2057 else
2058 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002059 }
2060
2061 void HandleExpr(Expr *E) {
2062 if (!E) return;
2063
2064 // Expressions like x(x) sometimes lack the surrounding expressions
2065 // but need to be checked anyways.
2066 HandleValue(E);
2067 Visit(E);
2068 }
2069
2070 void HandleValue(Expr *E) {
2071 E = E->IgnoreParens();
2072
2073 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2074 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002075 return;
2076
2077 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2078 // or union.
2079 MemberExpr *FieldME = ME;
2080
Hans Wennborg471f9852012-09-18 15:58:06 +00002081 Expr *Base = E;
2082 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002083 ME = cast<MemberExpr>(Base);
2084
2085 if (isa<VarDecl>(ME->getMemberDecl()))
2086 return;
2087
2088 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2089 if (!FD->isAnonymousStructOrUnion())
2090 FieldME = ME;
2091
Hans Wennborg471f9852012-09-18 15:58:06 +00002092 Base = ME->getBase();
2093 }
2094
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002095 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00002096 unsigned diag = VD->getType()->isReferenceType()
2097 ? diag::warn_reference_field_is_uninit
2098 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002099 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002100 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002101 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002102 }
2103
2104 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2105 HandleValue(CO->getTrueExpr());
2106 HandleValue(CO->getFalseExpr());
2107 return;
2108 }
2109
2110 if (BinaryConditionalOperator *BCO =
2111 dyn_cast<BinaryConditionalOperator>(E)) {
2112 HandleValue(BCO->getCommon());
2113 HandleValue(BCO->getFalseExpr());
2114 return;
2115 }
2116
2117 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2118 switch (BO->getOpcode()) {
2119 default:
2120 return;
2121 case(BO_PtrMemD):
2122 case(BO_PtrMemI):
2123 HandleValue(BO->getLHS());
2124 return;
2125 case(BO_Comma):
2126 HandleValue(BO->getRHS());
2127 return;
2128 }
2129 }
2130 }
2131
2132 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2133 if (E->getCastKind() == CK_LValueToRValue)
2134 HandleValue(E->getSubExpr());
2135
2136 Inherited::VisitImplicitCastExpr(E);
2137 }
2138
2139 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2140 Expr *Callee = E->getCallee();
2141 if (isa<MemberExpr>(Callee))
2142 HandleValue(Callee);
2143
2144 Inherited::VisitCXXMemberCallExpr(E);
2145 }
2146 };
2147 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2148 ValueDecl *VD) {
2149 UninitializedFieldVisitor(S, VD).HandleExpr(E);
2150 }
2151} // namespace
2152
Richard Smith7a614d82011-06-11 17:19:42 +00002153/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002154/// in-class initializer for a non-static C++ class member, and after
2155/// instantiating an in-class initializer in a class template. Such actions
2156/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002157void
Richard Smithca523302012-06-10 03:12:00 +00002158Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002159 Expr *InitExpr) {
2160 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002161 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2162 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002163
2164 if (!InitExpr) {
2165 FD->setInvalidDecl();
2166 FD->removeInClassInitializer();
2167 return;
2168 }
2169
Peter Collingbournefef21892011-10-23 18:59:44 +00002170 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2171 FD->setInvalidDecl();
2172 FD->removeInClassInitializer();
2173 return;
2174 }
2175
Hans Wennborg471f9852012-09-18 15:58:06 +00002176 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2177 != DiagnosticsEngine::Ignored) {
2178 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2179 }
2180
Richard Smith7a614d82011-06-11 17:19:42 +00002181 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002182 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002183 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002184 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002185 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002186 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002187 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2188 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002189 if (Init.isInvalid()) {
2190 FD->setInvalidDecl();
2191 return;
2192 }
Richard Smith7a614d82011-06-11 17:19:42 +00002193 }
2194
Richard Smith41956372013-01-14 22:39:08 +00002195 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002196 // The initialization of each base and member constitutes a
2197 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002198 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002199 if (Init.isInvalid()) {
2200 FD->setInvalidDecl();
2201 return;
2202 }
2203
2204 InitExpr = Init.release();
2205
2206 FD->setInClassInitializer(InitExpr);
2207}
2208
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002209/// \brief Find the direct and/or virtual base specifiers that
2210/// correspond to the given base type, for use in base initialization
2211/// within a constructor.
2212static bool FindBaseInitializer(Sema &SemaRef,
2213 CXXRecordDecl *ClassDecl,
2214 QualType BaseType,
2215 const CXXBaseSpecifier *&DirectBaseSpec,
2216 const CXXBaseSpecifier *&VirtualBaseSpec) {
2217 // First, check for a direct base class.
2218 DirectBaseSpec = 0;
2219 for (CXXRecordDecl::base_class_const_iterator Base
2220 = ClassDecl->bases_begin();
2221 Base != ClassDecl->bases_end(); ++Base) {
2222 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2223 // We found a direct base of this type. That's what we're
2224 // initializing.
2225 DirectBaseSpec = &*Base;
2226 break;
2227 }
2228 }
2229
2230 // Check for a virtual base class.
2231 // FIXME: We might be able to short-circuit this if we know in advance that
2232 // there are no virtual bases.
2233 VirtualBaseSpec = 0;
2234 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2235 // We haven't found a base yet; search the class hierarchy for a
2236 // virtual base class.
2237 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2238 /*DetectVirtual=*/false);
2239 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2240 BaseType, Paths)) {
2241 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2242 Path != Paths.end(); ++Path) {
2243 if (Path->back().Base->isVirtual()) {
2244 VirtualBaseSpec = Path->back().Base;
2245 break;
2246 }
2247 }
2248 }
2249 }
2250
2251 return DirectBaseSpec || VirtualBaseSpec;
2252}
2253
Sebastian Redl6df65482011-09-24 17:48:25 +00002254/// \brief Handle a C++ member initializer using braced-init-list syntax.
2255MemInitResult
2256Sema::ActOnMemInitializer(Decl *ConstructorD,
2257 Scope *S,
2258 CXXScopeSpec &SS,
2259 IdentifierInfo *MemberOrBase,
2260 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002261 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002262 SourceLocation IdLoc,
2263 Expr *InitList,
2264 SourceLocation EllipsisLoc) {
2265 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002266 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002267 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002268}
2269
2270/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002271MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002272Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002273 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002274 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002275 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002276 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002277 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002278 SourceLocation IdLoc,
2279 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002280 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002281 SourceLocation RParenLoc,
2282 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002283 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002284 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002285 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002286 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002287}
2288
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002289namespace {
2290
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002291// Callback to only accept typo corrections that can be a valid C++ member
2292// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002293class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002294public:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002295 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2296 : ClassDecl(ClassDecl) {}
2297
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002298 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002299 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2300 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2301 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002302 return isa<TypeDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002303 }
2304 return false;
2305 }
2306
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002307private:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002308 CXXRecordDecl *ClassDecl;
2309};
2310
2311}
2312
Sebastian Redl6df65482011-09-24 17:48:25 +00002313/// \brief Handle a C++ member initializer.
2314MemInitResult
2315Sema::BuildMemInitializer(Decl *ConstructorD,
2316 Scope *S,
2317 CXXScopeSpec &SS,
2318 IdentifierInfo *MemberOrBase,
2319 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002320 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002321 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002322 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002323 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002324 if (!ConstructorD)
2325 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002326
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002327 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002328
2329 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002330 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002331 if (!Constructor) {
2332 // The user wrote a constructor initializer on a function that is
2333 // not a C++ constructor. Ignore the error for now, because we may
2334 // have more member initializers coming; we'll diagnose it just
2335 // once in ActOnMemInitializers.
2336 return true;
2337 }
2338
2339 CXXRecordDecl *ClassDecl = Constructor->getParent();
2340
2341 // C++ [class.base.init]p2:
2342 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002343 // constructor's class and, if not found in that scope, are looked
2344 // up in the scope containing the constructor's definition.
2345 // [Note: if the constructor's class contains a member with the
2346 // same name as a direct or virtual base class of the class, a
2347 // mem-initializer-id naming the member or base class and composed
2348 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002349 // mem-initializer-id for the hidden base class may be specified
2350 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002351 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002352 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002353 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002354 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002355 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002356 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002357 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2358 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002359 if (EllipsisLoc.isValid())
2360 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002361 << MemberOrBase
2362 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002363
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002364 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002365 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002366 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002367 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002368 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002369 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002370 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002371
2372 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002373 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002374 } else if (DS.getTypeSpecType() == TST_decltype) {
2375 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002376 } else {
2377 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2378 LookupParsedName(R, S, &SS);
2379
2380 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2381 if (!TyD) {
2382 if (R.isAmbiguous()) return true;
2383
John McCallfd225442010-04-09 19:01:14 +00002384 // We don't want access-control diagnostics here.
2385 R.suppressDiagnostics();
2386
Douglas Gregor7a886e12010-01-19 06:46:48 +00002387 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2388 bool NotUnknownSpecialization = false;
2389 DeclContext *DC = computeDeclContext(SS, false);
2390 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2391 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2392
2393 if (!NotUnknownSpecialization) {
2394 // When the scope specifier can refer to a member of an unknown
2395 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002396 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2397 SS.getWithLocInContext(Context),
2398 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002399 if (BaseType.isNull())
2400 return true;
2401
Douglas Gregor7a886e12010-01-19 06:46:48 +00002402 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002403 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002404 }
2405 }
2406
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002407 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002408 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002409 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002410 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002411 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002412 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002413 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2414 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002415 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002416 // We have found a non-static data member with a similar
2417 // name to what was typed; complain and initialize that
2418 // member.
2419 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2420 << MemberOrBase << true << CorrectedQuotedStr
2421 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2422 Diag(Member->getLocation(), diag::note_previous_decl)
2423 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002424
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002425 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002426 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002427 const CXXBaseSpecifier *DirectBaseSpec;
2428 const CXXBaseSpecifier *VirtualBaseSpec;
2429 if (FindBaseInitializer(*this, ClassDecl,
2430 Context.getTypeDeclType(Type),
2431 DirectBaseSpec, VirtualBaseSpec)) {
2432 // We have found a direct or virtual base class with a
2433 // similar name to what was typed; complain and initialize
2434 // that base class.
2435 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002436 << MemberOrBase << false << CorrectedQuotedStr
2437 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002438
2439 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2440 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002441 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002442 diag::note_base_class_specified_here)
2443 << BaseSpec->getType()
2444 << BaseSpec->getSourceRange();
2445
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002446 TyD = Type;
2447 }
2448 }
2449 }
2450
Douglas Gregor7a886e12010-01-19 06:46:48 +00002451 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002452 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002453 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002454 return true;
2455 }
John McCall2b194412009-12-21 10:41:20 +00002456 }
2457
Douglas Gregor7a886e12010-01-19 06:46:48 +00002458 if (BaseType.isNull()) {
2459 BaseType = Context.getTypeDeclType(TyD);
2460 if (SS.isSet()) {
2461 NestedNameSpecifier *Qualifier =
2462 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002463
Douglas Gregor7a886e12010-01-19 06:46:48 +00002464 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002465 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002466 }
John McCall2b194412009-12-21 10:41:20 +00002467 }
2468 }
Mike Stump1eb44332009-09-09 15:08:12 +00002469
John McCalla93c9342009-12-07 02:54:59 +00002470 if (!TInfo)
2471 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002472
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002473 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002474}
2475
Chandler Carruth81c64772011-09-03 01:14:15 +00002476/// Checks a member initializer expression for cases where reference (or
2477/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002478static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2479 Expr *Init,
2480 SourceLocation IdLoc) {
2481 QualType MemberTy = Member->getType();
2482
2483 // We only handle pointers and references currently.
2484 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2485 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2486 return;
2487
2488 const bool IsPointer = MemberTy->isPointerType();
2489 if (IsPointer) {
2490 if (const UnaryOperator *Op
2491 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2492 // The only case we're worried about with pointers requires taking the
2493 // address.
2494 if (Op->getOpcode() != UO_AddrOf)
2495 return;
2496
2497 Init = Op->getSubExpr();
2498 } else {
2499 // We only handle address-of expression initializers for pointers.
2500 return;
2501 }
2502 }
2503
Richard Smitha4bb99c2013-06-12 21:51:50 +00002504 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002505 // We only warn when referring to a non-reference parameter declaration.
2506 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2507 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002508 return;
2509
2510 S.Diag(Init->getExprLoc(),
2511 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2512 : diag::warn_bind_ref_member_to_parameter)
2513 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002514 } else {
2515 // Other initializers are fine.
2516 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002517 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002518
2519 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2520 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002521}
2522
John McCallf312b1e2010-08-26 23:41:50 +00002523MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002524Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002525 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002526 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2527 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2528 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002529 "Member must be a FieldDecl or IndirectFieldDecl");
2530
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002531 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002532 return true;
2533
Douglas Gregor464b2f02010-11-05 22:21:31 +00002534 if (Member->isInvalidDecl())
2535 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002536
John McCallb4190042009-11-04 23:02:40 +00002537 // Diagnose value-uses of fields to initialize themselves, e.g.
2538 // foo(foo)
2539 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002540 // TODO: implement -Wuninitialized and fold this into that framework.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002541 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002542 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002543 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002544 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002545 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002546 } else {
2547 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002548 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002549 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002550
Richard Trieude5e75c2012-06-14 23:11:34 +00002551 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2552 != DiagnosticsEngine::Ignored)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002553 for (unsigned i = 0, e = Args.size(); i != e; ++i)
Richard Trieude5e75c2012-06-14 23:11:34 +00002554 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002555 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002556 // initializing the i'th field, throw a warning if any of the >= i'th
2557 // fields are used, as they are not yet initialized.
2558 // Right now we are only handling the case where the i'th field uses
2559 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002560 // Also need to take into account that some fields may be initialized by
2561 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002562 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002563
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002564 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002565
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002566 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002567 // Can't check initialization for a member of dependent type or when
2568 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002569 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002570 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002571 bool InitList = false;
2572 if (isa<InitListExpr>(Init)) {
2573 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002574 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002575 }
2576
Chandler Carruth894aed92010-12-06 09:23:57 +00002577 // Initialize the member.
2578 InitializedEntity MemberEntity =
2579 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2580 : InitializedEntity::InitializeMember(IndirectMember, 0);
2581 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002582 InitList ? InitializationKind::CreateDirectList(IdLoc)
2583 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2584 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002585
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002586 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2587 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002588 if (MemberInit.isInvalid())
2589 return true;
2590
Richard Smith8a07cd32013-06-12 20:42:33 +00002591 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2592
Richard Smith41956372013-01-14 22:39:08 +00002593 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002594 // The initialization of each base and member constitutes a
2595 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002596 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002597 if (MemberInit.isInvalid())
2598 return true;
2599
Richard Smithc83c2302012-12-19 01:39:02 +00002600 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002601 }
2602
Chandler Carruth894aed92010-12-06 09:23:57 +00002603 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002604 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2605 InitRange.getBegin(), Init,
2606 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002607 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002608 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2609 InitRange.getBegin(), Init,
2610 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002611 }
Eli Friedman59c04372009-07-29 19:44:27 +00002612}
2613
John McCallf312b1e2010-08-26 23:41:50 +00002614MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002615Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002616 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002617 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002618 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002619 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002620 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002621 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002622
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002623 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002624 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002625 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2626 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002627 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002628 }
2629
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002630 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002631 // Initialize the object.
2632 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2633 QualType(ClassDecl->getTypeForDecl(), 0));
2634 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002635 InitList ? InitializationKind::CreateDirectList(NameLoc)
2636 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2637 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002638 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002639 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002640 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002641 if (DelegationInit.isInvalid())
2642 return true;
2643
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002644 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2645 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002646
Richard Smith41956372013-01-14 22:39:08 +00002647 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002648 // The initialization of each base and member constitutes a
2649 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002650 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2651 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002652 if (DelegationInit.isInvalid())
2653 return true;
2654
Eli Friedmand21016f2012-05-19 23:35:23 +00002655 // If we are in a dependent context, template instantiation will
2656 // perform this type-checking again. Just save the arguments that we
2657 // received in a ParenListExpr.
2658 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2659 // of the information that we have about the base
2660 // initializer. However, deconstructing the ASTs is a dicey process,
2661 // and this approach is far more likely to get the corner cases right.
2662 if (CurContext->isDependentContext())
2663 DelegationInit = Owned(Init);
2664
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002665 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002666 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002667 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002668}
2669
2670MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002671Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002672 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002673 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002674 SourceLocation BaseLoc
2675 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002676
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002677 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2678 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2679 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2680
2681 // C++ [class.base.init]p2:
2682 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002683 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002684 // of that class, the mem-initializer is ill-formed. A
2685 // mem-initializer-list can initialize a base class using any
2686 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002687 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002688
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002689 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002690 if (EllipsisLoc.isValid()) {
2691 // This is a pack expansion.
2692 if (!BaseType->containsUnexpandedParameterPack()) {
2693 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002694 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002695
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002696 EllipsisLoc = SourceLocation();
2697 }
2698 } else {
2699 // Check for any unexpanded parameter packs.
2700 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2701 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002702
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002703 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002704 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002705 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002706
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002707 // Check for direct and virtual base classes.
2708 const CXXBaseSpecifier *DirectBaseSpec = 0;
2709 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2710 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002711 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2712 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002713 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002714
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002715 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2716 VirtualBaseSpec);
2717
2718 // C++ [base.class.init]p2:
2719 // Unless the mem-initializer-id names a nonstatic data member of the
2720 // constructor's class or a direct or virtual base of that class, the
2721 // mem-initializer is ill-formed.
2722 if (!DirectBaseSpec && !VirtualBaseSpec) {
2723 // If the class has any dependent bases, then it's possible that
2724 // one of those types will resolve to the same type as
2725 // BaseType. Therefore, just treat this as a dependent base
2726 // class initialization. FIXME: Should we try to check the
2727 // initialization anyway? It seems odd.
2728 if (ClassDecl->hasAnyDependentBases())
2729 Dependent = true;
2730 else
2731 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2732 << BaseType << Context.getTypeDeclType(ClassDecl)
2733 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2734 }
2735 }
2736
2737 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002738 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002739
Sebastian Redl6df65482011-09-24 17:48:25 +00002740 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2741 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002742 InitRange.getBegin(), Init,
2743 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002744 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002745
2746 // C++ [base.class.init]p2:
2747 // If a mem-initializer-id is ambiguous because it designates both
2748 // a direct non-virtual base class and an inherited virtual base
2749 // class, the mem-initializer is ill-formed.
2750 if (DirectBaseSpec && VirtualBaseSpec)
2751 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002752 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002753
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002754 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002755 if (!BaseSpec)
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002756 BaseSpec = VirtualBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002757
2758 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002759 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002760 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002761 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002762 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002763 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002764 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002765
2766 InitializedEntity BaseEntity =
2767 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2768 InitializationKind Kind =
2769 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2770 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2771 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002772 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2773 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002774 if (BaseInit.isInvalid())
2775 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002776
Richard Smith41956372013-01-14 22:39:08 +00002777 // C++11 [class.base.init]p7:
2778 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002779 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002780 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002781 if (BaseInit.isInvalid())
2782 return true;
2783
2784 // If we are in a dependent context, template instantiation will
2785 // perform this type-checking again. Just save the arguments that we
2786 // received in a ParenListExpr.
2787 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2788 // of the information that we have about the base
2789 // initializer. However, deconstructing the ASTs is a dicey process,
2790 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002791 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002792 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002793
Sean Huntcbb67482011-01-08 20:30:50 +00002794 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002795 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002796 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002797 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002798 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002799}
2800
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002801// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002802static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2803 if (T.isNull()) T = E->getType();
2804 QualType TargetType = SemaRef.BuildReferenceType(
2805 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002806 SourceLocation ExprLoc = E->getLocStart();
2807 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2808 TargetType, ExprLoc);
2809
2810 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2811 SourceRange(ExprLoc, ExprLoc),
2812 E->getSourceRange()).take();
2813}
2814
Anders Carlssone5ef7402010-04-23 03:10:23 +00002815/// ImplicitInitializerKind - How an implicit base or member initializer should
2816/// initialize its base or member.
2817enum ImplicitInitializerKind {
2818 IIK_Default,
2819 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002820 IIK_Move,
2821 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002822};
2823
Anders Carlssondefefd22010-04-23 02:00:02 +00002824static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002825BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002826 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002827 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002828 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002829 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002830 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002831 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2832 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002833
John McCall60d7b3a2010-08-24 06:29:42 +00002834 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002835
2836 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002837 case IIK_Inherit: {
2838 const CXXRecordDecl *Inherited =
2839 Constructor->getInheritedConstructor()->getParent();
2840 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2841 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2842 // C++11 [class.inhctor]p8:
2843 // Each expression in the expression-list is of the form
2844 // static_cast<T&&>(p), where p is the name of the corresponding
2845 // constructor parameter and T is the declared type of p.
2846 SmallVector<Expr*, 16> Args;
2847 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2848 ParmVarDecl *PD = Constructor->getParamDecl(I);
2849 ExprResult ArgExpr =
2850 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2851 VK_LValue, SourceLocation());
2852 if (ArgExpr.isInvalid())
2853 return true;
2854 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2855 }
2856
2857 InitializationKind InitKind = InitializationKind::CreateDirect(
2858 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002859 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002860 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2861 break;
2862 }
2863 }
2864 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002865 case IIK_Default: {
2866 InitializationKind InitKind
2867 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002868 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2869 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002870 break;
2871 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002872
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002873 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002874 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002875 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002876 ParmVarDecl *Param = Constructor->getParamDecl(0);
2877 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002878
Anders Carlssone5ef7402010-04-23 03:10:23 +00002879 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002880 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002881 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002882 Constructor->getLocation(), ParamType,
2883 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002884
Eli Friedman5f2987c2012-02-02 03:46:19 +00002885 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2886
Anders Carlssonc7957502010-04-24 22:02:54 +00002887 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002888 QualType ArgTy =
2889 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2890 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002891
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002892 if (Moving) {
2893 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2894 }
2895
John McCallf871d0c2010-08-07 06:22:56 +00002896 CXXCastPath BasePath;
2897 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002898 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2899 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002900 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002901 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002902
Anders Carlssone5ef7402010-04-23 03:10:23 +00002903 InitializationKind InitKind
2904 = InitializationKind::CreateDirect(Constructor->getLocation(),
2905 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002906 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2907 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002908 break;
2909 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002910 }
John McCall9ae2f072010-08-23 23:25:46 +00002911
Douglas Gregor53c374f2010-12-07 00:41:46 +00002912 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002913 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002914 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002915
Anders Carlssondefefd22010-04-23 02:00:02 +00002916 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002917 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002918 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2919 SourceLocation()),
2920 BaseSpec->isVirtual(),
2921 SourceLocation(),
2922 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002923 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002924 SourceLocation());
2925
Anders Carlssondefefd22010-04-23 02:00:02 +00002926 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002927}
2928
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002929static bool RefersToRValueRef(Expr *MemRef) {
2930 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2931 return Referenced->getType()->isRValueReferenceType();
2932}
2933
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002934static bool
2935BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002936 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002937 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002938 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002939 if (Field->isInvalidDecl())
2940 return true;
2941
Chandler Carruthf186b542010-06-29 23:50:44 +00002942 SourceLocation Loc = Constructor->getLocation();
2943
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002944 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2945 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002946 ParmVarDecl *Param = Constructor->getParamDecl(0);
2947 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002948
2949 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002950 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2951 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002952
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002953 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002954 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002955 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002956 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002957
Eli Friedman5f2987c2012-02-02 03:46:19 +00002958 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2959
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002960 if (Moving) {
2961 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2962 }
2963
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002964 // Build a reference to this field within the parameter.
2965 CXXScopeSpec SS;
2966 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2967 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002968 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2969 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002970 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002971 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002972 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002973 ParamType, Loc,
2974 /*IsArrow=*/false,
2975 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002976 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002977 /*FirstQualifierInScope=*/0,
2978 MemberLookup,
2979 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002980 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002981 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002982
2983 // C++11 [class.copy]p15:
2984 // - if a member m has rvalue reference type T&&, it is direct-initialized
2985 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002986 if (RefersToRValueRef(CtorArg.get())) {
2987 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002988 }
2989
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002990 // When the field we are copying is an array, create index variables for
2991 // each dimension of the array. We use these index variables to subscript
2992 // the source array, and other clients (e.g., CodeGen) will perform the
2993 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002994 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002995 QualType BaseType = Field->getType();
2996 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002997 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002998 while (const ConstantArrayType *Array
2999 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003000 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003001 // Create the iteration variable for this array index.
3002 IdentifierInfo *IterationVarName = 0;
3003 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003004 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003005 llvm::raw_svector_ostream OS(Str);
3006 OS << "__i" << IndexVariables.size();
3007 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3008 }
3009 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003010 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003011 IterationVarName, SizeType,
3012 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003013 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003014 IndexVariables.push_back(IterationVar);
3015
3016 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003017 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003018 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003019 assert(!IterationVarRef.isInvalid() &&
3020 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003021 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3022 assert(!IterationVarRef.isInvalid() &&
3023 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003024
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003025 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003026 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003027 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003028 Loc);
3029 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003030 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003031
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003032 BaseType = Array->getElementType();
3033 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003034
3035 // The array subscript expression is an lvalue, which is wrong for moving.
3036 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003037 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003038
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003039 // Construct the entity that we will be initializing. For an array, this
3040 // will be first element in the array, which may require several levels
3041 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003042 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003043 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003044 if (Indirect)
3045 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3046 else
3047 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003048 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3049 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3050 0,
3051 Entities.back()));
3052
3053 // Direct-initialize to use the copy constructor.
3054 InitializationKind InitKind =
3055 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3056
Sebastian Redl74e611a2011-09-04 18:14:28 +00003057 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003058 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003059
John McCall60d7b3a2010-08-24 06:29:42 +00003060 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003061 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003062 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003063 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003064 if (MemberInit.isInvalid())
3065 return true;
3066
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003067 if (Indirect) {
3068 assert(IndexVariables.size() == 0 &&
3069 "Indirect field improperly initialized");
3070 CXXMemberInit
3071 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3072 Loc, Loc,
3073 MemberInit.takeAs<Expr>(),
3074 Loc);
3075 } else
3076 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3077 Loc, MemberInit.takeAs<Expr>(),
3078 Loc,
3079 IndexVariables.data(),
3080 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003081 return false;
3082 }
3083
Richard Smith07b0fdc2013-03-18 21:12:30 +00003084 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3085 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003086
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003087 QualType FieldBaseElementType =
3088 SemaRef.Context.getBaseElementType(Field->getType());
3089
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003090 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003091 InitializedEntity InitEntity
3092 = Indirect? InitializedEntity::InitializeMember(Indirect)
3093 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003094 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003095 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003096
3097 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3098 ExprResult MemberInit =
3099 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003100
Douglas Gregor53c374f2010-12-07 00:41:46 +00003101 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003102 if (MemberInit.isInvalid())
3103 return true;
3104
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003105 if (Indirect)
3106 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3107 Indirect, Loc,
3108 Loc,
3109 MemberInit.get(),
3110 Loc);
3111 else
3112 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3113 Field, Loc, Loc,
3114 MemberInit.get(),
3115 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003116 return false;
3117 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003118
Sean Hunt1f2f3842011-05-17 00:19:05 +00003119 if (!Field->getParent()->isUnion()) {
3120 if (FieldBaseElementType->isReferenceType()) {
3121 SemaRef.Diag(Constructor->getLocation(),
3122 diag::err_uninitialized_member_in_ctor)
3123 << (int)Constructor->isImplicit()
3124 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3125 << 0 << Field->getDeclName();
3126 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3127 return true;
3128 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003129
Sean Hunt1f2f3842011-05-17 00:19:05 +00003130 if (FieldBaseElementType.isConstQualified()) {
3131 SemaRef.Diag(Constructor->getLocation(),
3132 diag::err_uninitialized_member_in_ctor)
3133 << (int)Constructor->isImplicit()
3134 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3135 << 1 << Field->getDeclName();
3136 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3137 return true;
3138 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003139 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003140
David Blaikie4e4d0842012-03-11 07:00:24 +00003141 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003142 FieldBaseElementType->isObjCRetainableType() &&
3143 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3144 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003145 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003146 // Default-initialize Objective-C pointers to NULL.
3147 CXXMemberInit
3148 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3149 Loc, Loc,
3150 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3151 Loc);
3152 return false;
3153 }
3154
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003155 // Nothing to initialize.
3156 CXXMemberInit = 0;
3157 return false;
3158}
John McCallf1860e52010-05-20 23:23:51 +00003159
3160namespace {
3161struct BaseAndFieldInfo {
3162 Sema &S;
3163 CXXConstructorDecl *Ctor;
3164 bool AnyErrorsInInits;
3165 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003166 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003167 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003168
3169 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3170 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003171 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3172 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003173 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003174 else if (Generated && Ctor->isMoveConstructor())
3175 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003176 else if (Ctor->getInheritedConstructor())
3177 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003178 else
3179 IIK = IIK_Default;
3180 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003181
3182 bool isImplicitCopyOrMove() const {
3183 switch (IIK) {
3184 case IIK_Copy:
3185 case IIK_Move:
3186 return true;
3187
3188 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003189 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003190 return false;
3191 }
David Blaikie30263482012-01-20 21:50:17 +00003192
3193 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003194 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003195
3196 bool addFieldInitializer(CXXCtorInitializer *Init) {
3197 AllToInit.push_back(Init);
3198
3199 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003200 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003201 S.UnusedPrivateFields.remove(Init->getAnyMember());
3202
3203 return false;
3204 }
John McCallf1860e52010-05-20 23:23:51 +00003205};
3206}
3207
Richard Smitha4950662011-09-19 13:34:43 +00003208/// \brief Determine whether the given indirect field declaration is somewhere
3209/// within an anonymous union.
3210static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3211 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3212 CEnd = F->chain_end();
3213 C != CEnd; ++C)
3214 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3215 if (Record->isUnion())
3216 return true;
3217
3218 return false;
3219}
3220
Douglas Gregorddb21472011-11-02 23:04:16 +00003221/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3222/// array type.
3223static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3224 if (T->isIncompleteArrayType())
3225 return true;
3226
3227 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3228 if (!ArrayT->getSize())
3229 return true;
3230
3231 T = ArrayT->getElementType();
3232 }
3233
3234 return false;
3235}
3236
Richard Smith7a614d82011-06-11 17:19:42 +00003237static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003238 FieldDecl *Field,
3239 IndirectFieldDecl *Indirect = 0) {
Eli Friedman5fb478b2013-06-28 21:07:41 +00003240 if (Field->isInvalidDecl())
3241 return false;
John McCallf1860e52010-05-20 23:23:51 +00003242
Chandler Carruthe861c602010-06-30 02:59:29 +00003243 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003244 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3245 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003246
Richard Smith0b8220a2012-08-07 21:30:42 +00003247 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003248 // has a brace-or-equal-initializer, the entity is initialized as specified
3249 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003250 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003251 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3252 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003253 CXXCtorInitializer *Init;
3254 if (Indirect)
3255 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3256 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003257 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003258 SourceLocation());
3259 else
3260 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3261 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003262 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003263 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003264 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003265 }
3266
Richard Smithc115f632011-09-18 11:14:50 +00003267 // Don't build an implicit initializer for union members if none was
3268 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003269 if (Field->getParent()->isUnion() ||
3270 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003271 return false;
3272
Douglas Gregorddb21472011-11-02 23:04:16 +00003273 // Don't initialize incomplete or zero-length arrays.
3274 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3275 return false;
3276
John McCallf1860e52010-05-20 23:23:51 +00003277 // Don't try to build an implicit initializer if there were semantic
3278 // errors in any of the initializers (and therefore we might be
3279 // missing some that the user actually wrote).
Eli Friedman5fb478b2013-06-28 21:07:41 +00003280 if (Info.AnyErrorsInInits)
John McCallf1860e52010-05-20 23:23:51 +00003281 return false;
3282
Sean Huntcbb67482011-01-08 20:30:50 +00003283 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003284 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3285 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003286 return true;
John McCallf1860e52010-05-20 23:23:51 +00003287
Richard Smith0b8220a2012-08-07 21:30:42 +00003288 if (!Init)
3289 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003290
Richard Smith0b8220a2012-08-07 21:30:42 +00003291 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003292}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003293
3294bool
3295Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3296 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003297 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003298 Constructor->setNumCtorInitializers(1);
3299 CXXCtorInitializer **initializer =
3300 new (Context) CXXCtorInitializer*[1];
3301 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3302 Constructor->setCtorInitializers(initializer);
3303
Sean Huntb76af9c2011-05-03 23:05:34 +00003304 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003305 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003306 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3307 }
3308
Sean Huntc1598702011-05-05 00:05:47 +00003309 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003310
Sean Hunt059ce0d2011-05-01 07:04:31 +00003311 return false;
3312}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003313
David Blaikie93c86172013-01-17 05:26:25 +00003314bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3315 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003316 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003317 // Just store the initializers as written, they will be checked during
3318 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003319 if (!Initializers.empty()) {
3320 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003321 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003322 new (Context) CXXCtorInitializer*[Initializers.size()];
3323 memcpy(baseOrMemberInitializers, Initializers.data(),
3324 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003325 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003326 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003327
3328 // Let template instantiation know whether we had errors.
3329 if (AnyErrors)
3330 Constructor->setInvalidDecl();
3331
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003332 return false;
3333 }
3334
John McCallf1860e52010-05-20 23:23:51 +00003335 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003336
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003337 // We need to build the initializer AST according to order of construction
3338 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003339 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003340 if (!ClassDecl)
3341 return true;
3342
Eli Friedman80c30da2009-11-09 19:20:36 +00003343 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003344
David Blaikie93c86172013-01-17 05:26:25 +00003345 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003346 CXXCtorInitializer *Member = Initializers[i];
Richard Smithcbc820a2013-07-22 02:56:56 +00003347
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003348 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003349 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003350 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003351 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003352 }
3353
Anders Carlsson711f34a2010-04-21 19:52:01 +00003354 // Keep track of the direct virtual bases.
3355 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3356 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3357 E = ClassDecl->bases_end(); I != E; ++I) {
3358 if (I->isVirtual())
3359 DirectVBases.insert(I);
3360 }
3361
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003362 // Push virtual bases before others.
3363 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3364 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3365
Sean Huntcbb67482011-01-08 20:30:50 +00003366 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003367 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Richard Smithcbc820a2013-07-22 02:56:56 +00003368 // [class.base.init]p7, per DR257:
3369 // A mem-initializer where the mem-initializer-id names a virtual base
3370 // class is ignored during execution of a constructor of any class that
3371 // is not the most derived class.
3372 if (ClassDecl->isAbstract()) {
3373 // FIXME: Provide a fixit to remove the base specifier. This requires
3374 // tracking the location of the associated comma for a base specifier.
3375 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3376 << VBase->getType() << ClassDecl;
3377 DiagnoseAbstractType(ClassDecl);
3378 }
3379
John McCallf1860e52010-05-20 23:23:51 +00003380 Info.AllToInit.push_back(Value);
Richard Smithcbc820a2013-07-22 02:56:56 +00003381 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3382 // [class.base.init]p8, per DR257:
3383 // If a given [...] base class is not named by a mem-initializer-id
3384 // [...] and the entity is not a virtual base class of an abstract
3385 // class, then [...] the entity is default-initialized.
Anders Carlsson711f34a2010-04-21 19:52:01 +00003386 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003387 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003388 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Richard Smithcbc820a2013-07-22 02:56:56 +00003389 VBase, IsInheritedVirtualBase,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003390 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003391 HadError = true;
3392 continue;
3393 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003394
John McCallf1860e52010-05-20 23:23:51 +00003395 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003396 }
3397 }
Mike Stump1eb44332009-09-09 15:08:12 +00003398
John McCallf1860e52010-05-20 23:23:51 +00003399 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003400 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3401 E = ClassDecl->bases_end(); Base != E; ++Base) {
3402 // Virtuals are in the virtual base list and already constructed.
3403 if (Base->isVirtual())
3404 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003405
Sean Huntcbb67482011-01-08 20:30:50 +00003406 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003407 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3408 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003409 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003410 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003411 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003412 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003413 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003414 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003415 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003416 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003417
John McCallf1860e52010-05-20 23:23:51 +00003418 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003419 }
3420 }
Mike Stump1eb44332009-09-09 15:08:12 +00003421
John McCallf1860e52010-05-20 23:23:51 +00003422 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003423 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3424 MemEnd = ClassDecl->decls_end();
3425 Mem != MemEnd; ++Mem) {
3426 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003427 // C++ [class.bit]p2:
3428 // A declaration for a bit-field that omits the identifier declares an
3429 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3430 // initialized.
3431 if (F->isUnnamedBitfield())
3432 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003433
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003434 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003435 // handle anonymous struct/union fields based on their individual
3436 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003437 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003438 continue;
3439
3440 if (CollectFieldInitializer(*this, Info, F))
3441 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003442 continue;
3443 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003444
3445 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003446 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003447 continue;
3448
3449 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3450 if (F->getType()->isIncompleteArrayType()) {
3451 assert(ClassDecl->hasFlexibleArrayMember() &&
3452 "Incomplete array type is not valid");
3453 continue;
3454 }
3455
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003456 // Initialize each field of an anonymous struct individually.
3457 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3458 HadError = true;
3459
3460 continue;
3461 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003462 }
Mike Stump1eb44332009-09-09 15:08:12 +00003463
David Blaikie93c86172013-01-17 05:26:25 +00003464 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003465 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003466 Constructor->setNumCtorInitializers(NumInitializers);
3467 CXXCtorInitializer **baseOrMemberInitializers =
3468 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003469 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003470 NumInitializers * sizeof(CXXCtorInitializer*));
3471 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003472
John McCallef027fe2010-03-16 21:39:52 +00003473 // Constructors implicitly reference the base and member
3474 // destructors.
3475 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3476 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003477 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003478
3479 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003480}
3481
David Blaikieee000bb2013-01-17 08:49:22 +00003482static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003483 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003484 const RecordDecl *RD = RT->getDecl();
3485 if (RD->isAnonymousStructOrUnion()) {
3486 for (RecordDecl::field_iterator Field = RD->field_begin(),
3487 E = RD->field_end(); Field != E; ++Field)
3488 PopulateKeysForFields(*Field, IdealInits);
3489 return;
3490 }
Eli Friedman6347f422009-07-21 19:28:10 +00003491 }
David Blaikieee000bb2013-01-17 08:49:22 +00003492 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003493}
3494
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003495static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3496 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003497}
3498
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003499static const void *GetKeyForMember(ASTContext &Context,
3500 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003501 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003502 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003503
David Blaikieee000bb2013-01-17 08:49:22 +00003504 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003505}
3506
David Blaikie93c86172013-01-17 05:26:25 +00003507static void DiagnoseBaseOrMemInitializerOrder(
3508 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3509 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003510 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003511 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003512
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003513 // Don't check initializers order unless the warning is enabled at the
3514 // location of at least one initializer.
3515 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003516 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003517 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003518 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3519 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003520 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003521 ShouldCheckOrder = true;
3522 break;
3523 }
3524 }
3525 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003526 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003527
John McCalld6ca8da2010-04-10 07:37:23 +00003528 // Build the list of bases and members in the order that they'll
3529 // actually be initialized. The explicit initializers should be in
3530 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003531 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003532
Anders Carlsson071d6102010-04-02 03:38:04 +00003533 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3534
John McCalld6ca8da2010-04-10 07:37:23 +00003535 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003536 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003537 ClassDecl->vbases_begin(),
3538 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003539 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003540
John McCalld6ca8da2010-04-10 07:37:23 +00003541 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003542 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003543 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003544 if (Base->isVirtual())
3545 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003546 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003547 }
Mike Stump1eb44332009-09-09 15:08:12 +00003548
John McCalld6ca8da2010-04-10 07:37:23 +00003549 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003550 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003551 E = ClassDecl->field_end(); Field != E; ++Field) {
3552 if (Field->isUnnamedBitfield())
3553 continue;
3554
David Blaikieee000bb2013-01-17 08:49:22 +00003555 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003556 }
3557
John McCalld6ca8da2010-04-10 07:37:23 +00003558 unsigned NumIdealInits = IdealInitKeys.size();
3559 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003560
Sean Huntcbb67482011-01-08 20:30:50 +00003561 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003562 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003563 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003564 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003565
3566 // Scan forward to try to find this initializer in the idealized
3567 // initializers list.
3568 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3569 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003570 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003571
3572 // If we didn't find this initializer, it must be because we
3573 // scanned past it on a previous iteration. That can only
3574 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003575 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003576 Sema::SemaDiagnosticBuilder D =
3577 SemaRef.Diag(PrevInit->getSourceLocation(),
3578 diag::warn_initializer_out_of_order);
3579
Francois Pichet00eb3f92010-12-04 09:14:42 +00003580 if (PrevInit->isAnyMemberInitializer())
3581 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003582 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003583 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003584
Francois Pichet00eb3f92010-12-04 09:14:42 +00003585 if (Init->isAnyMemberInitializer())
3586 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003587 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003588 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003589
3590 // Move back to the initializer's location in the ideal list.
3591 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3592 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003593 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003594
3595 assert(IdealIndex != NumIdealInits &&
3596 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003597 }
John McCalld6ca8da2010-04-10 07:37:23 +00003598
3599 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003600 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003601}
3602
John McCall3c3ccdb2010-04-10 09:28:51 +00003603namespace {
3604bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003605 CXXCtorInitializer *Init,
3606 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003607 if (!PrevInit) {
3608 PrevInit = Init;
3609 return false;
3610 }
3611
Douglas Gregordc392c12013-03-25 23:28:23 +00003612 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003613 S.Diag(Init->getSourceLocation(),
3614 diag::err_multiple_mem_initialization)
3615 << Field->getDeclName()
3616 << Init->getSourceRange();
3617 else {
John McCallf4c73712011-01-19 06:33:43 +00003618 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003619 assert(BaseClass && "neither field nor base");
3620 S.Diag(Init->getSourceLocation(),
3621 diag::err_multiple_base_initialization)
3622 << QualType(BaseClass, 0)
3623 << Init->getSourceRange();
3624 }
3625 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3626 << 0 << PrevInit->getSourceRange();
3627
3628 return true;
3629}
3630
Sean Huntcbb67482011-01-08 20:30:50 +00003631typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003632typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3633
3634bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003635 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003636 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003637 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003638 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003639 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003640
3641 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003642 if (Parent->isUnion()) {
3643 UnionEntry &En = Unions[Parent];
3644 if (En.first && En.first != Child) {
3645 S.Diag(Init->getSourceLocation(),
3646 diag::err_multiple_mem_union_initialization)
3647 << Field->getDeclName()
3648 << Init->getSourceRange();
3649 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3650 << 0 << En.second->getSourceRange();
3651 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003652 }
3653 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003654 En.first = Child;
3655 En.second = Init;
3656 }
David Blaikie6fe29652011-11-17 06:01:57 +00003657 if (!Parent->isAnonymousStructOrUnion())
3658 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003659 }
3660
3661 Child = Parent;
3662 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003663 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003664
3665 return false;
3666}
3667}
3668
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003669/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003670void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003671 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003672 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003673 bool AnyErrors) {
3674 if (!ConstructorDecl)
3675 return;
3676
3677 AdjustDeclIfTemplate(ConstructorDecl);
3678
3679 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003680 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003681
3682 if (!Constructor) {
3683 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3684 return;
3685 }
3686
John McCall3c3ccdb2010-04-10 09:28:51 +00003687 // Mapping for the duplicate initializers check.
3688 // For member initializers, this is keyed with a FieldDecl*.
3689 // For base initializers, this is keyed with a Type*.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003690 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003691
3692 // Mapping for the inconsistent anonymous-union initializers check.
3693 RedundantUnionMap MemberUnions;
3694
Anders Carlssonea356fb2010-04-02 05:42:15 +00003695 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003696 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003697 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003698
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003699 // Set the source order index.
3700 Init->setSourceOrder(i);
3701
Francois Pichet00eb3f92010-12-04 09:14:42 +00003702 if (Init->isAnyMemberInitializer()) {
3703 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003704 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3705 CheckRedundantUnionInit(*this, Init, MemberUnions))
3706 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003707 } else if (Init->isBaseInitializer()) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003708 const void *Key =
3709 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall3c3ccdb2010-04-10 09:28:51 +00003710 if (CheckRedundantInit(*this, Init, Members[Key]))
3711 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003712 } else {
3713 assert(Init->isDelegatingInitializer());
3714 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003715 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003716 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003717 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003718 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003719 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003720 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003721 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003722 // Return immediately as the initializer is set.
3723 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003724 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003725 }
3726
Anders Carlssonea356fb2010-04-02 05:42:15 +00003727 if (HadError)
3728 return;
3729
David Blaikie93c86172013-01-17 05:26:25 +00003730 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003731
David Blaikie93c86172013-01-17 05:26:25 +00003732 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003733}
3734
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003735void
John McCallef027fe2010-03-16 21:39:52 +00003736Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3737 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003738 // Ignore dependent contexts. Also ignore unions, since their members never
3739 // have destructors implicitly called.
3740 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003741 return;
John McCall58e6f342010-03-16 05:22:47 +00003742
3743 // FIXME: all the access-control diagnostics are positioned on the
3744 // field/base declaration. That's probably good; that said, the
3745 // user might reasonably want to know why the destructor is being
3746 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003747
Anders Carlsson9f853df2009-11-17 04:44:12 +00003748 // Non-static data members.
3749 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3750 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003751 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003752 if (Field->isInvalidDecl())
3753 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003754
3755 // Don't destroy incomplete or zero-length arrays.
3756 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3757 continue;
3758
Anders Carlsson9f853df2009-11-17 04:44:12 +00003759 QualType FieldType = Context.getBaseElementType(Field->getType());
3760
3761 const RecordType* RT = FieldType->getAs<RecordType>();
3762 if (!RT)
3763 continue;
3764
3765 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003766 if (FieldClassDecl->isInvalidDecl())
3767 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003768 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003769 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003770 // The destructor for an implicit anonymous union member is never invoked.
3771 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3772 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003773
Douglas Gregordb89f282010-07-01 22:47:18 +00003774 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003775 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003776 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003777 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003778 << Field->getDeclName()
3779 << FieldType);
3780
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003781 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003782 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003783 }
3784
John McCall58e6f342010-03-16 05:22:47 +00003785 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3786
Anders Carlsson9f853df2009-11-17 04:44:12 +00003787 // Bases.
3788 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3789 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003790 // Bases are always records in a well-formed non-dependent class.
3791 const RecordType *RT = Base->getType()->getAs<RecordType>();
3792
3793 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003794 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003795 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003796
John McCall58e6f342010-03-16 05:22:47 +00003797 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003798 // If our base class is invalid, we probably can't get its dtor anyway.
3799 if (BaseClassDecl->isInvalidDecl())
3800 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003801 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003802 continue;
John McCall58e6f342010-03-16 05:22:47 +00003803
Douglas Gregordb89f282010-07-01 22:47:18 +00003804 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003805 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003806
3807 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003808 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003809 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003810 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003811 << Base->getSourceRange(),
3812 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003813
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003814 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003815 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003816 }
3817
3818 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003819 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3820 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003821
3822 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003823 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003824
3825 // Ignore direct virtual bases.
3826 if (DirectVirtualBases.count(RT))
3827 continue;
3828
John McCall58e6f342010-03-16 05:22:47 +00003829 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003830 // If our base class is invalid, we probably can't get its dtor anyway.
3831 if (BaseClassDecl->isInvalidDecl())
3832 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003833 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003834 continue;
John McCall58e6f342010-03-16 05:22:47 +00003835
Douglas Gregordb89f282010-07-01 22:47:18 +00003836 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003837 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00003838 if (CheckDestructorAccess(
3839 ClassDecl->getLocation(), Dtor,
3840 PDiag(diag::err_access_dtor_vbase)
3841 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3842 Context.getTypeDeclType(ClassDecl)) ==
3843 AR_accessible) {
3844 CheckDerivedToBaseConversion(
3845 Context.getTypeDeclType(ClassDecl), VBase->getType(),
3846 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3847 SourceRange(), DeclarationName(), 0);
3848 }
John McCall58e6f342010-03-16 05:22:47 +00003849
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003850 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003851 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003852 }
3853}
3854
John McCalld226f652010-08-21 09:40:31 +00003855void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003856 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003857 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003858
Mike Stump1eb44332009-09-09 15:08:12 +00003859 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003860 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003861 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003862}
3863
Mike Stump1eb44332009-09-09 15:08:12 +00003864bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003865 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003866 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3867 unsigned DiagID;
3868 AbstractDiagSelID SelID;
3869
3870 public:
3871 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3872 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003873
3874 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
Eli Friedman2217f852012-08-14 02:06:07 +00003875 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003876 if (SelID == -1)
3877 S.Diag(Loc, DiagID) << T;
3878 else
3879 S.Diag(Loc, DiagID) << SelID << T;
3880 }
3881 } Diagnoser(DiagID, SelID);
3882
3883 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003884}
3885
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003886bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003887 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003888 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003889 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003890
Anders Carlsson11f21a02009-03-23 19:10:31 +00003891 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003892 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003893
Ted Kremenek6217b802009-07-29 21:53:49 +00003894 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003895 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003896 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003897 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003898
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003899 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003900 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003901 }
Mike Stump1eb44332009-09-09 15:08:12 +00003902
Ted Kremenek6217b802009-07-29 21:53:49 +00003903 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003904 if (!RT)
3905 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003906
John McCall86ff3082010-02-04 22:26:26 +00003907 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003908
John McCall94c3b562010-08-18 09:41:07 +00003909 // We can't answer whether something is abstract until it has a
3910 // definition. If it's currently being defined, we'll walk back
3911 // over all the declarations when we have a full definition.
3912 const CXXRecordDecl *Def = RD->getDefinition();
3913 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003914 return false;
3915
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003916 if (!RD->isAbstract())
3917 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003918
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003919 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003920 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003921
John McCall94c3b562010-08-18 09:41:07 +00003922 return true;
3923}
3924
3925void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3926 // Check if we've already emitted the list of pure virtual functions
3927 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003928 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003929 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003930
Richard Smithcbc820a2013-07-22 02:56:56 +00003931 // If the diagnostic is suppressed, don't emit the notes. We're only
3932 // going to emit them once, so try to attach them to a diagnostic we're
3933 // actually going to show.
3934 if (Diags.isLastDiagnosticIgnored())
3935 return;
3936
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003937 CXXFinalOverriderMap FinalOverriders;
3938 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003939
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003940 // Keep a set of seen pure methods so we won't diagnose the same method
3941 // more than once.
3942 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3943
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003944 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3945 MEnd = FinalOverriders.end();
3946 M != MEnd;
3947 ++M) {
3948 for (OverridingMethods::iterator SO = M->second.begin(),
3949 SOEnd = M->second.end();
3950 SO != SOEnd; ++SO) {
3951 // C++ [class.abstract]p4:
3952 // A class is abstract if it contains or inherits at least one
3953 // pure virtual function for which the final overrider is pure
3954 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003955
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003956 //
3957 if (SO->second.size() != 1)
3958 continue;
3959
3960 if (!SO->second.front().Method->isPure())
3961 continue;
3962
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003963 if (!SeenPureMethods.insert(SO->second.front().Method))
3964 continue;
3965
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003966 Diag(SO->second.front().Method->getLocation(),
3967 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003968 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003969 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003970 }
3971
3972 if (!PureVirtualClassDiagSet)
3973 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3974 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003975}
3976
Anders Carlsson8211eff2009-03-24 01:19:16 +00003977namespace {
John McCall94c3b562010-08-18 09:41:07 +00003978struct AbstractUsageInfo {
3979 Sema &S;
3980 CXXRecordDecl *Record;
3981 CanQualType AbstractType;
3982 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003983
John McCall94c3b562010-08-18 09:41:07 +00003984 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3985 : S(S), Record(Record),
3986 AbstractType(S.Context.getCanonicalType(
3987 S.Context.getTypeDeclType(Record))),
3988 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003989
John McCall94c3b562010-08-18 09:41:07 +00003990 void DiagnoseAbstractType() {
3991 if (Invalid) return;
3992 S.DiagnoseAbstractType(Record);
3993 Invalid = true;
3994 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003995
John McCall94c3b562010-08-18 09:41:07 +00003996 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3997};
3998
3999struct CheckAbstractUsage {
4000 AbstractUsageInfo &Info;
4001 const NamedDecl *Ctx;
4002
4003 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4004 : Info(Info), Ctx(Ctx) {}
4005
4006 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4007 switch (TL.getTypeLocClass()) {
4008#define ABSTRACT_TYPELOC(CLASS, PARENT)
4009#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00004010 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00004011#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00004012 }
John McCall94c3b562010-08-18 09:41:07 +00004013 }
Mike Stump1eb44332009-09-09 15:08:12 +00004014
John McCall94c3b562010-08-18 09:41:07 +00004015 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4016 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4017 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00004018 if (!TL.getArg(I))
4019 continue;
4020
John McCall94c3b562010-08-18 09:41:07 +00004021 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4022 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004023 }
John McCall94c3b562010-08-18 09:41:07 +00004024 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004025
John McCall94c3b562010-08-18 09:41:07 +00004026 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4027 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4028 }
Mike Stump1eb44332009-09-09 15:08:12 +00004029
John McCall94c3b562010-08-18 09:41:07 +00004030 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4031 // Visit the type parameters from a permissive context.
4032 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4033 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4034 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4035 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4036 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4037 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004038 }
John McCall94c3b562010-08-18 09:41:07 +00004039 }
Mike Stump1eb44332009-09-09 15:08:12 +00004040
John McCall94c3b562010-08-18 09:41:07 +00004041 // Visit pointee types from a permissive context.
4042#define CheckPolymorphic(Type) \
4043 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4044 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4045 }
4046 CheckPolymorphic(PointerTypeLoc)
4047 CheckPolymorphic(ReferenceTypeLoc)
4048 CheckPolymorphic(MemberPointerTypeLoc)
4049 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004050 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004051
John McCall94c3b562010-08-18 09:41:07 +00004052 /// Handle all the types we haven't given a more specific
4053 /// implementation for above.
4054 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4055 // Every other kind of type that we haven't called out already
4056 // that has an inner type is either (1) sugar or (2) contains that
4057 // inner type in some way as a subobject.
4058 if (TypeLoc Next = TL.getNextTypeLoc())
4059 return Visit(Next, Sel);
4060
4061 // If there's no inner type and we're in a permissive context,
4062 // don't diagnose.
4063 if (Sel == Sema::AbstractNone) return;
4064
4065 // Check whether the type matches the abstract type.
4066 QualType T = TL.getType();
4067 if (T->isArrayType()) {
4068 Sel = Sema::AbstractArrayType;
4069 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004070 }
John McCall94c3b562010-08-18 09:41:07 +00004071 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4072 if (CT != Info.AbstractType) return;
4073
4074 // It matched; do some magic.
4075 if (Sel == Sema::AbstractArrayType) {
4076 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4077 << T << TL.getSourceRange();
4078 } else {
4079 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4080 << Sel << T << TL.getSourceRange();
4081 }
4082 Info.DiagnoseAbstractType();
4083 }
4084};
4085
4086void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4087 Sema::AbstractDiagSelID Sel) {
4088 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4089}
4090
4091}
4092
4093/// Check for invalid uses of an abstract type in a method declaration.
4094static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4095 CXXMethodDecl *MD) {
4096 // No need to do the check on definitions, which require that
4097 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004098 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004099 return;
4100
4101 // For safety's sake, just ignore it if we don't have type source
4102 // information. This should never happen for non-implicit methods,
4103 // but...
4104 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4105 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4106}
4107
4108/// Check for invalid uses of an abstract type within a class definition.
4109static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4110 CXXRecordDecl *RD) {
4111 for (CXXRecordDecl::decl_iterator
4112 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4113 Decl *D = *I;
4114 if (D->isImplicit()) continue;
4115
4116 // Methods and method templates.
4117 if (isa<CXXMethodDecl>(D)) {
4118 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4119 } else if (isa<FunctionTemplateDecl>(D)) {
4120 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4121 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4122
4123 // Fields and static variables.
4124 } else if (isa<FieldDecl>(D)) {
4125 FieldDecl *FD = cast<FieldDecl>(D);
4126 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4127 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4128 } else if (isa<VarDecl>(D)) {
4129 VarDecl *VD = cast<VarDecl>(D);
4130 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4131 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4132
4133 // Nested classes and class templates.
4134 } else if (isa<CXXRecordDecl>(D)) {
4135 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4136 } else if (isa<ClassTemplateDecl>(D)) {
4137 CheckAbstractClassUsage(Info,
4138 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4139 }
4140 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004141}
4142
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004143/// \brief Perform semantic checks on a class definition that has been
4144/// completing, introducing implicitly-declared members, checking for
4145/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004146void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004147 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004148 return;
4149
John McCall94c3b562010-08-18 09:41:07 +00004150 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4151 AbstractUsageInfo Info(*this, Record);
4152 CheckAbstractClassUsage(Info, Record);
4153 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004154
4155 // If this is not an aggregate type and has no user-declared constructor,
4156 // complain about any non-static data members of reference or const scalar
4157 // type, since they will never get initializers.
4158 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004159 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4160 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004161 bool Complained = false;
4162 for (RecordDecl::field_iterator F = Record->field_begin(),
4163 FEnd = Record->field_end();
4164 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004165 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004166 continue;
4167
Douglas Gregor325e5932010-04-15 00:00:53 +00004168 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004169 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004170 if (!Complained) {
4171 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4172 << Record->getTagKind() << Record;
4173 Complained = true;
4174 }
4175
4176 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4177 << F->getType()->isReferenceType()
4178 << F->getDeclName();
4179 }
4180 }
4181 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004182
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004183 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004184 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004185
4186 if (Record->getIdentifier()) {
4187 // C++ [class.mem]p13:
4188 // If T is the name of a class, then each of the following shall have a
4189 // name different from T:
4190 // - every member of every anonymous union that is a member of class T.
4191 //
4192 // C++ [class.mem]p14:
4193 // In addition, if class T has a user-declared constructor (12.1), every
4194 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004195 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4196 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4197 ++I) {
4198 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004199 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4200 isa<IndirectFieldDecl>(D)) {
4201 Diag(D->getLocation(), diag::err_member_name_of_class)
4202 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004203 break;
4204 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004205 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004206 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004207
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004208 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004209 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004210 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004211 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004212 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4213 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4214 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004215
David Blaikieb6b5b972012-09-21 03:21:07 +00004216 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4217 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4218 DiagnoseAbstractType(Record);
4219 }
4220
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004221 if (!Record->isDependentType()) {
4222 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4223 MEnd = Record->method_end();
4224 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004225 // See if a method overloads virtual methods in a base
4226 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004227 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004228 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004229
4230 // Check whether the explicitly-defaulted special members are valid.
4231 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4232 CheckExplicitlyDefaultedSpecialMember(*M);
4233
4234 // For an explicitly defaulted or deleted special member, we defer
4235 // determining triviality until the class is complete. That time is now!
4236 if (!M->isImplicit() && !M->isUserProvided()) {
4237 CXXSpecialMember CSM = getSpecialMember(*M);
4238 if (CSM != CXXInvalid) {
4239 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4240
4241 // Inform the class that we've finished declaring this member.
4242 Record->finishedDefaultedOrDeletedMember(*M);
4243 }
4244 }
4245 }
4246 }
4247
4248 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4249 // function that is not a constructor declares that member function to be
4250 // const. [...] The class of which that function is a member shall be
4251 // a literal type.
4252 //
4253 // If the class has virtual bases, any constexpr members will already have
4254 // been diagnosed by the checks performed on the member declaration, so
4255 // suppress this (less useful) diagnostic.
4256 //
4257 // We delay this until we know whether an explicitly-defaulted (or deleted)
4258 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004259 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004260 !Record->isLiteral() && !Record->getNumVBases()) {
4261 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4262 MEnd = Record->method_end();
4263 M != MEnd; ++M) {
4264 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4265 switch (Record->getTemplateSpecializationKind()) {
4266 case TSK_ImplicitInstantiation:
4267 case TSK_ExplicitInstantiationDeclaration:
4268 case TSK_ExplicitInstantiationDefinition:
4269 // If a template instantiates to a non-literal type, but its members
4270 // instantiate to constexpr functions, the template is technically
4271 // ill-formed, but we allow it for sanity.
4272 continue;
4273
4274 case TSK_Undeclared:
4275 case TSK_ExplicitSpecialization:
4276 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4277 diag::err_constexpr_method_non_literal);
4278 break;
4279 }
4280
4281 // Only produce one error per class.
4282 break;
4283 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004284 }
4285 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004286
Richard Smith07b0fdc2013-03-18 21:12:30 +00004287 // Declare inheriting constructors. We do this eagerly here because:
4288 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004289 // constructors from different classes.
4290 // - The lazy declaration of the other implicit constructors is so as to not
4291 // waste space and performance on classes that are not meant to be
4292 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004293 // have inheriting constructors.
4294 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004295}
4296
Richard Smith7756afa2012-06-10 05:43:50 +00004297/// Is the special member function which would be selected to perform the
4298/// specified operation on the specified class type a constexpr constructor?
4299static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4300 Sema::CXXSpecialMember CSM,
4301 bool ConstArg) {
4302 Sema::SpecialMemberOverloadResult *SMOR =
4303 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4304 false, false, false, false);
4305 if (!SMOR || !SMOR->getMethod())
4306 // A constructor we wouldn't select can't be "involved in initializing"
4307 // anything.
4308 return true;
4309 return SMOR->getMethod()->isConstexpr();
4310}
4311
4312/// Determine whether the specified special member function would be constexpr
4313/// if it were implicitly defined.
4314static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4315 Sema::CXXSpecialMember CSM,
4316 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004317 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004318 return false;
4319
4320 // C++11 [dcl.constexpr]p4:
4321 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004322 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004323 switch (CSM) {
4324 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004325 // Since default constructor lookup is essentially trivial (and cannot
4326 // involve, for instance, template instantiation), we compute whether a
4327 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4328 //
4329 // This is important for performance; we need to know whether the default
4330 // constructor is constexpr to determine whether the type is a literal type.
4331 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4332
Richard Smith7756afa2012-06-10 05:43:50 +00004333 case Sema::CXXCopyConstructor:
4334 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004335 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004336 break;
4337
4338 case Sema::CXXCopyAssignment:
4339 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004340 if (!S.getLangOpts().CPlusPlus1y)
4341 return false;
4342 // In C++1y, we need to perform overload resolution.
4343 Ctor = false;
4344 break;
4345
Richard Smith7756afa2012-06-10 05:43:50 +00004346 case Sema::CXXDestructor:
4347 case Sema::CXXInvalid:
4348 return false;
4349 }
4350
4351 // -- if the class is a non-empty union, or for each non-empty anonymous
4352 // union member of a non-union class, exactly one non-static data member
4353 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004354 //
4355 // If we squint, this is guaranteed, since exactly one non-static data member
4356 // will be initialized (if the constructor isn't deleted), we just don't know
4357 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004358 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004359 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004360
4361 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004362 if (Ctor && ClassDecl->getNumVBases())
4363 return false;
4364
4365 // C++1y [class.copy]p26:
4366 // -- [the class] is a literal type, and
4367 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004368 return false;
4369
4370 // -- every constructor involved in initializing [...] base class
4371 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004372 // -- the assignment operator selected to copy/move each direct base
4373 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004374 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4375 BEnd = ClassDecl->bases_end();
4376 B != BEnd; ++B) {
4377 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4378 if (!BaseType) continue;
4379
4380 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4381 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4382 return false;
4383 }
4384
4385 // -- every constructor involved in initializing non-static data members
4386 // [...] shall be a constexpr constructor;
4387 // -- every non-static data member and base class sub-object shall be
4388 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004389 // -- for each non-stastic data member of X that is of class type (or array
4390 // thereof), the assignment operator selected to copy/move that member is
4391 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004392 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4393 FEnd = ClassDecl->field_end();
4394 F != FEnd; ++F) {
4395 if (F->isInvalidDecl())
4396 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004397 if (const RecordType *RecordTy =
4398 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004399 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4400 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4401 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004402 }
4403 }
4404
4405 // All OK, it's constexpr!
4406 return true;
4407}
4408
Richard Smithb9d0b762012-07-27 04:22:15 +00004409static Sema::ImplicitExceptionSpecification
4410computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4411 switch (S.getSpecialMember(MD)) {
4412 case Sema::CXXDefaultConstructor:
4413 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4414 case Sema::CXXCopyConstructor:
4415 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4416 case Sema::CXXCopyAssignment:
4417 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4418 case Sema::CXXMoveConstructor:
4419 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4420 case Sema::CXXMoveAssignment:
4421 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4422 case Sema::CXXDestructor:
4423 return S.ComputeDefaultedDtorExceptionSpec(MD);
4424 case Sema::CXXInvalid:
4425 break;
4426 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004427 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4428 "only special members have implicit exception specs");
4429 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004430}
4431
Richard Smithdd25e802012-07-30 23:48:14 +00004432static void
4433updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4434 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4435 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4436 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004437 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4438 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004439}
4440
Richard Smithb9d0b762012-07-27 04:22:15 +00004441void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4442 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4443 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4444 return;
4445
Richard Smithdd25e802012-07-30 23:48:14 +00004446 // Evaluate the exception specification.
4447 ImplicitExceptionSpecification ExceptSpec =
4448 computeImplicitExceptionSpec(*this, Loc, MD);
4449
4450 // Update the type of the special member to use it.
4451 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4452
4453 // A user-provided destructor can be defined outside the class. When that
4454 // happens, be sure to update the exception specification on both
4455 // declarations.
4456 const FunctionProtoType *CanonicalFPT =
4457 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4458 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4459 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4460 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004461}
4462
Richard Smith3003e1d2012-05-15 04:39:51 +00004463void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4464 CXXRecordDecl *RD = MD->getParent();
4465 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004466
Richard Smith3003e1d2012-05-15 04:39:51 +00004467 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4468 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004469
4470 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004471 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004472 bool First = MD == MD->getCanonicalDecl();
4473
4474 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004475
4476 // C++11 [dcl.fct.def.default]p1:
4477 // A function that is explicitly defaulted shall
4478 // -- be a special member function (checked elsewhere),
4479 // -- have the same type (except for ref-qualifiers, and except that a
4480 // copy operation can take a non-const reference) as an implicit
4481 // declaration, and
4482 // -- not have default arguments.
4483 unsigned ExpectedParams = 1;
4484 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4485 ExpectedParams = 0;
4486 if (MD->getNumParams() != ExpectedParams) {
4487 // This also checks for default arguments: a copy or move constructor with a
4488 // default argument is classified as a default constructor, and assignment
4489 // operations and destructors can't have default arguments.
4490 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4491 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004492 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004493 } else if (MD->isVariadic()) {
4494 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4495 << CSM << MD->getSourceRange();
4496 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004497 }
4498
Richard Smith3003e1d2012-05-15 04:39:51 +00004499 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004500
Richard Smith7756afa2012-06-10 05:43:50 +00004501 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004502 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004503 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004504 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004505 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004506
Richard Smith3003e1d2012-05-15 04:39:51 +00004507 QualType ReturnType = Context.VoidTy;
4508 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4509 // Check for return type matching.
4510 ReturnType = Type->getResultType();
4511 QualType ExpectedReturnType =
4512 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4513 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4514 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4515 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4516 HadError = true;
4517 }
4518
4519 // A defaulted special member cannot have cv-qualifiers.
4520 if (Type->getTypeQuals()) {
4521 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004522 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004523 HadError = true;
4524 }
4525 }
4526
4527 // Check for parameter type matching.
4528 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004529 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004530 if (ExpectedParams && ArgType->isReferenceType()) {
4531 // Argument must be reference to possibly-const T.
4532 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004533 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004534
4535 if (ReferentType.isVolatileQualified()) {
4536 Diag(MD->getLocation(),
4537 diag::err_defaulted_special_member_volatile_param) << CSM;
4538 HadError = true;
4539 }
4540
Richard Smith7756afa2012-06-10 05:43:50 +00004541 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004542 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4543 Diag(MD->getLocation(),
4544 diag::err_defaulted_special_member_copy_const_param)
4545 << (CSM == CXXCopyAssignment);
4546 // FIXME: Explain why this special member can't be const.
4547 } else {
4548 Diag(MD->getLocation(),
4549 diag::err_defaulted_special_member_move_const_param)
4550 << (CSM == CXXMoveAssignment);
4551 }
4552 HadError = true;
4553 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004554 } else if (ExpectedParams) {
4555 // A copy assignment operator can take its argument by value, but a
4556 // defaulted one cannot.
4557 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004558 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004559 HadError = true;
4560 }
Sean Huntbe631222011-05-17 20:44:43 +00004561
Richard Smith61802452011-12-22 02:22:31 +00004562 // C++11 [dcl.fct.def.default]p2:
4563 // An explicitly-defaulted function may be declared constexpr only if it
4564 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004565 // Do not apply this rule to members of class templates, since core issue 1358
4566 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004567 // functions which cannot be constexpr (for non-constructors in C++11 and for
4568 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004569 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4570 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004571 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4572 : isa<CXXConstructorDecl>(MD)) &&
4573 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004574 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4575 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004576 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004577 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004578 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004579
Richard Smith61802452011-12-22 02:22:31 +00004580 // and may have an explicit exception-specification only if it is compatible
4581 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004582 if (Type->hasExceptionSpec()) {
4583 // Delay the check if this is the first declaration of the special member,
4584 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004585 if (First) {
4586 // If the exception specification needs to be instantiated, do so now,
4587 // before we clobber it with an EST_Unevaluated specification below.
4588 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4589 InstantiateExceptionSpec(MD->getLocStart(), MD);
4590 Type = MD->getType()->getAs<FunctionProtoType>();
4591 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004592 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004593 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004594 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4595 }
Richard Smith61802452011-12-22 02:22:31 +00004596
4597 // If a function is explicitly defaulted on its first declaration,
4598 if (First) {
4599 // -- it is implicitly considered to be constexpr if the implicit
4600 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004601 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004602
Richard Smith3003e1d2012-05-15 04:39:51 +00004603 // -- it is implicitly considered to have the same exception-specification
4604 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004605 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4606 EPI.ExceptionSpecType = EST_Unevaluated;
4607 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004608 MD->setType(Context.getFunctionType(ReturnType,
4609 ArrayRef<QualType>(&ArgType,
4610 ExpectedParams),
4611 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004612 }
4613
Richard Smith3003e1d2012-05-15 04:39:51 +00004614 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004615 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004616 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004617 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004618 // C++11 [dcl.fct.def.default]p4:
4619 // [For a] user-provided explicitly-defaulted function [...] if such a
4620 // function is implicitly defined as deleted, the program is ill-formed.
4621 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4622 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004623 }
4624 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004625
Richard Smith3003e1d2012-05-15 04:39:51 +00004626 if (HadError)
4627 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004628}
4629
Richard Smith1d28caf2012-12-11 01:14:52 +00004630/// Check whether the exception specification provided for an
4631/// explicitly-defaulted special member matches the exception specification
4632/// that would have been generated for an implicit special member, per
4633/// C++11 [dcl.fct.def.default]p2.
4634void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4635 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4636 // Compute the implicit exception specification.
4637 FunctionProtoType::ExtProtoInfo EPI;
4638 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4639 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004640 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004641
4642 // Ensure that it matches.
4643 CheckEquivalentExceptionSpec(
4644 PDiag(diag::err_incorrect_defaulted_exception_spec)
4645 << getSpecialMember(MD), PDiag(),
4646 ImplicitType, SourceLocation(),
4647 SpecifiedType, MD->getLocation());
4648}
4649
4650void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4651 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4652 I != N; ++I)
4653 CheckExplicitlyDefaultedMemberExceptionSpec(
4654 DelayedDefaultedMemberExceptionSpecs[I].first,
4655 DelayedDefaultedMemberExceptionSpecs[I].second);
4656
4657 DelayedDefaultedMemberExceptionSpecs.clear();
4658}
4659
Richard Smith7d5088a2012-02-18 02:02:13 +00004660namespace {
4661struct SpecialMemberDeletionInfo {
4662 Sema &S;
4663 CXXMethodDecl *MD;
4664 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004665 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004666
4667 // Properties of the special member, computed for convenience.
4668 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4669 SourceLocation Loc;
4670
4671 bool AllFieldsAreConst;
4672
4673 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004674 Sema::CXXSpecialMember CSM, bool Diagnose)
4675 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004676 IsConstructor(false), IsAssignment(false), IsMove(false),
4677 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4678 AllFieldsAreConst(true) {
4679 switch (CSM) {
4680 case Sema::CXXDefaultConstructor:
4681 case Sema::CXXCopyConstructor:
4682 IsConstructor = true;
4683 break;
4684 case Sema::CXXMoveConstructor:
4685 IsConstructor = true;
4686 IsMove = true;
4687 break;
4688 case Sema::CXXCopyAssignment:
4689 IsAssignment = true;
4690 break;
4691 case Sema::CXXMoveAssignment:
4692 IsAssignment = true;
4693 IsMove = true;
4694 break;
4695 case Sema::CXXDestructor:
4696 break;
4697 case Sema::CXXInvalid:
4698 llvm_unreachable("invalid special member kind");
4699 }
4700
4701 if (MD->getNumParams()) {
4702 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4703 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4704 }
4705 }
4706
4707 bool inUnion() const { return MD->getParent()->isUnion(); }
4708
4709 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004710 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4711 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004712 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004713 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4714 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4715 Quals = 0;
4716 return S.LookupSpecialMember(Class, CSM,
4717 ConstArg || (Quals & Qualifiers::Const),
4718 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004719 MD->getRefQualifier() == RQ_RValue,
4720 TQ & Qualifiers::Const,
4721 TQ & Qualifiers::Volatile);
4722 }
4723
Richard Smith6c4c36c2012-03-30 20:53:28 +00004724 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004725
Richard Smith6c4c36c2012-03-30 20:53:28 +00004726 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004727 bool shouldDeleteForField(FieldDecl *FD);
4728 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004729
Richard Smith517bb842012-07-18 03:51:16 +00004730 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4731 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004732 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4733 Sema::SpecialMemberOverloadResult *SMOR,
4734 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004735
4736 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004737};
4738}
4739
John McCall12d8d802012-04-09 20:53:23 +00004740/// Is the given special member inaccessible when used on the given
4741/// sub-object.
4742bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4743 CXXMethodDecl *target) {
4744 /// If we're operating on a base class, the object type is the
4745 /// type of this special member.
4746 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004747 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004748 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4749 objectTy = S.Context.getTypeDeclType(MD->getParent());
4750 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4751
4752 // If we're operating on a field, the object type is the type of the field.
4753 } else {
4754 objectTy = S.Context.getTypeDeclType(target->getParent());
4755 }
4756
4757 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4758}
4759
Richard Smith6c4c36c2012-03-30 20:53:28 +00004760/// Check whether we should delete a special member due to the implicit
4761/// definition containing a call to a special member of a subobject.
4762bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4763 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4764 bool IsDtorCallInCtor) {
4765 CXXMethodDecl *Decl = SMOR->getMethod();
4766 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4767
4768 int DiagKind = -1;
4769
4770 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4771 DiagKind = !Decl ? 0 : 1;
4772 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4773 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004774 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004775 DiagKind = 3;
4776 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4777 !Decl->isTrivial()) {
4778 // A member of a union must have a trivial corresponding special member.
4779 // As a weird special case, a destructor call from a union's constructor
4780 // must be accessible and non-deleted, but need not be trivial. Such a
4781 // destructor is never actually called, but is semantically checked as
4782 // if it were.
4783 DiagKind = 4;
4784 }
4785
4786 if (DiagKind == -1)
4787 return false;
4788
4789 if (Diagnose) {
4790 if (Field) {
4791 S.Diag(Field->getLocation(),
4792 diag::note_deleted_special_member_class_subobject)
4793 << CSM << MD->getParent() << /*IsField*/true
4794 << Field << DiagKind << IsDtorCallInCtor;
4795 } else {
4796 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4797 S.Diag(Base->getLocStart(),
4798 diag::note_deleted_special_member_class_subobject)
4799 << CSM << MD->getParent() << /*IsField*/false
4800 << Base->getType() << DiagKind << IsDtorCallInCtor;
4801 }
4802
4803 if (DiagKind == 1)
4804 S.NoteDeletedFunction(Decl);
4805 // FIXME: Explain inaccessibility if DiagKind == 3.
4806 }
4807
4808 return true;
4809}
4810
Richard Smith9a561d52012-02-26 09:11:52 +00004811/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004812/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004813bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004814 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004815 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004816
4817 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004818 // -- any direct or virtual base class, or non-static data member with no
4819 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004820 // either M has no default constructor or overload resolution as applied
4821 // to M's default constructor results in an ambiguity or in a function
4822 // that is deleted or inaccessible
4823 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4824 // -- a direct or virtual base class B that cannot be copied/moved because
4825 // overload resolution, as applied to B's corresponding special member,
4826 // results in an ambiguity or a function that is deleted or inaccessible
4827 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004828 // C++11 [class.dtor]p5:
4829 // -- any direct or virtual base class [...] has a type with a destructor
4830 // that is deleted or inaccessible
4831 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004832 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004833 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004834 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004835
Richard Smith6c4c36c2012-03-30 20:53:28 +00004836 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4837 // -- any direct or virtual base class or non-static data member has a
4838 // type with a destructor that is deleted or inaccessible
4839 if (IsConstructor) {
4840 Sema::SpecialMemberOverloadResult *SMOR =
4841 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4842 false, false, false, false, false);
4843 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4844 return true;
4845 }
4846
Richard Smith9a561d52012-02-26 09:11:52 +00004847 return false;
4848}
4849
4850/// Check whether we should delete a special member function due to the class
4851/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004852bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004853 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004854 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004855}
4856
4857/// Check whether we should delete a special member function due to the class
4858/// having a particular non-static data member.
4859bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4860 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4861 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4862
4863 if (CSM == Sema::CXXDefaultConstructor) {
4864 // For a default constructor, all references must be initialized in-class
4865 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004866 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4867 if (Diagnose)
4868 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4869 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004870 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004871 }
Richard Smith79363f52012-02-27 06:07:25 +00004872 // C++11 [class.ctor]p5: any non-variant non-static data member of
4873 // const-qualified type (or array thereof) with no
4874 // brace-or-equal-initializer does not have a user-provided default
4875 // constructor.
4876 if (!inUnion() && FieldType.isConstQualified() &&
4877 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004878 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4879 if (Diagnose)
4880 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004881 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004882 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004883 }
4884
4885 if (inUnion() && !FieldType.isConstQualified())
4886 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004887 } else if (CSM == Sema::CXXCopyConstructor) {
4888 // For a copy constructor, data members must not be of rvalue reference
4889 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004890 if (FieldType->isRValueReferenceType()) {
4891 if (Diagnose)
4892 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4893 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004894 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004895 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004896 } else if (IsAssignment) {
4897 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004898 if (FieldType->isReferenceType()) {
4899 if (Diagnose)
4900 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4901 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004902 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004903 }
4904 if (!FieldRecord && FieldType.isConstQualified()) {
4905 // C++11 [class.copy]p23:
4906 // -- a non-static data member of const non-class type (or array thereof)
4907 if (Diagnose)
4908 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004909 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004910 return true;
4911 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004912 }
4913
4914 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004915 // Some additional restrictions exist on the variant members.
4916 if (!inUnion() && FieldRecord->isUnion() &&
4917 FieldRecord->isAnonymousStructOrUnion()) {
4918 bool AllVariantFieldsAreConst = true;
4919
Richard Smithdf8dc862012-03-29 19:00:10 +00004920 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004921 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4922 UE = FieldRecord->field_end();
4923 UI != UE; ++UI) {
4924 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004925
4926 if (!UnionFieldType.isConstQualified())
4927 AllVariantFieldsAreConst = false;
4928
Richard Smith9a561d52012-02-26 09:11:52 +00004929 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4930 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004931 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4932 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004933 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004934 }
4935
4936 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004937 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004938 FieldRecord->field_begin() != FieldRecord->field_end()) {
4939 if (Diagnose)
4940 S.Diag(FieldRecord->getLocation(),
4941 diag::note_deleted_default_ctor_all_const)
4942 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004943 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004944 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004945
Richard Smithdf8dc862012-03-29 19:00:10 +00004946 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004947 // This is technically non-conformant, but sanity demands it.
4948 return false;
4949 }
4950
Richard Smith517bb842012-07-18 03:51:16 +00004951 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4952 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004953 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004954 }
4955
4956 return false;
4957}
4958
4959/// C++11 [class.ctor] p5:
4960/// A defaulted default constructor for a class X is defined as deleted if
4961/// X is a union and all of its variant members are of const-qualified type.
4962bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004963 // This is a silly definition, because it gives an empty union a deleted
4964 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004965 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4966 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4967 if (Diagnose)
4968 S.Diag(MD->getParent()->getLocation(),
4969 diag::note_deleted_default_ctor_all_const)
4970 << MD->getParent() << /*not anonymous union*/0;
4971 return true;
4972 }
4973 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004974}
4975
4976/// Determine whether a defaulted special member function should be defined as
4977/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4978/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004979bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4980 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004981 if (MD->isInvalidDecl())
4982 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004983 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004984 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004985 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004986 return false;
4987
Richard Smith7d5088a2012-02-18 02:02:13 +00004988 // C++11 [expr.lambda.prim]p19:
4989 // The closure type associated with a lambda-expression has a
4990 // deleted (8.4.3) default constructor and a deleted copy
4991 // assignment operator.
4992 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004993 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4994 if (Diagnose)
4995 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004996 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004997 }
4998
Richard Smith5bdaac52012-04-02 20:59:25 +00004999 // For an anonymous struct or union, the copy and assignment special members
5000 // will never be used, so skip the check. For an anonymous union declared at
5001 // namespace scope, the constructor and destructor are used.
5002 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5003 RD->isAnonymousStructOrUnion())
5004 return false;
5005
Richard Smith6c4c36c2012-03-30 20:53:28 +00005006 // C++11 [class.copy]p7, p18:
5007 // If the class definition declares a move constructor or move assignment
5008 // operator, an implicitly declared copy constructor or copy assignment
5009 // operator is defined as deleted.
5010 if (MD->isImplicit() &&
5011 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5012 CXXMethodDecl *UserDeclaredMove = 0;
5013
5014 // In Microsoft mode, a user-declared move only causes the deletion of the
5015 // corresponding copy operation, not both copy operations.
5016 if (RD->hasUserDeclaredMoveConstructor() &&
5017 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5018 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005019
5020 // Find any user-declared move constructor.
5021 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5022 E = RD->ctor_end(); I != E; ++I) {
5023 if (I->isMoveConstructor()) {
5024 UserDeclaredMove = *I;
5025 break;
5026 }
5027 }
Richard Smith1c931be2012-04-02 18:40:40 +00005028 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005029 } else if (RD->hasUserDeclaredMoveAssignment() &&
5030 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5031 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005032
5033 // Find any user-declared move assignment operator.
5034 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5035 E = RD->method_end(); I != E; ++I) {
5036 if (I->isMoveAssignmentOperator()) {
5037 UserDeclaredMove = *I;
5038 break;
5039 }
5040 }
Richard Smith1c931be2012-04-02 18:40:40 +00005041 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005042 }
5043
5044 if (UserDeclaredMove) {
5045 Diag(UserDeclaredMove->getLocation(),
5046 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005047 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005048 << UserDeclaredMove->isMoveAssignmentOperator();
5049 return true;
5050 }
5051 }
Sean Hunte16da072011-10-10 06:18:57 +00005052
Richard Smith5bdaac52012-04-02 20:59:25 +00005053 // Do access control from the special member function
5054 ContextRAII MethodContext(*this, MD);
5055
Richard Smith9a561d52012-02-26 09:11:52 +00005056 // C++11 [class.dtor]p5:
5057 // -- for a virtual destructor, lookup of the non-array deallocation function
5058 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005059 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005060 FunctionDecl *OperatorDelete = 0;
5061 DeclarationName Name =
5062 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5063 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005064 OperatorDelete, false)) {
5065 if (Diagnose)
5066 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005067 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005068 }
Richard Smith9a561d52012-02-26 09:11:52 +00005069 }
5070
Richard Smith6c4c36c2012-03-30 20:53:28 +00005071 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005072
Sean Huntcdee3fe2011-05-11 22:34:38 +00005073 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005074 BE = RD->bases_end(); BI != BE; ++BI)
5075 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005076 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005077 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005078
Richard Smithe0883602013-07-22 18:06:23 +00005079 // Per DR1611, do not consider virtual bases of constructors of abstract
5080 // classes, since we are not going to construct them.
Richard Smithcbc820a2013-07-22 02:56:56 +00005081 if (!RD->isAbstract() || !SMI.IsConstructor) {
5082 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5083 BE = RD->vbases_end();
5084 BI != BE; ++BI)
5085 if (SMI.shouldDeleteForBase(BI))
5086 return true;
5087 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00005088
5089 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005090 FE = RD->field_end(); FI != FE; ++FI)
5091 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005092 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005093 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005094
Richard Smith7d5088a2012-02-18 02:02:13 +00005095 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005096 return true;
5097
5098 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005099}
5100
Richard Smithac713512012-12-08 02:53:02 +00005101/// Perform lookup for a special member of the specified kind, and determine
5102/// whether it is trivial. If the triviality can be determined without the
5103/// lookup, skip it. This is intended for use when determining whether a
5104/// special member of a containing object is trivial, and thus does not ever
5105/// perform overload resolution for default constructors.
5106///
5107/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5108/// member that was most likely to be intended to be trivial, if any.
5109static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5110 Sema::CXXSpecialMember CSM, unsigned Quals,
5111 CXXMethodDecl **Selected) {
5112 if (Selected)
5113 *Selected = 0;
5114
5115 switch (CSM) {
5116 case Sema::CXXInvalid:
5117 llvm_unreachable("not a special member");
5118
5119 case Sema::CXXDefaultConstructor:
5120 // C++11 [class.ctor]p5:
5121 // A default constructor is trivial if:
5122 // - all the [direct subobjects] have trivial default constructors
5123 //
5124 // Note, no overload resolution is performed in this case.
5125 if (RD->hasTrivialDefaultConstructor())
5126 return true;
5127
5128 if (Selected) {
5129 // If there's a default constructor which could have been trivial, dig it
5130 // out. Otherwise, if there's any user-provided default constructor, point
5131 // to that as an example of why there's not a trivial one.
5132 CXXConstructorDecl *DefCtor = 0;
5133 if (RD->needsImplicitDefaultConstructor())
5134 S.DeclareImplicitDefaultConstructor(RD);
5135 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5136 CE = RD->ctor_end(); CI != CE; ++CI) {
5137 if (!CI->isDefaultConstructor())
5138 continue;
5139 DefCtor = *CI;
5140 if (!DefCtor->isUserProvided())
5141 break;
5142 }
5143
5144 *Selected = DefCtor;
5145 }
5146
5147 return false;
5148
5149 case Sema::CXXDestructor:
5150 // C++11 [class.dtor]p5:
5151 // A destructor is trivial if:
5152 // - all the direct [subobjects] have trivial destructors
5153 if (RD->hasTrivialDestructor())
5154 return true;
5155
5156 if (Selected) {
5157 if (RD->needsImplicitDestructor())
5158 S.DeclareImplicitDestructor(RD);
5159 *Selected = RD->getDestructor();
5160 }
5161
5162 return false;
5163
5164 case Sema::CXXCopyConstructor:
5165 // C++11 [class.copy]p12:
5166 // A copy constructor is trivial if:
5167 // - the constructor selected to copy each direct [subobject] is trivial
5168 if (RD->hasTrivialCopyConstructor()) {
5169 if (Quals == Qualifiers::Const)
5170 // We must either select the trivial copy constructor or reach an
5171 // ambiguity; no need to actually perform overload resolution.
5172 return true;
5173 } else if (!Selected) {
5174 return false;
5175 }
5176 // In C++98, we are not supposed to perform overload resolution here, but we
5177 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5178 // cases like B as having a non-trivial copy constructor:
5179 // struct A { template<typename T> A(T&); };
5180 // struct B { mutable A a; };
5181 goto NeedOverloadResolution;
5182
5183 case Sema::CXXCopyAssignment:
5184 // C++11 [class.copy]p25:
5185 // A copy assignment operator is trivial if:
5186 // - the assignment operator selected to copy each direct [subobject] is
5187 // trivial
5188 if (RD->hasTrivialCopyAssignment()) {
5189 if (Quals == Qualifiers::Const)
5190 return true;
5191 } else if (!Selected) {
5192 return false;
5193 }
5194 // In C++98, we are not supposed to perform overload resolution here, but we
5195 // treat that as a language defect.
5196 goto NeedOverloadResolution;
5197
5198 case Sema::CXXMoveConstructor:
5199 case Sema::CXXMoveAssignment:
5200 NeedOverloadResolution:
5201 Sema::SpecialMemberOverloadResult *SMOR =
5202 S.LookupSpecialMember(RD, CSM,
5203 Quals & Qualifiers::Const,
5204 Quals & Qualifiers::Volatile,
5205 /*RValueThis*/false, /*ConstThis*/false,
5206 /*VolatileThis*/false);
5207
5208 // The standard doesn't describe how to behave if the lookup is ambiguous.
5209 // We treat it as not making the member non-trivial, just like the standard
5210 // mandates for the default constructor. This should rarely matter, because
5211 // the member will also be deleted.
5212 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5213 return true;
5214
5215 if (!SMOR->getMethod()) {
5216 assert(SMOR->getKind() ==
5217 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5218 return false;
5219 }
5220
5221 // We deliberately don't check if we found a deleted special member. We're
5222 // not supposed to!
5223 if (Selected)
5224 *Selected = SMOR->getMethod();
5225 return SMOR->getMethod()->isTrivial();
5226 }
5227
5228 llvm_unreachable("unknown special method kind");
5229}
5230
Benjamin Kramera574c892013-02-15 12:30:38 +00005231static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005232 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5233 CI != CE; ++CI)
5234 if (!CI->isImplicit())
5235 return *CI;
5236
5237 // Look for constructor templates.
5238 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5239 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5240 if (CXXConstructorDecl *CD =
5241 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5242 return CD;
5243 }
5244
5245 return 0;
5246}
5247
5248/// The kind of subobject we are checking for triviality. The values of this
5249/// enumeration are used in diagnostics.
5250enum TrivialSubobjectKind {
5251 /// The subobject is a base class.
5252 TSK_BaseClass,
5253 /// The subobject is a non-static data member.
5254 TSK_Field,
5255 /// The object is actually the complete object.
5256 TSK_CompleteObject
5257};
5258
5259/// Check whether the special member selected for a given type would be trivial.
5260static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5261 QualType SubType,
5262 Sema::CXXSpecialMember CSM,
5263 TrivialSubobjectKind Kind,
5264 bool Diagnose) {
5265 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5266 if (!SubRD)
5267 return true;
5268
5269 CXXMethodDecl *Selected;
5270 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5271 Diagnose ? &Selected : 0))
5272 return true;
5273
5274 if (Diagnose) {
5275 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5276 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5277 << Kind << SubType.getUnqualifiedType();
5278 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5279 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5280 } else if (!Selected)
5281 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5282 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5283 else if (Selected->isUserProvided()) {
5284 if (Kind == TSK_CompleteObject)
5285 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5286 << Kind << SubType.getUnqualifiedType() << CSM;
5287 else {
5288 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5289 << Kind << SubType.getUnqualifiedType() << CSM;
5290 S.Diag(Selected->getLocation(), diag::note_declared_at);
5291 }
5292 } else {
5293 if (Kind != TSK_CompleteObject)
5294 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5295 << Kind << SubType.getUnqualifiedType() << CSM;
5296
5297 // Explain why the defaulted or deleted special member isn't trivial.
5298 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5299 }
5300 }
5301
5302 return false;
5303}
5304
5305/// Check whether the members of a class type allow a special member to be
5306/// trivial.
5307static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5308 Sema::CXXSpecialMember CSM,
5309 bool ConstArg, bool Diagnose) {
5310 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5311 FE = RD->field_end(); FI != FE; ++FI) {
5312 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5313 continue;
5314
5315 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5316
5317 // Pretend anonymous struct or union members are members of this class.
5318 if (FI->isAnonymousStructOrUnion()) {
5319 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5320 CSM, ConstArg, Diagnose))
5321 return false;
5322 continue;
5323 }
5324
5325 // C++11 [class.ctor]p5:
5326 // A default constructor is trivial if [...]
5327 // -- no non-static data member of its class has a
5328 // brace-or-equal-initializer
5329 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5330 if (Diagnose)
5331 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5332 return false;
5333 }
5334
5335 // Objective C ARC 4.3.5:
5336 // [...] nontrivally ownership-qualified types are [...] not trivially
5337 // default constructible, copy constructible, move constructible, copy
5338 // assignable, move assignable, or destructible [...]
5339 if (S.getLangOpts().ObjCAutoRefCount &&
5340 FieldType.hasNonTrivialObjCLifetime()) {
5341 if (Diagnose)
5342 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5343 << RD << FieldType.getObjCLifetime();
5344 return false;
5345 }
5346
5347 if (ConstArg && !FI->isMutable())
5348 FieldType.addConst();
5349 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5350 TSK_Field, Diagnose))
5351 return false;
5352 }
5353
5354 return true;
5355}
5356
5357/// Diagnose why the specified class does not have a trivial special member of
5358/// the given kind.
5359void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5360 QualType Ty = Context.getRecordType(RD);
5361 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5362 Ty.addConst();
5363
5364 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5365 TSK_CompleteObject, /*Diagnose*/true);
5366}
5367
5368/// Determine whether a defaulted or deleted special member function is trivial,
5369/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5370/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5371bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5372 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005373 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5374
5375 CXXRecordDecl *RD = MD->getParent();
5376
5377 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005378
5379 // C++11 [class.copy]p12, p25:
5380 // A [special member] is trivial if its declared parameter type is the same
5381 // as if it had been implicitly declared [...]
5382 switch (CSM) {
5383 case CXXDefaultConstructor:
5384 case CXXDestructor:
5385 // Trivial default constructors and destructors cannot have parameters.
5386 break;
5387
5388 case CXXCopyConstructor:
5389 case CXXCopyAssignment: {
5390 // Trivial copy operations always have const, non-volatile parameter types.
5391 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005392 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005393 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5394 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5395 if (Diagnose)
5396 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5397 << Param0->getSourceRange() << Param0->getType()
5398 << Context.getLValueReferenceType(
5399 Context.getRecordType(RD).withConst());
5400 return false;
5401 }
5402 break;
5403 }
5404
5405 case CXXMoveConstructor:
5406 case CXXMoveAssignment: {
5407 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005408 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005409 const RValueReferenceType *RT =
5410 Param0->getType()->getAs<RValueReferenceType>();
5411 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5412 if (Diagnose)
5413 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5414 << Param0->getSourceRange() << Param0->getType()
5415 << Context.getRValueReferenceType(Context.getRecordType(RD));
5416 return false;
5417 }
5418 break;
5419 }
5420
5421 case CXXInvalid:
5422 llvm_unreachable("not a special member");
5423 }
5424
5425 // FIXME: We require that the parameter-declaration-clause is equivalent to
5426 // that of an implicit declaration, not just that the declared parameter type
5427 // matches, in order to prevent absuridities like a function simultaneously
5428 // being a trivial copy constructor and a non-trivial default constructor.
5429 // This issue has not yet been assigned a core issue number.
5430 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5431 if (Diagnose)
5432 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5433 diag::note_nontrivial_default_arg)
5434 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5435 return false;
5436 }
5437 if (MD->isVariadic()) {
5438 if (Diagnose)
5439 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5440 return false;
5441 }
5442
5443 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5444 // A copy/move [constructor or assignment operator] is trivial if
5445 // -- the [member] selected to copy/move each direct base class subobject
5446 // is trivial
5447 //
5448 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5449 // A [default constructor or destructor] is trivial if
5450 // -- all the direct base classes have trivial [default constructors or
5451 // destructors]
5452 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5453 BE = RD->bases_end(); BI != BE; ++BI)
5454 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5455 ConstArg ? BI->getType().withConst()
5456 : BI->getType(),
5457 CSM, TSK_BaseClass, Diagnose))
5458 return false;
5459
5460 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5461 // A copy/move [constructor or assignment operator] for a class X is
5462 // trivial if
5463 // -- for each non-static data member of X that is of class type (or array
5464 // thereof), the constructor selected to copy/move that member is
5465 // trivial
5466 //
5467 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5468 // A [default constructor or destructor] is trivial if
5469 // -- for all of the non-static data members of its class that are of class
5470 // type (or array thereof), each such class has a trivial [default
5471 // constructor or destructor]
5472 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5473 return false;
5474
5475 // C++11 [class.dtor]p5:
5476 // A destructor is trivial if [...]
5477 // -- the destructor is not virtual
5478 if (CSM == CXXDestructor && MD->isVirtual()) {
5479 if (Diagnose)
5480 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5481 return false;
5482 }
5483
5484 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5485 // A [special member] for class X is trivial if [...]
5486 // -- class X has no virtual functions and no virtual base classes
5487 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5488 if (!Diagnose)
5489 return false;
5490
5491 if (RD->getNumVBases()) {
5492 // Check for virtual bases. We already know that the corresponding
5493 // member in all bases is trivial, so vbases must all be direct.
5494 CXXBaseSpecifier &BS = *RD->vbases_begin();
5495 assert(BS.isVirtual());
5496 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5497 return false;
5498 }
5499
5500 // Must have a virtual method.
5501 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5502 ME = RD->method_end(); MI != ME; ++MI) {
5503 if (MI->isVirtual()) {
5504 SourceLocation MLoc = MI->getLocStart();
5505 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5506 return false;
5507 }
5508 }
5509
5510 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5511 }
5512
5513 // Looks like it's trivial!
5514 return true;
5515}
5516
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005517/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005518namespace {
5519 struct FindHiddenVirtualMethodData {
5520 Sema *S;
5521 CXXMethodDecl *Method;
5522 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005523 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005524 };
5525}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005526
David Blaikie5f750682012-10-19 00:53:08 +00005527/// \brief Check whether any most overriden method from MD in Methods
5528static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5529 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5530 if (MD->size_overridden_methods() == 0)
5531 return Methods.count(MD->getCanonicalDecl());
5532 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5533 E = MD->end_overridden_methods();
5534 I != E; ++I)
5535 if (CheckMostOverridenMethods(*I, Methods))
5536 return true;
5537 return false;
5538}
5539
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005540/// \brief Member lookup function that determines whether a given C++
5541/// method overloads virtual methods in a base class without overriding any,
5542/// to be used with CXXRecordDecl::lookupInBases().
5543static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5544 CXXBasePath &Path,
5545 void *UserData) {
5546 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5547
5548 FindHiddenVirtualMethodData &Data
5549 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5550
5551 DeclarationName Name = Data.Method->getDeclName();
5552 assert(Name.getNameKind() == DeclarationName::Identifier);
5553
5554 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005555 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005556 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005557 !Path.Decls.empty();
5558 Path.Decls = Path.Decls.slice(1)) {
5559 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005560 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005561 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005562 foundSameNameMethod = true;
5563 // Interested only in hidden virtual methods.
5564 if (!MD->isVirtual())
5565 continue;
5566 // If the method we are checking overrides a method from its base
5567 // don't warn about the other overloaded methods.
5568 if (!Data.S->IsOverload(Data.Method, MD, false))
5569 return true;
5570 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005571 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005572 overloadedMethods.push_back(MD);
5573 }
5574 }
5575
5576 if (foundSameNameMethod)
5577 Data.OverloadedMethods.append(overloadedMethods.begin(),
5578 overloadedMethods.end());
5579 return foundSameNameMethod;
5580}
5581
David Blaikie5f750682012-10-19 00:53:08 +00005582/// \brief Add the most overriden methods from MD to Methods
5583static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5584 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5585 if (MD->size_overridden_methods() == 0)
5586 Methods.insert(MD->getCanonicalDecl());
5587 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5588 E = MD->end_overridden_methods();
5589 I != E; ++I)
5590 AddMostOverridenMethods(*I, Methods);
5591}
5592
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005593/// \brief See if a method overloads virtual methods in a base class without
5594/// overriding any.
5595void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5596 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005597 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005598 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005599 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005600 return;
5601
5602 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5603 /*bool RecordPaths=*/false,
5604 /*bool DetectVirtual=*/false);
5605 FindHiddenVirtualMethodData Data;
5606 Data.Method = MD;
5607 Data.S = this;
5608
5609 // Keep the base methods that were overriden or introduced in the subclass
5610 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005611 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5612 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5613 NamedDecl *ND = *I;
5614 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005615 ND = shad->getTargetDecl();
5616 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5617 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005618 }
5619
5620 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5621 !Data.OverloadedMethods.empty()) {
5622 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5623 << MD << (Data.OverloadedMethods.size() > 1);
5624
5625 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5626 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005627 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005628 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005629 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5630 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005631 }
5632 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005633}
5634
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005635void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005636 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005637 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005638 SourceLocation RBrac,
5639 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005640 if (!TagDecl)
5641 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005642
Douglas Gregor42af25f2009-05-11 19:58:34 +00005643 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005644
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005645 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5646 if (l->getKind() != AttributeList::AT_Visibility)
5647 continue;
5648 l->setInvalid();
5649 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5650 l->getName();
5651 }
5652
David Blaikie77b6de02011-09-22 02:58:26 +00005653 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005654 // strict aliasing violation!
5655 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005656 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005657
Douglas Gregor23c94db2010-07-02 17:43:08 +00005658 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005659 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005660}
5661
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005662/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5663/// special functions, such as the default constructor, copy
5664/// constructor, or destructor, to the given C++ class (C++
5665/// [special]p1). This routine can only be executed just before the
5666/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005667void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005668 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005669 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005670
Richard Smithbc2a35d2012-12-08 08:32:28 +00005671 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005672 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005673
Richard Smithbc2a35d2012-12-08 08:32:28 +00005674 // If the properties or semantics of the copy constructor couldn't be
5675 // determined while the class was being declared, force a declaration
5676 // of it now.
5677 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5678 DeclareImplicitCopyConstructor(ClassDecl);
5679 }
5680
Richard Smith80ad52f2013-01-02 11:42:31 +00005681 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005682 ++ASTContext::NumImplicitMoveConstructors;
5683
Richard Smithbc2a35d2012-12-08 08:32:28 +00005684 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5685 DeclareImplicitMoveConstructor(ClassDecl);
5686 }
5687
Douglas Gregora376d102010-07-02 21:50:04 +00005688 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5689 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005690
5691 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005692 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005693 // it shows up in the right place in the vtable and that we diagnose
5694 // problems with the implicit exception specification.
5695 if (ClassDecl->isDynamicClass() ||
5696 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005697 DeclareImplicitCopyAssignment(ClassDecl);
5698 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005699
Richard Smith80ad52f2013-01-02 11:42:31 +00005700 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005701 ++ASTContext::NumImplicitMoveAssignmentOperators;
5702
5703 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005704 if (ClassDecl->isDynamicClass() ||
5705 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005706 DeclareImplicitMoveAssignment(ClassDecl);
5707 }
5708
Douglas Gregor4923aa22010-07-02 20:37:36 +00005709 if (!ClassDecl->hasUserDeclaredDestructor()) {
5710 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005711
5712 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005713 // have to declare the destructor immediately. This ensures that, e.g., it
5714 // shows up in the right place in the vtable and that we diagnose problems
5715 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005716 if (ClassDecl->isDynamicClass() ||
5717 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005718 DeclareImplicitDestructor(ClassDecl);
5719 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005720}
5721
Francois Pichet8387e2a2011-04-22 22:18:13 +00005722void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5723 if (!D)
5724 return;
5725
5726 int NumParamList = D->getNumTemplateParameterLists();
5727 for (int i = 0; i < NumParamList; i++) {
5728 TemplateParameterList* Params = D->getTemplateParameterList(i);
5729 for (TemplateParameterList::iterator Param = Params->begin(),
5730 ParamEnd = Params->end();
5731 Param != ParamEnd; ++Param) {
5732 NamedDecl *Named = cast<NamedDecl>(*Param);
5733 if (Named->getDeclName()) {
5734 S->AddDecl(Named);
5735 IdResolver.AddDecl(Named);
5736 }
5737 }
5738 }
5739}
5740
John McCalld226f652010-08-21 09:40:31 +00005741void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005742 if (!D)
5743 return;
5744
5745 TemplateParameterList *Params = 0;
5746 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5747 Params = Template->getTemplateParameters();
5748 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5749 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5750 Params = PartialSpec->getTemplateParameters();
5751 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005752 return;
5753
Douglas Gregor6569d682009-05-27 23:11:45 +00005754 for (TemplateParameterList::iterator Param = Params->begin(),
5755 ParamEnd = Params->end();
5756 Param != ParamEnd; ++Param) {
5757 NamedDecl *Named = cast<NamedDecl>(*Param);
5758 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005759 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005760 IdResolver.AddDecl(Named);
5761 }
5762 }
5763}
5764
John McCalld226f652010-08-21 09:40:31 +00005765void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005766 if (!RecordD) return;
5767 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005768 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005769 PushDeclContext(S, Record);
5770}
5771
John McCalld226f652010-08-21 09:40:31 +00005772void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005773 if (!RecordD) return;
5774 PopDeclContext();
5775}
5776
Douglas Gregor72b505b2008-12-16 21:30:33 +00005777/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5778/// parsing a top-level (non-nested) C++ class, and we are now
5779/// parsing those parts of the given Method declaration that could
5780/// not be parsed earlier (C++ [class.mem]p2), such as default
5781/// arguments. This action should enter the scope of the given
5782/// Method declaration as if we had just parsed the qualified method
5783/// name. However, it should not bring the parameters into scope;
5784/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005785void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005786}
5787
5788/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5789/// C++ method declaration. We're (re-)introducing the given
5790/// function parameter into scope for use in parsing later parts of
5791/// the method declaration. For example, we could see an
5792/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005793void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005794 if (!ParamD)
5795 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005796
John McCalld226f652010-08-21 09:40:31 +00005797 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005798
5799 // If this parameter has an unparsed default argument, clear it out
5800 // to make way for the parsed default argument.
5801 if (Param->hasUnparsedDefaultArg())
5802 Param->setDefaultArg(0);
5803
John McCalld226f652010-08-21 09:40:31 +00005804 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005805 if (Param->getDeclName())
5806 IdResolver.AddDecl(Param);
5807}
5808
5809/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5810/// processing the delayed method declaration for Method. The method
5811/// declaration is now considered finished. There may be a separate
5812/// ActOnStartOfFunctionDef action later (not necessarily
5813/// immediately!) for this method, if it was also defined inside the
5814/// class body.
John McCalld226f652010-08-21 09:40:31 +00005815void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005816 if (!MethodD)
5817 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005818
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005819 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005820
John McCalld226f652010-08-21 09:40:31 +00005821 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005822
5823 // Now that we have our default arguments, check the constructor
5824 // again. It could produce additional diagnostics or affect whether
5825 // the class has implicitly-declared destructors, among other
5826 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005827 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5828 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005829
5830 // Check the default arguments, which we may have added.
5831 if (!Method->isInvalidDecl())
5832 CheckCXXDefaultArguments(Method);
5833}
5834
Douglas Gregor42a552f2008-11-05 20:51:48 +00005835/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005836/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005837/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005838/// emit diagnostics and set the invalid bit to true. In any case, the type
5839/// will be updated to reflect a well-formed type for the constructor and
5840/// returned.
5841QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005842 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005843 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005844
5845 // C++ [class.ctor]p3:
5846 // A constructor shall not be virtual (10.3) or static (9.4). A
5847 // constructor can be invoked for a const, volatile or const
5848 // volatile object. A constructor shall not be declared const,
5849 // volatile, or const volatile (9.3.2).
5850 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005851 if (!D.isInvalidType())
5852 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5853 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5854 << SourceRange(D.getIdentifierLoc());
5855 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005856 }
John McCalld931b082010-08-26 03:08:43 +00005857 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005858 if (!D.isInvalidType())
5859 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5860 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5861 << SourceRange(D.getIdentifierLoc());
5862 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005863 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005864 }
Mike Stump1eb44332009-09-09 15:08:12 +00005865
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005866 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005867 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005868 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005869 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5870 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005871 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005872 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5873 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005874 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005875 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5876 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005877 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005878 }
Mike Stump1eb44332009-09-09 15:08:12 +00005879
Douglas Gregorc938c162011-01-26 05:01:58 +00005880 // C++0x [class.ctor]p4:
5881 // A constructor shall not be declared with a ref-qualifier.
5882 if (FTI.hasRefQualifier()) {
5883 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5884 << FTI.RefQualifierIsLValueRef
5885 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5886 D.setInvalidType();
5887 }
5888
Douglas Gregor42a552f2008-11-05 20:51:48 +00005889 // Rebuild the function type "R" without any type qualifiers (in
5890 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005891 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005892 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005893 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5894 return R;
5895
5896 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5897 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005898 EPI.RefQualifier = RQ_None;
5899
Richard Smith07b0fdc2013-03-18 21:12:30 +00005900 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005901}
5902
Douglas Gregor72b505b2008-12-16 21:30:33 +00005903/// CheckConstructor - Checks a fully-formed constructor for
5904/// well-formedness, issuing any diagnostics required. Returns true if
5905/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005906void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005907 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005908 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5909 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005910 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005911
5912 // C++ [class.copy]p3:
5913 // A declaration of a constructor for a class X is ill-formed if
5914 // its first parameter is of type (optionally cv-qualified) X and
5915 // either there are no other parameters or else all other
5916 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005917 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005918 ((Constructor->getNumParams() == 1) ||
5919 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005920 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5921 Constructor->getTemplateSpecializationKind()
5922 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005923 QualType ParamType = Constructor->getParamDecl(0)->getType();
5924 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5925 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005926 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005927 const char *ConstRef
5928 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5929 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005930 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005931 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005932
5933 // FIXME: Rather that making the constructor invalid, we should endeavor
5934 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005935 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005936 }
5937 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005938}
5939
John McCall15442822010-08-04 01:04:25 +00005940/// CheckDestructor - Checks a fully-formed destructor definition for
5941/// well-formedness, issuing any diagnostics required. Returns true
5942/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005943bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005944 CXXRecordDecl *RD = Destructor->getParent();
5945
Peter Collingbournef51cfb82013-05-20 14:12:25 +00005946 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005947 SourceLocation Loc;
5948
5949 if (!Destructor->isImplicit())
5950 Loc = Destructor->getLocation();
5951 else
5952 Loc = RD->getLocation();
5953
5954 // If we have a virtual destructor, look up the deallocation function
5955 FunctionDecl *OperatorDelete = 0;
5956 DeclarationName Name =
5957 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005958 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005959 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005960
Eli Friedman5f2987c2012-02-02 03:46:19 +00005961 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005962
5963 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005964 }
Anders Carlsson37909802009-11-30 21:24:50 +00005965
5966 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005967}
5968
Mike Stump1eb44332009-09-09 15:08:12 +00005969static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005970FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5971 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5972 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005973 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005974}
5975
Douglas Gregor42a552f2008-11-05 20:51:48 +00005976/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5977/// the well-formednes of the destructor declarator @p D with type @p
5978/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005979/// emit diagnostics and set the declarator to invalid. Even if this happens,
5980/// will be updated to reflect a well-formed type for the destructor and
5981/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005982QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005983 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005984 // C++ [class.dtor]p1:
5985 // [...] A typedef-name that names a class is a class-name
5986 // (7.1.3); however, a typedef-name that names a class shall not
5987 // be used as the identifier in the declarator for a destructor
5988 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005989 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005990 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005991 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005992 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005993 else if (const TemplateSpecializationType *TST =
5994 DeclaratorType->getAs<TemplateSpecializationType>())
5995 if (TST->isTypeAlias())
5996 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5997 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005998
5999 // C++ [class.dtor]p2:
6000 // A destructor is used to destroy objects of its class type. A
6001 // destructor takes no parameters, and no return type can be
6002 // specified for it (not even void). The address of a destructor
6003 // shall not be taken. A destructor shall not be static. A
6004 // destructor can be invoked for a const, volatile or const
6005 // volatile object. A destructor shall not be declared const,
6006 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00006007 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006008 if (!D.isInvalidType())
6009 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6010 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00006011 << SourceRange(D.getIdentifierLoc())
6012 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6013
John McCalld931b082010-08-26 03:08:43 +00006014 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006015 }
Chris Lattner65401802009-04-25 08:28:21 +00006016 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006017 // Destructors don't have return types, but the parser will
6018 // happily parse something like:
6019 //
6020 // class X {
6021 // float ~X();
6022 // };
6023 //
6024 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006025 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6026 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6027 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00006028 }
Mike Stump1eb44332009-09-09 15:08:12 +00006029
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006030 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006031 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006032 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006033 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6034 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006035 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006036 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6037 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006038 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006039 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6040 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006041 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006042 }
6043
Douglas Gregorc938c162011-01-26 05:01:58 +00006044 // C++0x [class.dtor]p2:
6045 // A destructor shall not be declared with a ref-qualifier.
6046 if (FTI.hasRefQualifier()) {
6047 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6048 << FTI.RefQualifierIsLValueRef
6049 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6050 D.setInvalidType();
6051 }
6052
Douglas Gregor42a552f2008-11-05 20:51:48 +00006053 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006054 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006055 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6056
6057 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006058 FTI.freeArgs();
6059 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006060 }
6061
Mike Stump1eb44332009-09-09 15:08:12 +00006062 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006063 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006064 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006065 D.setInvalidType();
6066 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006067
6068 // Rebuild the function type "R" without any type qualifiers or
6069 // parameters (in case any of the errors above fired) and with
6070 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006071 // types.
John McCalle23cf432010-12-14 08:05:40 +00006072 if (!D.isInvalidType())
6073 return R;
6074
Douglas Gregord92ec472010-07-01 05:10:53 +00006075 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006076 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6077 EPI.Variadic = false;
6078 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006079 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006080 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006081}
6082
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006083/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6084/// well-formednes of the conversion function declarator @p D with
6085/// type @p R. If there are any errors in the declarator, this routine
6086/// will emit diagnostics and return true. Otherwise, it will return
6087/// false. Either way, the type @p R will be updated to reflect a
6088/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006089void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006090 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006091 // C++ [class.conv.fct]p1:
6092 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006093 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006094 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006095 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006096 if (!D.isInvalidType())
6097 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006098 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6099 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006100 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006101 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006102 }
John McCalla3f81372010-04-13 00:04:31 +00006103
6104 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6105
Chris Lattner6e475012009-04-25 08:35:12 +00006106 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006107 // Conversion functions don't have return types, but the parser will
6108 // happily parse something like:
6109 //
6110 // class X {
6111 // float operator bool();
6112 // };
6113 //
6114 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006115 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6116 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6117 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006118 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006119 }
6120
John McCalla3f81372010-04-13 00:04:31 +00006121 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6122
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006123 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006124 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006125 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6126
6127 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006128 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006129 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006130 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006131 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006132 D.setInvalidType();
6133 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006134
John McCalla3f81372010-04-13 00:04:31 +00006135 // Diagnose "&operator bool()" and other such nonsense. This
6136 // is actually a gcc extension which we don't support.
6137 if (Proto->getResultType() != ConvType) {
6138 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6139 << Proto->getResultType();
6140 D.setInvalidType();
6141 ConvType = Proto->getResultType();
6142 }
6143
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006144 // C++ [class.conv.fct]p4:
6145 // The conversion-type-id shall not represent a function type nor
6146 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006147 if (ConvType->isArrayType()) {
6148 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6149 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006150 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006151 } else if (ConvType->isFunctionType()) {
6152 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6153 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006154 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006155 }
6156
6157 // Rebuild the function type "R" without any parameters (in case any
6158 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006159 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006160 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006161 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006162
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006163 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006164 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006165 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006166 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006167 diag::warn_cxx98_compat_explicit_conversion_functions :
6168 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006169 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006170}
6171
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006172/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6173/// the declaration of the given C++ conversion function. This routine
6174/// is responsible for recording the conversion function in the C++
6175/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006176Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006177 assert(Conversion && "Expected to receive a conversion function declaration");
6178
Douglas Gregor9d350972008-12-12 08:25:50 +00006179 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006180
6181 // Make sure we aren't redeclaring the conversion function.
6182 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006183
6184 // C++ [class.conv.fct]p1:
6185 // [...] A conversion function is never used to convert a
6186 // (possibly cv-qualified) object to the (possibly cv-qualified)
6187 // same object type (or a reference to it), to a (possibly
6188 // cv-qualified) base class of that type (or a reference to it),
6189 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006190 // FIXME: Suppress this warning if the conversion function ends up being a
6191 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006192 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006193 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006194 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006195 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006196 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6197 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006198 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006199 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006200 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6201 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006202 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006203 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006204 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006205 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006206 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006207 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006208 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006209 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006210 }
6211
Douglas Gregore80622f2010-09-29 04:25:11 +00006212 if (FunctionTemplateDecl *ConversionTemplate
6213 = Conversion->getDescribedFunctionTemplate())
6214 return ConversionTemplate;
6215
John McCalld226f652010-08-21 09:40:31 +00006216 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006217}
6218
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006219//===----------------------------------------------------------------------===//
6220// Namespace Handling
6221//===----------------------------------------------------------------------===//
6222
Richard Smithd1a55a62012-10-04 22:13:39 +00006223/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6224/// reopened.
6225static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6226 SourceLocation Loc,
6227 IdentifierInfo *II, bool *IsInline,
6228 NamespaceDecl *PrevNS) {
6229 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006230
Richard Smithc969e6a2012-10-05 01:46:25 +00006231 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6232 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6233 // inline namespaces, with the intention of bringing names into namespace std.
6234 //
6235 // We support this just well enough to get that case working; this is not
6236 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006237 if (*IsInline && II && II->getName().startswith("__atomic") &&
6238 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006239 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006240 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6241 NS = NS->getPreviousDecl())
6242 NS->setInline(*IsInline);
6243 // Patch up the lookup table for the containing namespace. This isn't really
6244 // correct, but it's good enough for this particular case.
6245 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6246 E = PrevNS->decls_end(); I != E; ++I)
6247 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6248 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6249 return;
6250 }
6251
6252 if (PrevNS->isInline())
6253 // The user probably just forgot the 'inline', so suggest that it
6254 // be added back.
6255 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6256 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6257 else
6258 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6259 << IsInline;
6260
6261 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6262 *IsInline = PrevNS->isInline();
6263}
John McCallea318642010-08-26 09:15:37 +00006264
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006265/// ActOnStartNamespaceDef - This is called at the start of a namespace
6266/// definition.
John McCalld226f652010-08-21 09:40:31 +00006267Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006268 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006269 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006270 SourceLocation IdentLoc,
6271 IdentifierInfo *II,
6272 SourceLocation LBrace,
6273 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006274 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6275 // For anonymous namespace, take the location of the left brace.
6276 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006277 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006278 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006279 bool IsStd = false;
6280 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006281 Scope *DeclRegionScope = NamespcScope->getParent();
6282
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006283 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006284 if (II) {
6285 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006286 // The identifier in an original-namespace-definition shall not
6287 // have been previously defined in the declarative region in
6288 // which the original-namespace-definition appears. The
6289 // identifier in an original-namespace-definition is the name of
6290 // the namespace. Subsequently in that declarative region, it is
6291 // treated as an original-namespace-name.
6292 //
6293 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006294 // look through using directives, just look for any ordinary names.
6295
6296 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006297 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6298 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006299 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006300 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6301 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6302 ++I) {
6303 if ((*I)->getIdentifierNamespace() & IDNS) {
6304 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006305 break;
6306 }
6307 }
6308
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006309 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6310
6311 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006312 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006313 if (IsInline != PrevNS->isInline())
6314 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6315 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006316 } else if (PrevDecl) {
6317 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006318 Diag(Loc, diag::err_redefinition_different_kind)
6319 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006320 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006321 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006322 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006323 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006324 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006325 // This is the first "real" definition of the namespace "std", so update
6326 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006327 PrevNS = getStdNamespace();
6328 IsStd = true;
6329 AddToKnown = !IsInline;
6330 } else {
6331 // We've seen this namespace for the first time.
6332 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006333 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006334 } else {
John McCall9aeed322009-10-01 00:25:31 +00006335 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006336
6337 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006338 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006339 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006340 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006341 } else {
6342 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006343 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006344 }
6345
Richard Smithd1a55a62012-10-04 22:13:39 +00006346 if (PrevNS && IsInline != PrevNS->isInline())
6347 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6348 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006349 }
6350
6351 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6352 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006353 if (IsInvalid)
6354 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006355
6356 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006357
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006358 // FIXME: Should we be merging attributes?
6359 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006360 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006361
6362 if (IsStd)
6363 StdNamespace = Namespc;
6364 if (AddToKnown)
6365 KnownNamespaces[Namespc] = false;
6366
6367 if (II) {
6368 PushOnScopeChains(Namespc, DeclRegionScope);
6369 } else {
6370 // Link the anonymous namespace into its parent.
6371 DeclContext *Parent = CurContext->getRedeclContext();
6372 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6373 TU->setAnonymousNamespace(Namespc);
6374 } else {
6375 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006376 }
John McCall9aeed322009-10-01 00:25:31 +00006377
Douglas Gregora4181472010-03-24 00:46:35 +00006378 CurContext->addDecl(Namespc);
6379
John McCall9aeed322009-10-01 00:25:31 +00006380 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6381 // behaves as if it were replaced by
6382 // namespace unique { /* empty body */ }
6383 // using namespace unique;
6384 // namespace unique { namespace-body }
6385 // where all occurrences of 'unique' in a translation unit are
6386 // replaced by the same identifier and this identifier differs
6387 // from all other identifiers in the entire program.
6388
6389 // We just create the namespace with an empty name and then add an
6390 // implicit using declaration, just like the standard suggests.
6391 //
6392 // CodeGen enforces the "universally unique" aspect by giving all
6393 // declarations semantically contained within an anonymous
6394 // namespace internal linkage.
6395
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006396 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006397 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006398 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006399 /* 'using' */ LBrace,
6400 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006401 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006402 /* identifier */ SourceLocation(),
6403 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006404 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006405 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006406 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006407 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006408 }
6409
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006410 ActOnDocumentableDecl(Namespc);
6411
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006412 // Although we could have an invalid decl (i.e. the namespace name is a
6413 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006414 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6415 // for the namespace has the declarations that showed up in that particular
6416 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006417 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006418 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006419}
6420
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006421/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6422/// is a namespace alias, returns the namespace it points to.
6423static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6424 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6425 return AD->getNamespace();
6426 return dyn_cast_or_null<NamespaceDecl>(D);
6427}
6428
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006429/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6430/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006431void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006432 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6433 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006434 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006435 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006436 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006437 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006438}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006439
John McCall384aff82010-08-25 07:42:41 +00006440CXXRecordDecl *Sema::getStdBadAlloc() const {
6441 return cast_or_null<CXXRecordDecl>(
6442 StdBadAlloc.get(Context.getExternalSource()));
6443}
6444
6445NamespaceDecl *Sema::getStdNamespace() const {
6446 return cast_or_null<NamespaceDecl>(
6447 StdNamespace.get(Context.getExternalSource()));
6448}
6449
Douglas Gregor66992202010-06-29 17:53:46 +00006450/// \brief Retrieve the special "std" namespace, which may require us to
6451/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006452NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006453 if (!StdNamespace) {
6454 // The "std" namespace has not yet been defined, so build one implicitly.
6455 StdNamespace = NamespaceDecl::Create(Context,
6456 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006457 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006458 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006459 &PP.getIdentifierTable().get("std"),
6460 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006461 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006462 }
6463
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006464 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006465}
6466
Sebastian Redl395e04d2012-01-17 22:49:33 +00006467bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006468 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006469 "Looking for std::initializer_list outside of C++.");
6470
6471 // We're looking for implicit instantiations of
6472 // template <typename E> class std::initializer_list.
6473
6474 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6475 return false;
6476
Sebastian Redl84760e32012-01-17 22:49:58 +00006477 ClassTemplateDecl *Template = 0;
6478 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006479
Sebastian Redl84760e32012-01-17 22:49:58 +00006480 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006481
Sebastian Redl84760e32012-01-17 22:49:58 +00006482 ClassTemplateSpecializationDecl *Specialization =
6483 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6484 if (!Specialization)
6485 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006486
Sebastian Redl84760e32012-01-17 22:49:58 +00006487 Template = Specialization->getSpecializedTemplate();
6488 Arguments = Specialization->getTemplateArgs().data();
6489 } else if (const TemplateSpecializationType *TST =
6490 Ty->getAs<TemplateSpecializationType>()) {
6491 Template = dyn_cast_or_null<ClassTemplateDecl>(
6492 TST->getTemplateName().getAsTemplateDecl());
6493 Arguments = TST->getArgs();
6494 }
6495 if (!Template)
6496 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006497
6498 if (!StdInitializerList) {
6499 // Haven't recognized std::initializer_list yet, maybe this is it.
6500 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6501 if (TemplateClass->getIdentifier() !=
6502 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006503 !getStdNamespace()->InEnclosingNamespaceSetOf(
6504 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006505 return false;
6506 // This is a template called std::initializer_list, but is it the right
6507 // template?
6508 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006509 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006510 return false;
6511 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6512 return false;
6513
6514 // It's the right template.
6515 StdInitializerList = Template;
6516 }
6517
6518 if (Template != StdInitializerList)
6519 return false;
6520
6521 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006522 if (Element)
6523 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006524 return true;
6525}
6526
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006527static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6528 NamespaceDecl *Std = S.getStdNamespace();
6529 if (!Std) {
6530 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6531 return 0;
6532 }
6533
6534 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6535 Loc, Sema::LookupOrdinaryName);
6536 if (!S.LookupQualifiedName(Result, Std)) {
6537 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6538 return 0;
6539 }
6540 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6541 if (!Template) {
6542 Result.suppressDiagnostics();
6543 // We found something weird. Complain about the first thing we found.
6544 NamedDecl *Found = *Result.begin();
6545 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6546 return 0;
6547 }
6548
6549 // We found some template called std::initializer_list. Now verify that it's
6550 // correct.
6551 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006552 if (Params->getMinRequiredArguments() != 1 ||
6553 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006554 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6555 return 0;
6556 }
6557
6558 return Template;
6559}
6560
6561QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6562 if (!StdInitializerList) {
6563 StdInitializerList = LookupStdInitializerList(*this, Loc);
6564 if (!StdInitializerList)
6565 return QualType();
6566 }
6567
6568 TemplateArgumentListInfo Args(Loc, Loc);
6569 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6570 Context.getTrivialTypeSourceInfo(Element,
6571 Loc)));
6572 return Context.getCanonicalType(
6573 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6574}
6575
Sebastian Redl98d36062012-01-17 22:50:14 +00006576bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6577 // C++ [dcl.init.list]p2:
6578 // A constructor is an initializer-list constructor if its first parameter
6579 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6580 // std::initializer_list<E> for some type E, and either there are no other
6581 // parameters or else all other parameters have default arguments.
6582 if (Ctor->getNumParams() < 1 ||
6583 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6584 return false;
6585
6586 QualType ArgType = Ctor->getParamDecl(0)->getType();
6587 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6588 ArgType = RT->getPointeeType().getUnqualifiedType();
6589
6590 return isStdInitializerList(ArgType, 0);
6591}
6592
Douglas Gregor9172aa62011-03-26 22:25:30 +00006593/// \brief Determine whether a using statement is in a context where it will be
6594/// apply in all contexts.
6595static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6596 switch (CurContext->getDeclKind()) {
6597 case Decl::TranslationUnit:
6598 return true;
6599 case Decl::LinkageSpec:
6600 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6601 default:
6602 return false;
6603 }
6604}
6605
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006606namespace {
6607
6608// Callback to only accept typo corrections that are namespaces.
6609class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00006610public:
6611 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6612 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006613 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006614 return false;
6615 }
6616};
6617
6618}
6619
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006620static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6621 CXXScopeSpec &SS,
6622 SourceLocation IdentLoc,
6623 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006624 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006625 R.clear();
6626 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006627 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006628 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006629 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6630 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006631 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
6632 bool droppedSpecifier = Corrected.WillReplaceSpecifier() &&
6633 Ident->getName().equals(CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006634 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006635 << Ident << DC << droppedSpecifier << CorrectedQuotedStr
6636 << SS.getRange() << FixItHint::CreateReplacement(
6637 Corrected.getCorrectionRange(), CorrectedStr);
6638 } else {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006639 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6640 << Ident << CorrectedQuotedStr
6641 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006642 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006643
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006644 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6645 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006646
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006647 R.addDecl(Corrected.getCorrectionDecl());
6648 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006649 }
6650 return false;
6651}
6652
John McCalld226f652010-08-21 09:40:31 +00006653Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006654 SourceLocation UsingLoc,
6655 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006656 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006657 SourceLocation IdentLoc,
6658 IdentifierInfo *NamespcName,
6659 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006660 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6661 assert(NamespcName && "Invalid NamespcName.");
6662 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006663
6664 // This can only happen along a recovery path.
6665 while (S->getFlags() & Scope::TemplateParamScope)
6666 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006667 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006668
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006669 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006670 NestedNameSpecifier *Qualifier = 0;
6671 if (SS.isSet())
6672 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6673
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006674 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006675 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6676 LookupParsedName(R, S, &SS);
6677 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006678 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006679
Douglas Gregor66992202010-06-29 17:53:46 +00006680 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006681 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006682 // Allow "using namespace std;" or "using namespace ::std;" even if
6683 // "std" hasn't been defined yet, for GCC compatibility.
6684 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6685 NamespcName->isStr("std")) {
6686 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006687 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006688 R.resolveKind();
6689 }
6690 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006691 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006692 }
6693
John McCallf36e02d2009-10-09 21:13:30 +00006694 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006695 NamedDecl *Named = R.getFoundDecl();
6696 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6697 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006698 // C++ [namespace.udir]p1:
6699 // A using-directive specifies that the names in the nominated
6700 // namespace can be used in the scope in which the
6701 // using-directive appears after the using-directive. During
6702 // unqualified name lookup (3.4.1), the names appear as if they
6703 // were declared in the nearest enclosing namespace which
6704 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006705 // namespace. [Note: in this context, "contains" means "contains
6706 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006707
6708 // Find enclosing context containing both using-directive and
6709 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006710 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006711 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6712 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6713 CommonAncestor = CommonAncestor->getParent();
6714
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006715 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006716 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006717 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006718
Douglas Gregor9172aa62011-03-26 22:25:30 +00006719 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006720 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006721 Diag(IdentLoc, diag::warn_using_directive_in_header);
6722 }
6723
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006724 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006725 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006726 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006727 }
6728
Richard Smith6b3d3e52013-02-20 19:22:51 +00006729 if (UDir)
6730 ProcessDeclAttributeList(S, UDir, AttrList);
6731
John McCalld226f652010-08-21 09:40:31 +00006732 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006733}
6734
6735void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006736 // If the scope has an associated entity and the using directive is at
6737 // namespace or translation unit scope, add the UsingDirectiveDecl into
6738 // its lookup structure so qualified name lookup can find it.
6739 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6740 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006741 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006742 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006743 // Otherwise, it is at block sope. The using-directives will affect lookup
6744 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006745 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006746}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006747
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006748
John McCalld226f652010-08-21 09:40:31 +00006749Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006750 AccessSpecifier AS,
6751 bool HasUsingKeyword,
6752 SourceLocation UsingLoc,
6753 CXXScopeSpec &SS,
6754 UnqualifiedId &Name,
6755 AttributeList *AttrList,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00006756 bool HasTypenameKeyword,
John McCall78b81052010-11-10 02:40:36 +00006757 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006758 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006759
Douglas Gregor12c118a2009-11-04 16:30:06 +00006760 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006761 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006762 case UnqualifiedId::IK_Identifier:
6763 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006764 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006765 case UnqualifiedId::IK_ConversionFunctionId:
6766 break;
6767
6768 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006769 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006770 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006771 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006772 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006773 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006774 diag::err_using_decl_constructor)
6775 << SS.getRange();
6776
Richard Smith80ad52f2013-01-02 11:42:31 +00006777 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006778
John McCalld226f652010-08-21 09:40:31 +00006779 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006780
6781 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006782 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006783 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006784 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006785
6786 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006787 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006788 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006789 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006790 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006791
6792 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6793 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006794 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006795 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006796
Richard Smith07b0fdc2013-03-18 21:12:30 +00006797 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006798 if (!HasUsingKeyword) {
Enea Zaffanellad4de59d2013-07-17 17:28:56 +00006799 Diag(Name.getLocStart(),
Richard Smith1b2209f2013-06-13 02:12:17 +00006800 getLangOpts().CPlusPlus11 ? diag::err_access_decl
6801 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006802 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006803 }
6804
Douglas Gregor56c04582010-12-16 00:46:58 +00006805 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6806 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6807 return 0;
6808
John McCall9488ea12009-11-17 05:59:44 +00006809 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006810 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006811 /* IsInstantiation */ false,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00006812 HasTypenameKeyword, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006813 if (UD)
6814 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006815
John McCalld226f652010-08-21 09:40:31 +00006816 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006817}
6818
Douglas Gregor09acc982010-07-07 23:08:52 +00006819/// \brief Determine whether a using declaration considers the given
6820/// declarations as "equivalent", e.g., if they are redeclarations of
6821/// the same entity or are both typedefs of the same type.
6822static bool
6823IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6824 bool &SuppressRedeclaration) {
6825 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6826 SuppressRedeclaration = false;
6827 return true;
6828 }
6829
Richard Smith162e1c12011-04-15 14:24:37 +00006830 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6831 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006832 SuppressRedeclaration = true;
6833 return Context.hasSameType(TD1->getUnderlyingType(),
6834 TD2->getUnderlyingType());
6835 }
6836
6837 return false;
6838}
6839
6840
John McCall9f54ad42009-12-10 09:41:52 +00006841/// Determines whether to create a using shadow decl for a particular
6842/// decl, given the set of decls existing prior to this using lookup.
6843bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6844 const LookupResult &Previous) {
6845 // Diagnose finding a decl which is not from a base class of the
6846 // current class. We do this now because there are cases where this
6847 // function will silently decide not to build a shadow decl, which
6848 // will pre-empt further diagnostics.
6849 //
6850 // We don't need to do this in C++0x because we do the check once on
6851 // the qualifier.
6852 //
6853 // FIXME: diagnose the following if we care enough:
6854 // struct A { int foo; };
6855 // struct B : A { using A::foo; };
6856 // template <class T> struct C : A {};
6857 // template <class T> struct D : C<T> { using B::foo; } // <---
6858 // This is invalid (during instantiation) in C++03 because B::foo
6859 // resolves to the using decl in B, which is not a base class of D<T>.
6860 // We can't diagnose it immediately because C<T> is an unknown
6861 // specialization. The UsingShadowDecl in D<T> then points directly
6862 // to A::foo, which will look well-formed when we instantiate.
6863 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006864 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006865 DeclContext *OrigDC = Orig->getDeclContext();
6866
6867 // Handle enums and anonymous structs.
6868 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6869 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6870 while (OrigRec->isAnonymousStructOrUnion())
6871 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6872
6873 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6874 if (OrigDC == CurContext) {
6875 Diag(Using->getLocation(),
6876 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006877 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006878 Diag(Orig->getLocation(), diag::note_using_decl_target);
6879 return true;
6880 }
6881
Douglas Gregordc355712011-02-25 00:36:19 +00006882 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006883 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006884 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006885 << cast<CXXRecordDecl>(CurContext)
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 }
6891
6892 if (Previous.empty()) return false;
6893
6894 NamedDecl *Target = Orig;
6895 if (isa<UsingShadowDecl>(Target))
6896 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6897
John McCalld7533ec2009-12-11 02:33:26 +00006898 // If the target happens to be one of the previous declarations, we
6899 // don't have a conflict.
6900 //
6901 // FIXME: but we might be increasing its access, in which case we
6902 // should redeclare it.
6903 NamedDecl *NonTag = 0, *Tag = 0;
6904 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6905 I != E; ++I) {
6906 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006907 bool Result;
6908 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6909 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006910
6911 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6912 }
6913
John McCall9f54ad42009-12-10 09:41:52 +00006914 if (Target->isFunctionOrFunctionTemplate()) {
6915 FunctionDecl *FD;
6916 if (isa<FunctionTemplateDecl>(Target))
6917 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6918 else
6919 FD = cast<FunctionDecl>(Target);
6920
6921 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006922 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006923 case Ovl_Overload:
6924 return false;
6925
6926 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006927 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006928 break;
6929
6930 // We found a decl with the exact signature.
6931 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006932 // If we're in a record, we want to hide the target, so we
6933 // return true (without a diagnostic) to tell the caller not to
6934 // build a shadow decl.
6935 if (CurContext->isRecord())
6936 return true;
6937
6938 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006939 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006940 break;
6941 }
6942
6943 Diag(Target->getLocation(), diag::note_using_decl_target);
6944 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6945 return true;
6946 }
6947
6948 // Target is not a function.
6949
John McCall9f54ad42009-12-10 09:41:52 +00006950 if (isa<TagDecl>(Target)) {
6951 // No conflict between a tag and a non-tag.
6952 if (!Tag) return false;
6953
John McCall41ce66f2009-12-10 19:51:03 +00006954 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006955 Diag(Target->getLocation(), diag::note_using_decl_target);
6956 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6957 return true;
6958 }
6959
6960 // No conflict between a tag and a non-tag.
6961 if (!NonTag) 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(NonTag->getLocation(), diag::note_using_decl_conflict);
6966 return true;
6967}
6968
John McCall9488ea12009-11-17 05:59:44 +00006969/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006970UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006971 UsingDecl *UD,
6972 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006973
6974 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006975 NamedDecl *Target = Orig;
6976 if (isa<UsingShadowDecl>(Target)) {
6977 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6978 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006979 }
6980
6981 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006982 = UsingShadowDecl::Create(Context, CurContext,
6983 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006984 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006985
6986 Shadow->setAccess(UD->getAccess());
6987 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6988 Shadow->setInvalidDecl();
6989
John McCall9488ea12009-11-17 05:59:44 +00006990 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006991 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006992 else
John McCall604e7f12009-12-08 07:46:18 +00006993 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006994
John McCall604e7f12009-12-08 07:46:18 +00006995
John McCall9f54ad42009-12-10 09:41:52 +00006996 return Shadow;
6997}
John McCall604e7f12009-12-08 07:46:18 +00006998
John McCall9f54ad42009-12-10 09:41:52 +00006999/// Hides a using shadow declaration. This is required by the current
7000/// using-decl implementation when a resolvable using declaration in a
7001/// class is followed by a declaration which would hide or override
7002/// one or more of the using decl's targets; for example:
7003///
7004/// struct Base { void foo(int); };
7005/// struct Derived : Base {
7006/// using Base::foo;
7007/// void foo(int);
7008/// };
7009///
7010/// The governing language is C++03 [namespace.udecl]p12:
7011///
7012/// When a using-declaration brings names from a base class into a
7013/// derived class scope, member functions in the derived class
7014/// override and/or hide member functions with the same name and
7015/// parameter types in a base class (rather than conflicting).
7016///
7017/// There are two ways to implement this:
7018/// (1) optimistically create shadow decls when they're not hidden
7019/// by existing declarations, or
7020/// (2) don't create any shadow decls (or at least don't make them
7021/// visible) until we've fully parsed/instantiated the class.
7022/// The problem with (1) is that we might have to retroactively remove
7023/// a shadow decl, which requires several O(n) operations because the
7024/// decl structures are (very reasonably) not designed for removal.
7025/// (2) avoids this but is very fiddly and phase-dependent.
7026void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00007027 if (Shadow->getDeclName().getNameKind() ==
7028 DeclarationName::CXXConversionFunctionName)
7029 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7030
John McCall9f54ad42009-12-10 09:41:52 +00007031 // Remove it from the DeclContext...
7032 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007033
John McCall9f54ad42009-12-10 09:41:52 +00007034 // ...and the scope, if applicable...
7035 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007036 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007037 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007038 }
7039
John McCall9f54ad42009-12-10 09:41:52 +00007040 // ...and the using decl.
7041 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7042
7043 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007044 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007045}
7046
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007047namespace {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007048class UsingValidatorCCC : public CorrectionCandidateCallback {
7049public:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007050 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation)
7051 : HasTypenameKeyword(HasTypenameKeyword),
7052 IsInstantiation(IsInstantiation) {}
7053
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007054 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7055 NamedDecl *ND = Candidate.getCorrectionDecl();
7056
7057 // Keywords are not valid here.
7058 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007059 return false;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007060
7061 // Completely unqualified names are invalid for a 'using' declaration.
7062 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7063 return false;
7064
7065 if (isa<TypeDecl>(ND))
7066 return HasTypenameKeyword || !IsInstantiation;
7067
7068 return !HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007069 }
7070
7071private:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007072 bool HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007073 bool IsInstantiation;
7074};
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007075} // end anonymous namespace
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007076
John McCall7ba107a2009-11-18 02:36:19 +00007077/// Builds a using declaration.
7078///
7079/// \param IsInstantiation - Whether this call arises from an
7080/// instantiation of an unresolved using declaration. We treat
7081/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007082NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7083 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007084 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007085 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007086 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007087 bool IsInstantiation,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007088 bool HasTypenameKeyword,
John McCall7ba107a2009-11-18 02:36:19 +00007089 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007090 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007091 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007092 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007093
Anders Carlsson550b14b2009-08-28 05:49:21 +00007094 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007095
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007096 if (SS.isEmpty()) {
7097 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007098 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007099 }
Mike Stump1eb44332009-09-09 15:08:12 +00007100
John McCall9f54ad42009-12-10 09:41:52 +00007101 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007102 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007103 ForRedeclaration);
7104 Previous.setHideTags(false);
7105 if (S) {
7106 LookupName(Previous, S);
7107
7108 // It is really dumb that we have to do this.
7109 LookupResult::Filter F = Previous.makeFilter();
7110 while (F.hasNext()) {
7111 NamedDecl *D = F.next();
7112 if (!isDeclInScope(D, CurContext, S))
7113 F.erase();
7114 }
7115 F.done();
7116 } else {
7117 assert(IsInstantiation && "no scope in non-instantiation");
7118 assert(CurContext->isRecord() && "scope not record in instantiation");
7119 LookupQualifiedName(Previous, CurContext);
7120 }
7121
John McCall9f54ad42009-12-10 09:41:52 +00007122 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007123 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7124 SS, IdentLoc, Previous))
John McCall9f54ad42009-12-10 09:41:52 +00007125 return 0;
7126
7127 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007128 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7129 return 0;
7130
John McCallaf8e6ed2009-11-12 03:15:40 +00007131 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007132 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007133 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007134 if (!LookupContext) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007135 if (HasTypenameKeyword) {
John McCalled976492009-12-04 22:46:56 +00007136 // FIXME: not all declaration name kinds are legal here
7137 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7138 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007139 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007140 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007141 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007142 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7143 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007144 }
John McCalled976492009-12-04 22:46:56 +00007145 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007146 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007147 NameInfo, HasTypenameKeyword);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007148 }
John McCalled976492009-12-04 22:46:56 +00007149 D->setAccess(AS);
7150 CurContext->addDecl(D);
7151
7152 if (!LookupContext) return D;
7153 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007154
John McCall77bb1aa2010-05-01 00:40:08 +00007155 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007156 UD->setInvalidDecl();
7157 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007158 }
7159
Richard Smithc5a89a12012-04-02 01:30:27 +00007160 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007161 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007162 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007163 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007164 return UD;
7165 }
7166
7167 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007168
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007169 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007170
John McCall604e7f12009-12-08 07:46:18 +00007171 // Unlike most lookups, we don't always want to hide tag
7172 // declarations: tag names are visible through the using declaration
7173 // even if hidden by ordinary names, *except* in a dependent context
7174 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007175 if (!IsInstantiation)
7176 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007177
John McCallb9abd8722012-04-07 03:04:20 +00007178 // For the purposes of this lookup, we have a base object type
7179 // equal to that of the current context.
7180 if (CurContext->isRecord()) {
7181 R.setBaseObjectType(
7182 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7183 }
7184
John McCalla24dc2e2009-11-17 02:14:36 +00007185 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007186
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007187 // Try to correct typos if possible.
John McCallf36e02d2009-10-09 21:13:30 +00007188 if (R.empty()) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007189 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation);
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007190 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7191 R.getLookupKind(), S, &SS, CCC)){
7192 // We reject any correction for which ND would be NULL.
7193 NamedDecl *ND = Corrected.getCorrectionDecl();
7194 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
7195 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
7196 R.setLookupName(Corrected.getCorrection());
7197 R.addDecl(ND);
7198 // We reject candidates where droppedSpecifier == true, hence the
7199 // literal '0' below.
7200 Diag(R.getNameLoc(), diag::err_no_member_suggest)
7201 << NameInfo.getName() << LookupContext << 0
7202 << CorrectedQuotedStr << SS.getRange()
7203 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
7204 CorrectedStr);
7205 Diag(ND->getLocation(), diag::note_previous_decl)
7206 << CorrectedQuotedStr;
7207 } else {
7208 Diag(IdentLoc, diag::err_no_member)
7209 << NameInfo.getName() << LookupContext << SS.getRange();
7210 UD->setInvalidDecl();
7211 return UD;
7212 }
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007213 }
7214
John McCalled976492009-12-04 22:46:56 +00007215 if (R.isAmbiguous()) {
7216 UD->setInvalidDecl();
7217 return UD;
7218 }
Mike Stump1eb44332009-09-09 15:08:12 +00007219
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007220 if (HasTypenameKeyword) {
John McCall7ba107a2009-11-18 02:36:19 +00007221 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007222 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007223 Diag(IdentLoc, diag::err_using_typename_non_type);
7224 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7225 Diag((*I)->getUnderlyingDecl()->getLocation(),
7226 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007227 UD->setInvalidDecl();
7228 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007229 }
7230 } else {
7231 // If we asked for a non-typename and we got a type, error out,
7232 // but only if this is an instantiation of an unresolved using
7233 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007234 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007235 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7236 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007237 UD->setInvalidDecl();
7238 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007239 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007240 }
7241
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007242 // C++0x N2914 [namespace.udecl]p6:
7243 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007244 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007245 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7246 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007247 UD->setInvalidDecl();
7248 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007249 }
Mike Stump1eb44332009-09-09 15:08:12 +00007250
John McCall9f54ad42009-12-10 09:41:52 +00007251 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7252 if (!CheckUsingShadowDecl(UD, *I, Previous))
7253 BuildUsingShadowDecl(S, UD, *I);
7254 }
John McCall9488ea12009-11-17 05:59:44 +00007255
7256 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007257}
7258
Sebastian Redlf677ea32011-02-05 19:23:19 +00007259/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007260bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007261 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007262
Douglas Gregordc355712011-02-25 00:36:19 +00007263 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007264 assert(SourceType &&
7265 "Using decl naming constructor doesn't have type in scope spec.");
7266 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7267
7268 // Check whether the named type is a direct base class.
7269 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7270 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7271 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7272 BaseIt != BaseE; ++BaseIt) {
7273 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7274 if (CanonicalSourceType == BaseType)
7275 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007276 if (BaseIt->getType()->isDependentType())
7277 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007278 }
7279
7280 if (BaseIt == BaseE) {
7281 // Did not find SourceType in the bases.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007282 Diag(UD->getUsingLoc(),
Sebastian Redlf677ea32011-02-05 19:23:19 +00007283 diag::err_using_decl_constructor_not_in_direct_base)
7284 << UD->getNameInfo().getSourceRange()
7285 << QualType(SourceType, 0) << TargetClass;
7286 return true;
7287 }
7288
Richard Smithc5a89a12012-04-02 01:30:27 +00007289 if (!CurContext->isDependentContext())
7290 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007291
7292 return false;
7293}
7294
John McCall9f54ad42009-12-10 09:41:52 +00007295/// Checks that the given using declaration is not an invalid
7296/// redeclaration. Note that this is checking only for the using decl
7297/// itself, not for any ill-formedness among the UsingShadowDecls.
7298bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007299 bool HasTypenameKeyword,
John McCall9f54ad42009-12-10 09:41:52 +00007300 const CXXScopeSpec &SS,
7301 SourceLocation NameLoc,
7302 const LookupResult &Prev) {
7303 // C++03 [namespace.udecl]p8:
7304 // C++0x [namespace.udecl]p10:
7305 // A using-declaration is a declaration and can therefore be used
7306 // repeatedly where (and only where) multiple declarations are
7307 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007308 //
John McCall8a726212010-11-29 18:01:58 +00007309 // That's in non-member contexts.
7310 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007311 return false;
7312
7313 NestedNameSpecifier *Qual
7314 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7315
7316 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7317 NamedDecl *D = *I;
7318
7319 bool DTypename;
7320 NestedNameSpecifier *DQual;
7321 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007322 DTypename = UD->hasTypename();
Douglas Gregordc355712011-02-25 00:36:19 +00007323 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007324 } else if (UnresolvedUsingValueDecl *UD
7325 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7326 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007327 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007328 } else if (UnresolvedUsingTypenameDecl *UD
7329 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7330 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007331 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007332 } else continue;
7333
7334 // using decls differ if one says 'typename' and the other doesn't.
7335 // FIXME: non-dependent using decls?
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007336 if (HasTypenameKeyword != DTypename) continue;
John McCall9f54ad42009-12-10 09:41:52 +00007337
7338 // using decls differ if they name different scopes (but note that
7339 // template instantiation can cause this check to trigger when it
7340 // didn't before instantiation).
7341 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7342 Context.getCanonicalNestedNameSpecifier(DQual))
7343 continue;
7344
7345 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007346 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007347 return true;
7348 }
7349
7350 return false;
7351}
7352
John McCall604e7f12009-12-08 07:46:18 +00007353
John McCalled976492009-12-04 22:46:56 +00007354/// Checks that the given nested-name qualifier used in a using decl
7355/// in the current context is appropriately related to the current
7356/// scope. If an error is found, diagnoses it and returns true.
7357bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7358 const CXXScopeSpec &SS,
7359 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007360 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007361
John McCall604e7f12009-12-08 07:46:18 +00007362 if (!CurContext->isRecord()) {
7363 // C++03 [namespace.udecl]p3:
7364 // C++0x [namespace.udecl]p8:
7365 // A using-declaration for a class member shall be a member-declaration.
7366
7367 // If we weren't able to compute a valid scope, it must be a
7368 // dependent class scope.
7369 if (!NamedContext || NamedContext->isRecord()) {
7370 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7371 << SS.getRange();
7372 return true;
7373 }
7374
7375 // Otherwise, everything is known to be fine.
7376 return false;
7377 }
7378
7379 // The current scope is a record.
7380
7381 // If the named context is dependent, we can't decide much.
7382 if (!NamedContext) {
7383 // FIXME: in C++0x, we can diagnose if we can prove that the
7384 // nested-name-specifier does not refer to a base class, which is
7385 // still possible in some cases.
7386
7387 // Otherwise we have to conservatively report that things might be
7388 // okay.
7389 return false;
7390 }
7391
7392 if (!NamedContext->isRecord()) {
7393 // Ideally this would point at the last name in the specifier,
7394 // but we don't have that level of source info.
7395 Diag(SS.getRange().getBegin(),
7396 diag::err_using_decl_nested_name_specifier_is_not_class)
7397 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7398 return true;
7399 }
7400
Douglas Gregor6fb07292010-12-21 07:41:49 +00007401 if (!NamedContext->isDependentContext() &&
7402 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7403 return true;
7404
Richard Smith80ad52f2013-01-02 11:42:31 +00007405 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007406 // C++0x [namespace.udecl]p3:
7407 // In a using-declaration used as a member-declaration, the
7408 // nested-name-specifier shall name a base class of the class
7409 // being defined.
7410
7411 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7412 cast<CXXRecordDecl>(NamedContext))) {
7413 if (CurContext == NamedContext) {
7414 Diag(NameLoc,
7415 diag::err_using_decl_nested_name_specifier_is_current_class)
7416 << SS.getRange();
7417 return true;
7418 }
7419
7420 Diag(SS.getRange().getBegin(),
7421 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7422 << (NestedNameSpecifier*) SS.getScopeRep()
7423 << cast<CXXRecordDecl>(CurContext)
7424 << SS.getRange();
7425 return true;
7426 }
7427
7428 return false;
7429 }
7430
7431 // C++03 [namespace.udecl]p4:
7432 // A using-declaration used as a member-declaration shall refer
7433 // to a member of a base class of the class being defined [etc.].
7434
7435 // Salient point: SS doesn't have to name a base class as long as
7436 // lookup only finds members from base classes. Therefore we can
7437 // diagnose here only if we can prove that that can't happen,
7438 // i.e. if the class hierarchies provably don't intersect.
7439
7440 // TODO: it would be nice if "definitely valid" results were cached
7441 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7442 // need to be repeated.
7443
7444 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007445 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007446
7447 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7448 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7449 Data->Bases.insert(Base);
7450 return true;
7451 }
7452
7453 bool hasDependentBases(const CXXRecordDecl *Class) {
7454 return !Class->forallBases(collect, this);
7455 }
7456
7457 /// Returns true if the base is dependent or is one of the
7458 /// accumulated base classes.
7459 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7460 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7461 return !Data->Bases.count(Base);
7462 }
7463
7464 bool mightShareBases(const CXXRecordDecl *Class) {
7465 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7466 }
7467 };
7468
7469 UserData Data;
7470
7471 // Returns false if we find a dependent base.
7472 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7473 return false;
7474
7475 // Returns false if the class has a dependent base or if it or one
7476 // of its bases is present in the base set of the current context.
7477 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7478 return false;
7479
7480 Diag(SS.getRange().getBegin(),
7481 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7482 << (NestedNameSpecifier*) SS.getScopeRep()
7483 << cast<CXXRecordDecl>(CurContext)
7484 << SS.getRange();
7485
7486 return true;
John McCalled976492009-12-04 22:46:56 +00007487}
7488
Richard Smith162e1c12011-04-15 14:24:37 +00007489Decl *Sema::ActOnAliasDeclaration(Scope *S,
7490 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007491 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007492 SourceLocation UsingLoc,
7493 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007494 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007495 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007496 // Skip up to the relevant declaration scope.
7497 while (S->getFlags() & Scope::TemplateParamScope)
7498 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007499 assert((S->getFlags() & Scope::DeclScope) &&
7500 "got alias-declaration outside of declaration scope");
7501
7502 if (Type.isInvalid())
7503 return 0;
7504
7505 bool Invalid = false;
7506 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7507 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007508 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007509
7510 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7511 return 0;
7512
7513 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007514 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007515 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007516 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7517 TInfo->getTypeLoc().getBeginLoc());
7518 }
Richard Smith162e1c12011-04-15 14:24:37 +00007519
7520 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7521 LookupName(Previous, S);
7522
7523 // Warn about shadowing the name of a template parameter.
7524 if (Previous.isSingleResult() &&
7525 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007526 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007527 Previous.clear();
7528 }
7529
7530 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7531 "name in alias declaration must be an identifier");
7532 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7533 Name.StartLocation,
7534 Name.Identifier, TInfo);
7535
7536 NewTD->setAccess(AS);
7537
7538 if (Invalid)
7539 NewTD->setInvalidDecl();
7540
Richard Smith6b3d3e52013-02-20 19:22:51 +00007541 ProcessDeclAttributeList(S, NewTD, AttrList);
7542
Richard Smith3e4c6c42011-05-05 21:57:07 +00007543 CheckTypedefForVariablyModifiedType(S, NewTD);
7544 Invalid |= NewTD->isInvalidDecl();
7545
Richard Smith162e1c12011-04-15 14:24:37 +00007546 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007547
7548 NamedDecl *NewND;
7549 if (TemplateParamLists.size()) {
7550 TypeAliasTemplateDecl *OldDecl = 0;
7551 TemplateParameterList *OldTemplateParams = 0;
7552
7553 if (TemplateParamLists.size() != 1) {
7554 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007555 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7556 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007557 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007558 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007559
7560 // Only consider previous declarations in the same scope.
7561 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7562 /*ExplicitInstantiationOrSpecialization*/false);
7563 if (!Previous.empty()) {
7564 Redeclaration = true;
7565
7566 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7567 if (!OldDecl && !Invalid) {
7568 Diag(UsingLoc, diag::err_redefinition_different_kind)
7569 << Name.Identifier;
7570
7571 NamedDecl *OldD = Previous.getRepresentativeDecl();
7572 if (OldD->getLocation().isValid())
7573 Diag(OldD->getLocation(), diag::note_previous_definition);
7574
7575 Invalid = true;
7576 }
7577
7578 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7579 if (TemplateParameterListsAreEqual(TemplateParams,
7580 OldDecl->getTemplateParameters(),
7581 /*Complain=*/true,
7582 TPL_TemplateMatch))
7583 OldTemplateParams = OldDecl->getTemplateParameters();
7584 else
7585 Invalid = true;
7586
7587 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7588 if (!Invalid &&
7589 !Context.hasSameType(OldTD->getUnderlyingType(),
7590 NewTD->getUnderlyingType())) {
7591 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7592 // but we can't reasonably accept it.
7593 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7594 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7595 if (OldTD->getLocation().isValid())
7596 Diag(OldTD->getLocation(), diag::note_previous_definition);
7597 Invalid = true;
7598 }
7599 }
7600 }
7601
7602 // Merge any previous default template arguments into our parameters,
7603 // and check the parameter list.
7604 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7605 TPC_TypeAliasTemplate))
7606 return 0;
7607
7608 TypeAliasTemplateDecl *NewDecl =
7609 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7610 Name.Identifier, TemplateParams,
7611 NewTD);
7612
7613 NewDecl->setAccess(AS);
7614
7615 if (Invalid)
7616 NewDecl->setInvalidDecl();
7617 else if (OldDecl)
7618 NewDecl->setPreviousDeclaration(OldDecl);
7619
7620 NewND = NewDecl;
7621 } else {
7622 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7623 NewND = NewTD;
7624 }
Richard Smith162e1c12011-04-15 14:24:37 +00007625
7626 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007627 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007628
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007629 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007630 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007631}
7632
John McCalld226f652010-08-21 09:40:31 +00007633Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007634 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007635 SourceLocation AliasLoc,
7636 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007637 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007638 SourceLocation IdentLoc,
7639 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007640
Anders Carlsson81c85c42009-03-28 23:53:49 +00007641 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007642 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7643 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007644
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007645 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007646 NamedDecl *PrevDecl
7647 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7648 ForRedeclaration);
7649 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7650 PrevDecl = 0;
7651
7652 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007653 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007654 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007655 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007656 // FIXME: At some point, we'll want to create the (redundant)
7657 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007658 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007659 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007660 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007661 }
Mike Stump1eb44332009-09-09 15:08:12 +00007662
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007663 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7664 diag::err_redefinition_different_kind;
7665 Diag(AliasLoc, DiagID) << Alias;
7666 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007667 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007668 }
7669
John McCalla24dc2e2009-11-17 02:14:36 +00007670 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007671 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007672
John McCallf36e02d2009-10-09 21:13:30 +00007673 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007674 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007675 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007676 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007677 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007678 }
Mike Stump1eb44332009-09-09 15:08:12 +00007679
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007680 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007681 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007682 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007683 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007684
John McCall3dbd3d52010-02-16 06:53:13 +00007685 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007686 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007687}
7688
Sean Hunt001cad92011-05-10 00:49:42 +00007689Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007690Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7691 CXXMethodDecl *MD) {
7692 CXXRecordDecl *ClassDecl = MD->getParent();
7693
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007694 // C++ [except.spec]p14:
7695 // An implicitly declared special member function (Clause 12) shall have an
7696 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007697 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007698 if (ClassDecl->isInvalidDecl())
7699 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007700
Sebastian Redl60618fa2011-03-12 11:50:43 +00007701 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007702 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7703 BEnd = ClassDecl->bases_end();
7704 B != BEnd; ++B) {
7705 if (B->isVirtual()) // Handled below.
7706 continue;
7707
Douglas Gregor18274032010-07-03 00:47:00 +00007708 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7709 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007710 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7711 // If this is a deleted function, add it anyway. This might be conformant
7712 // with the standard. This might not. I'm not sure. It might not matter.
7713 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007714 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007715 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007716 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007717
7718 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007719 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7720 BEnd = ClassDecl->vbases_end();
7721 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007722 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7723 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007724 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7725 // If this is a deleted function, add it anyway. This might be conformant
7726 // with the standard. This might not. I'm not sure. It might not matter.
7727 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007728 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007729 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007730 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007731
7732 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007733 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7734 FEnd = ClassDecl->field_end();
7735 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007736 if (F->hasInClassInitializer()) {
7737 if (Expr *E = F->getInClassInitializer())
7738 ExceptSpec.CalledExpr(E);
7739 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007740 // DR1351:
7741 // If the brace-or-equal-initializer of a non-static data member
7742 // invokes a defaulted default constructor of its class or of an
7743 // enclosing class in a potentially evaluated subexpression, the
7744 // program is ill-formed.
7745 //
7746 // This resolution is unworkable: the exception specification of the
7747 // default constructor can be needed in an unevaluated context, in
7748 // particular, in the operand of a noexcept-expression, and we can be
7749 // unable to compute an exception specification for an enclosed class.
7750 //
7751 // We do not allow an in-class initializer to require the evaluation
7752 // of the exception specification for any in-class initializer whose
7753 // definition is not lexically complete.
7754 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007755 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007756 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007757 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7758 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7759 // If this is a deleted function, add it anyway. This might be conformant
7760 // with the standard. This might not. I'm not sure. It might not matter.
7761 // In particular, the problem is that this function never gets called. It
7762 // might just be ill-formed because this function attempts to refer to
7763 // a deleted function here.
7764 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007765 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007766 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007767 }
John McCalle23cf432010-12-14 08:05:40 +00007768
Sean Hunt001cad92011-05-10 00:49:42 +00007769 return ExceptSpec;
7770}
7771
Richard Smith07b0fdc2013-03-18 21:12:30 +00007772Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007773Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7774 CXXRecordDecl *ClassDecl = CD->getParent();
7775
7776 // C++ [except.spec]p14:
7777 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007778 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007779 if (ClassDecl->isInvalidDecl())
7780 return ExceptSpec;
7781
7782 // Inherited constructor.
7783 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7784 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7785 // FIXME: Copying or moving the parameters could add extra exceptions to the
7786 // set, as could the default arguments for the inherited constructor. This
7787 // will be addressed when we implement the resolution of core issue 1351.
7788 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7789
7790 // Direct base-class constructors.
7791 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7792 BEnd = ClassDecl->bases_end();
7793 B != BEnd; ++B) {
7794 if (B->isVirtual()) // Handled below.
7795 continue;
7796
7797 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7798 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7799 if (BaseClassDecl == InheritedDecl)
7800 continue;
7801 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7802 if (Constructor)
7803 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7804 }
7805 }
7806
7807 // Virtual base-class constructors.
7808 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7809 BEnd = ClassDecl->vbases_end();
7810 B != BEnd; ++B) {
7811 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7812 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7813 if (BaseClassDecl == InheritedDecl)
7814 continue;
7815 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7816 if (Constructor)
7817 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7818 }
7819 }
7820
7821 // Field constructors.
7822 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7823 FEnd = ClassDecl->field_end();
7824 F != FEnd; ++F) {
7825 if (F->hasInClassInitializer()) {
7826 if (Expr *E = F->getInClassInitializer())
7827 ExceptSpec.CalledExpr(E);
7828 else if (!F->isInvalidDecl())
7829 Diag(CD->getLocation(),
7830 diag::err_in_class_initializer_references_def_ctor) << CD;
7831 } else if (const RecordType *RecordTy
7832 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7833 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7834 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7835 if (Constructor)
7836 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7837 }
7838 }
7839
Richard Smith07b0fdc2013-03-18 21:12:30 +00007840 return ExceptSpec;
7841}
7842
Richard Smithafb49182012-11-29 01:34:07 +00007843namespace {
7844/// RAII object to register a special member as being currently declared.
7845struct DeclaringSpecialMember {
7846 Sema &S;
7847 Sema::SpecialMemberDecl D;
7848 bool WasAlreadyBeingDeclared;
7849
7850 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7851 : S(S), D(RD, CSM) {
7852 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7853 if (WasAlreadyBeingDeclared)
7854 // This almost never happens, but if it does, ensure that our cache
7855 // doesn't contain a stale result.
7856 S.SpecialMemberCache.clear();
7857
7858 // FIXME: Register a note to be produced if we encounter an error while
7859 // declaring the special member.
7860 }
7861 ~DeclaringSpecialMember() {
7862 if (!WasAlreadyBeingDeclared)
7863 S.SpecialMembersBeingDeclared.erase(D);
7864 }
7865
7866 /// \brief Are we already trying to declare this special member?
7867 bool isAlreadyBeingDeclared() const {
7868 return WasAlreadyBeingDeclared;
7869 }
7870};
7871}
7872
Sean Hunt001cad92011-05-10 00:49:42 +00007873CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7874 CXXRecordDecl *ClassDecl) {
7875 // C++ [class.ctor]p5:
7876 // A default constructor for a class X is a constructor of class X
7877 // that can be called without an argument. If there is no
7878 // user-declared constructor for class X, a default constructor is
7879 // implicitly declared. An implicitly-declared default constructor
7880 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007881 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007882 "Should not build implicit default constructor!");
7883
Richard Smithafb49182012-11-29 01:34:07 +00007884 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7885 if (DSM.isAlreadyBeingDeclared())
7886 return 0;
7887
Richard Smith7756afa2012-06-10 05:43:50 +00007888 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7889 CXXDefaultConstructor,
7890 false);
7891
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007892 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007893 CanQualType ClassType
7894 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007895 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007896 DeclarationName Name
7897 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007898 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007899 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007900 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007901 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007902 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007903 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007904 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007905 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007906
7907 // Build an exception specification pointing back at this constructor.
7908 FunctionProtoType::ExtProtoInfo EPI;
7909 EPI.ExceptionSpecType = EST_Unevaluated;
7910 EPI.ExceptionSpecDecl = DefaultCon;
Dmitri Gribenko55431692013-05-05 00:41:58 +00007911 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007912
Richard Smithbc2a35d2012-12-08 08:32:28 +00007913 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7914 // constructors is easy to compute.
7915 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7916
7917 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007918 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007919
Douglas Gregor18274032010-07-03 00:47:00 +00007920 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007921 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007922
Douglas Gregor23c94db2010-07-02 17:43:08 +00007923 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007924 PushOnScopeChains(DefaultCon, S, false);
7925 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007926
Douglas Gregor32df23e2010-07-01 22:02:46 +00007927 return DefaultCon;
7928}
7929
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007930void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7931 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007932 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007933 !Constructor->doesThisDeclarationHaveABody() &&
7934 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007935 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007936
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007937 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007938 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007939
Eli Friedman9a14db32012-10-18 20:14:08 +00007940 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007941 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007942 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007943 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007944 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007945 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007946 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007947 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007948 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007949
7950 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007951 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007952
7953 Constructor->setUsed();
7954 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007955
7956 if (ASTMutationListener *L = getASTMutationListener()) {
7957 L->CompletedImplicitDefinition(Constructor);
7958 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007959}
7960
Richard Smith7a614d82011-06-11 17:19:42 +00007961void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007962 // Check that any explicitly-defaulted methods have exception specifications
7963 // compatible with their implicit exception specifications.
7964 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007965}
7966
Richard Smith4841ca52013-04-10 05:48:59 +00007967namespace {
7968/// Information on inheriting constructors to declare.
7969class InheritingConstructorInfo {
7970public:
7971 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7972 : SemaRef(SemaRef), Derived(Derived) {
7973 // Mark the constructors that we already have in the derived class.
7974 //
7975 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7976 // unless there is a user-declared constructor with the same signature in
7977 // the class where the using-declaration appears.
7978 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7979 }
7980
7981 void inheritAll(CXXRecordDecl *RD) {
7982 visitAll(RD, &InheritingConstructorInfo::inherit);
7983 }
7984
7985private:
7986 /// Information about an inheriting constructor.
7987 struct InheritingConstructor {
7988 InheritingConstructor()
7989 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7990
7991 /// If \c true, a constructor with this signature is already declared
7992 /// in the derived class.
7993 bool DeclaredInDerived;
7994
7995 /// The constructor which is inherited.
7996 const CXXConstructorDecl *BaseCtor;
7997
7998 /// The derived constructor we declared.
7999 CXXConstructorDecl *DerivedCtor;
8000 };
8001
8002 /// Inheriting constructors with a given canonical type. There can be at
8003 /// most one such non-template constructor, and any number of templated
8004 /// constructors.
8005 struct InheritingConstructorsForType {
8006 InheritingConstructor NonTemplate;
8007 llvm::SmallVector<
8008 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
8009
8010 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8011 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8012 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8013 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8014 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8015 false, S.TPL_TemplateMatch))
8016 return Templates[I].second;
8017 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8018 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008019 }
Richard Smith4841ca52013-04-10 05:48:59 +00008020
8021 return NonTemplate;
8022 }
8023 };
8024
8025 /// Get or create the inheriting constructor record for a constructor.
8026 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8027 QualType CtorType) {
8028 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8029 .getEntry(SemaRef, Ctor);
8030 }
8031
8032 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8033
8034 /// Process all constructors for a class.
8035 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8036 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8037 CtorE = RD->ctor_end();
8038 CtorIt != CtorE; ++CtorIt)
8039 (this->*Callback)(*CtorIt);
8040 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8041 I(RD->decls_begin()), E(RD->decls_end());
8042 I != E; ++I) {
8043 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8044 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8045 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008046 }
8047 }
Richard Smith4841ca52013-04-10 05:48:59 +00008048
8049 /// Note that a constructor (or constructor template) was declared in Derived.
8050 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8051 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8052 }
8053
8054 /// Inherit a single constructor.
8055 void inherit(const CXXConstructorDecl *Ctor) {
8056 const FunctionProtoType *CtorType =
8057 Ctor->getType()->castAs<FunctionProtoType>();
8058 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8059 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8060
8061 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8062
8063 // Core issue (no number yet): the ellipsis is always discarded.
8064 if (EPI.Variadic) {
8065 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8066 SemaRef.Diag(Ctor->getLocation(),
8067 diag::note_using_decl_constructor_ellipsis);
8068 EPI.Variadic = false;
8069 }
8070
8071 // Declare a constructor for each number of parameters.
8072 //
8073 // C++11 [class.inhctor]p1:
8074 // The candidate set of inherited constructors from the class X named in
8075 // the using-declaration consists of [... modulo defects ...] for each
8076 // constructor or constructor template of X, the set of constructors or
8077 // constructor templates that results from omitting any ellipsis parameter
8078 // specification and successively omitting parameters with a default
8079 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00008080 unsigned MinParams = minParamsToInherit(Ctor);
8081 unsigned Params = Ctor->getNumParams();
8082 if (Params >= MinParams) {
8083 do
8084 declareCtor(UsingLoc, Ctor,
8085 SemaRef.Context.getFunctionType(
8086 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8087 while (Params > MinParams &&
8088 Ctor->getParamDecl(--Params)->hasDefaultArg());
8089 }
Richard Smith4841ca52013-04-10 05:48:59 +00008090 }
8091
8092 /// Find the using-declaration which specified that we should inherit the
8093 /// constructors of \p Base.
8094 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8095 // No fancy lookup required; just look for the base constructor name
8096 // directly within the derived class.
8097 ASTContext &Context = SemaRef.Context;
8098 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8099 Context.getCanonicalType(Context.getRecordType(Base)));
8100 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8101 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8102 }
8103
8104 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8105 // C++11 [class.inhctor]p3:
8106 // [F]or each constructor template in the candidate set of inherited
8107 // constructors, a constructor template is implicitly declared
8108 if (Ctor->getDescribedFunctionTemplate())
8109 return 0;
8110
8111 // For each non-template constructor in the candidate set of inherited
8112 // constructors other than a constructor having no parameters or a
8113 // copy/move constructor having a single parameter, a constructor is
8114 // implicitly declared [...]
8115 if (Ctor->getNumParams() == 0)
8116 return 1;
8117 if (Ctor->isCopyOrMoveConstructor())
8118 return 2;
8119
8120 // Per discussion on core reflector, never inherit a constructor which
8121 // would become a default, copy, or move constructor of Derived either.
8122 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8123 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8124 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8125 }
8126
8127 /// Declare a single inheriting constructor, inheriting the specified
8128 /// constructor, with the given type.
8129 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8130 QualType DerivedType) {
8131 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8132
8133 // C++11 [class.inhctor]p3:
8134 // ... a constructor is implicitly declared with the same constructor
8135 // characteristics unless there is a user-declared constructor with
8136 // the same signature in the class where the using-declaration appears
8137 if (Entry.DeclaredInDerived)
8138 return;
8139
8140 // C++11 [class.inhctor]p7:
8141 // If two using-declarations declare inheriting constructors with the
8142 // same signature, the program is ill-formed
8143 if (Entry.DerivedCtor) {
8144 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8145 // Only diagnose this once per constructor.
8146 if (Entry.DerivedCtor->isInvalidDecl())
8147 return;
8148 Entry.DerivedCtor->setInvalidDecl();
8149
8150 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8151 SemaRef.Diag(BaseCtor->getLocation(),
8152 diag::note_using_decl_constructor_conflict_current_ctor);
8153 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8154 diag::note_using_decl_constructor_conflict_previous_ctor);
8155 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8156 diag::note_using_decl_constructor_conflict_previous_using);
8157 } else {
8158 // Core issue (no number): if the same inheriting constructor is
8159 // produced by multiple base class constructors from the same base
8160 // class, the inheriting constructor is defined as deleted.
8161 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8162 }
8163
8164 return;
8165 }
8166
8167 ASTContext &Context = SemaRef.Context;
8168 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8169 Context.getCanonicalType(Context.getRecordType(Derived)));
8170 DeclarationNameInfo NameInfo(Name, UsingLoc);
8171
8172 TemplateParameterList *TemplateParams = 0;
8173 if (const FunctionTemplateDecl *FTD =
8174 BaseCtor->getDescribedFunctionTemplate()) {
8175 TemplateParams = FTD->getTemplateParameters();
8176 // We're reusing template parameters from a different DeclContext. This
8177 // is questionable at best, but works out because the template depth in
8178 // both places is guaranteed to be 0.
8179 // FIXME: Rebuild the template parameters in the new context, and
8180 // transform the function type to refer to them.
8181 }
8182
8183 // Build type source info pointing at the using-declaration. This is
8184 // required by template instantiation.
8185 TypeSourceInfo *TInfo =
8186 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8187 FunctionProtoTypeLoc ProtoLoc =
8188 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8189
8190 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8191 Context, Derived, UsingLoc, NameInfo, DerivedType,
8192 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8193 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8194
8195 // Build an unevaluated exception specification for this constructor.
8196 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8197 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8198 EPI.ExceptionSpecType = EST_Unevaluated;
8199 EPI.ExceptionSpecDecl = DerivedCtor;
8200 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8201 FPT->getArgTypes(), EPI));
8202
8203 // Build the parameter declarations.
8204 SmallVector<ParmVarDecl *, 16> ParamDecls;
8205 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8206 TypeSourceInfo *TInfo =
8207 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8208 ParmVarDecl *PD = ParmVarDecl::Create(
8209 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8210 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8211 PD->setScopeInfo(0, I);
8212 PD->setImplicit();
8213 ParamDecls.push_back(PD);
8214 ProtoLoc.setArg(I, PD);
8215 }
8216
8217 // Set up the new constructor.
8218 DerivedCtor->setAccess(BaseCtor->getAccess());
8219 DerivedCtor->setParams(ParamDecls);
8220 DerivedCtor->setInheritedConstructor(BaseCtor);
8221 if (BaseCtor->isDeleted())
8222 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8223
8224 // If this is a constructor template, build the template declaration.
8225 if (TemplateParams) {
8226 FunctionTemplateDecl *DerivedTemplate =
8227 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8228 TemplateParams, DerivedCtor);
8229 DerivedTemplate->setAccess(BaseCtor->getAccess());
8230 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8231 Derived->addDecl(DerivedTemplate);
8232 } else {
8233 Derived->addDecl(DerivedCtor);
8234 }
8235
8236 Entry.BaseCtor = BaseCtor;
8237 Entry.DerivedCtor = DerivedCtor;
8238 }
8239
8240 Sema &SemaRef;
8241 CXXRecordDecl *Derived;
8242 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8243 MapType Map;
8244};
8245}
8246
8247void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8248 // Defer declaring the inheriting constructors until the class is
8249 // instantiated.
8250 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008251 return;
8252
Richard Smith4841ca52013-04-10 05:48:59 +00008253 // Find base classes from which we might inherit constructors.
8254 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8255 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8256 BaseE = ClassDecl->bases_end();
8257 BaseIt != BaseE; ++BaseIt)
8258 if (BaseIt->getInheritConstructors())
8259 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008260
Richard Smith4841ca52013-04-10 05:48:59 +00008261 // Go no further if we're not inheriting any constructors.
8262 if (InheritedBases.empty())
8263 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008264
Richard Smith4841ca52013-04-10 05:48:59 +00008265 // Declare the inherited constructors.
8266 InheritingConstructorInfo ICI(*this, ClassDecl);
8267 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8268 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008269}
8270
Richard Smith07b0fdc2013-03-18 21:12:30 +00008271void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8272 CXXConstructorDecl *Constructor) {
8273 CXXRecordDecl *ClassDecl = Constructor->getParent();
8274 assert(Constructor->getInheritedConstructor() &&
8275 !Constructor->doesThisDeclarationHaveABody() &&
8276 !Constructor->isDeleted());
8277
8278 SynthesizedFunctionScope Scope(*this, Constructor);
8279 DiagnosticErrorTrap Trap(Diags);
8280 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8281 Trap.hasErrorOccurred()) {
8282 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8283 << Context.getTagDeclType(ClassDecl);
8284 Constructor->setInvalidDecl();
8285 return;
8286 }
8287
8288 SourceLocation Loc = Constructor->getLocation();
8289 Constructor->setBody(new (Context) CompoundStmt(Loc));
8290
8291 Constructor->setUsed();
8292 MarkVTableUsed(CurrentLocation, ClassDecl);
8293
8294 if (ASTMutationListener *L = getASTMutationListener()) {
8295 L->CompletedImplicitDefinition(Constructor);
8296 }
8297}
8298
8299
Sean Huntcb45a0f2011-05-12 22:46:25 +00008300Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008301Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8302 CXXRecordDecl *ClassDecl = MD->getParent();
8303
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008304 // C++ [except.spec]p14:
8305 // An implicitly declared special member function (Clause 12) shall have
8306 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008307 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008308 if (ClassDecl->isInvalidDecl())
8309 return ExceptSpec;
8310
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008311 // Direct base-class destructors.
8312 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8313 BEnd = ClassDecl->bases_end();
8314 B != BEnd; ++B) {
8315 if (B->isVirtual()) // Handled below.
8316 continue;
8317
8318 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008319 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008320 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008321 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008322
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008323 // Virtual base-class destructors.
8324 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8325 BEnd = ClassDecl->vbases_end();
8326 B != BEnd; ++B) {
8327 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008328 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008329 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008330 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008331
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008332 // Field destructors.
8333 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8334 FEnd = ClassDecl->field_end();
8335 F != FEnd; ++F) {
8336 if (const RecordType *RecordTy
8337 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008338 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008339 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008340 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008341
Sean Huntcb45a0f2011-05-12 22:46:25 +00008342 return ExceptSpec;
8343}
8344
8345CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8346 // C++ [class.dtor]p2:
8347 // If a class has no user-declared destructor, a destructor is
8348 // declared implicitly. An implicitly-declared destructor is an
8349 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008350 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008351
Richard Smithafb49182012-11-29 01:34:07 +00008352 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8353 if (DSM.isAlreadyBeingDeclared())
8354 return 0;
8355
Douglas Gregor4923aa22010-07-02 20:37:36 +00008356 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008357 CanQualType ClassType
8358 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008359 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008360 DeclarationName Name
8361 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008362 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008363 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008364 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8365 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008366 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008367 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008368 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008369 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008370
8371 // Build an exception specification pointing back at this destructor.
8372 FunctionProtoType::ExtProtoInfo EPI;
8373 EPI.ExceptionSpecType = EST_Unevaluated;
8374 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008375 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008376
Richard Smithbc2a35d2012-12-08 08:32:28 +00008377 AddOverriddenMethods(ClassDecl, Destructor);
8378
8379 // We don't need to use SpecialMemberIsTrivial here; triviality for
8380 // destructors is easy to compute.
8381 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8382
8383 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008384 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008385
Douglas Gregor4923aa22010-07-02 20:37:36 +00008386 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008387 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008388
Douglas Gregor4923aa22010-07-02 20:37:36 +00008389 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008390 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008391 PushOnScopeChains(Destructor, S, false);
8392 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008393
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008394 return Destructor;
8395}
8396
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008397void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008398 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008399 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008400 !Destructor->doesThisDeclarationHaveABody() &&
8401 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008402 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008403 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008404 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008405
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008406 if (Destructor->isInvalidDecl())
8407 return;
8408
Eli Friedman9a14db32012-10-18 20:14:08 +00008409 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008410
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008411 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008412 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8413 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008414
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008415 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008416 Diag(CurrentLocation, diag::note_member_synthesized_at)
8417 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8418
8419 Destructor->setInvalidDecl();
8420 return;
8421 }
8422
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008423 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008424 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008425 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008426 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008427 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008428
8429 if (ASTMutationListener *L = getASTMutationListener()) {
8430 L->CompletedImplicitDefinition(Destructor);
8431 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008432}
8433
Richard Smitha4156b82012-04-21 18:42:51 +00008434/// \brief Perform any semantic analysis which needs to be delayed until all
8435/// pending class member declarations have been parsed.
8436void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008437 // If the context is an invalid C++ class, just suppress these checks.
8438 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8439 if (Record->isInvalidDecl()) {
8440 DelayedDestructorExceptionSpecChecks.clear();
8441 return;
8442 }
8443 }
8444
Richard Smitha4156b82012-04-21 18:42:51 +00008445 // Perform any deferred checking of exception specifications for virtual
8446 // destructors.
8447 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8448 i != e; ++i) {
8449 const CXXDestructorDecl *Dtor =
8450 DelayedDestructorExceptionSpecChecks[i].first;
8451 assert(!Dtor->getParent()->isDependentType() &&
8452 "Should not ever add destructors of templates into the list.");
8453 CheckOverridingFunctionExceptionSpec(Dtor,
8454 DelayedDestructorExceptionSpecChecks[i].second);
8455 }
8456 DelayedDestructorExceptionSpecChecks.clear();
8457}
8458
Richard Smithb9d0b762012-07-27 04:22:15 +00008459void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8460 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008461 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008462 "adjusting dtor exception specs was introduced in c++11");
8463
Sebastian Redl0ee33912011-05-19 05:13:44 +00008464 // C++11 [class.dtor]p3:
8465 // A declaration of a destructor that does not have an exception-
8466 // specification is implicitly considered to have the same exception-
8467 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008468 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008469 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008470 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008471 return;
8472
Chandler Carruth3f224b22011-09-20 04:55:26 +00008473 // Replace the destructor's type, building off the existing one. Fortunately,
8474 // the only thing of interest in the destructor type is its extended info.
8475 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008476 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8477 EPI.ExceptionSpecType = EST_Unevaluated;
8478 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008479 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008480
Sebastian Redl0ee33912011-05-19 05:13:44 +00008481 // FIXME: If the destructor has a body that could throw, and the newly created
8482 // spec doesn't allow exceptions, we should emit a warning, because this
8483 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008484 // However, we don't have a body or an exception specification yet, so it
8485 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008486}
8487
Richard Smith8c889532012-11-14 00:50:40 +00008488/// When generating a defaulted copy or move assignment operator, if a field
8489/// should be copied with __builtin_memcpy rather than via explicit assignments,
8490/// do so. This optimization only applies for arrays of scalars, and for arrays
8491/// of class type where the selected copy/move-assignment operator is trivial.
8492static StmtResult
8493buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8494 Expr *To, Expr *From) {
8495 // Compute the size of the memory buffer to be copied.
8496 QualType SizeType = S.Context.getSizeType();
8497 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8498 S.Context.getTypeSizeInChars(T).getQuantity());
8499
8500 // Take the address of the field references for "from" and "to". We
8501 // directly construct UnaryOperators here because semantic analysis
8502 // does not permit us to take the address of an xvalue.
8503 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8504 S.Context.getPointerType(From->getType()),
8505 VK_RValue, OK_Ordinary, Loc);
8506 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8507 S.Context.getPointerType(To->getType()),
8508 VK_RValue, OK_Ordinary, Loc);
8509
8510 const Type *E = T->getBaseElementTypeUnsafe();
8511 bool NeedsCollectableMemCpy =
8512 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8513
8514 // Create a reference to the __builtin_objc_memmove_collectable function
8515 StringRef MemCpyName = NeedsCollectableMemCpy ?
8516 "__builtin_objc_memmove_collectable" :
8517 "__builtin_memcpy";
8518 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8519 Sema::LookupOrdinaryName);
8520 S.LookupName(R, S.TUScope, true);
8521
8522 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8523 if (!MemCpy)
8524 // Something went horribly wrong earlier, and we will have complained
8525 // about it.
8526 return StmtError();
8527
8528 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8529 VK_RValue, Loc, 0);
8530 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8531
8532 Expr *CallArgs[] = {
8533 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8534 };
8535 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8536 Loc, CallArgs, Loc);
8537
8538 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8539 return S.Owned(Call.takeAs<Stmt>());
8540}
8541
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008542/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008543/// \c To.
8544///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008545/// This routine is used to copy/move the members of a class with an
8546/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008547/// copied are arrays, this routine builds for loops to copy them.
8548///
8549/// \param S The Sema object used for type-checking.
8550///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008551/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008552///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008553/// \param T The type of the expressions being copied/moved. Both expressions
8554/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008555///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008556/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008557///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008558/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008559///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008560/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008561/// Otherwise, it's a non-static member subobject.
8562///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008563/// \param Copying Whether we're copying or moving.
8564///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008565/// \param Depth Internal parameter recording the depth of the recursion.
8566///
Richard Smith8c889532012-11-14 00:50:40 +00008567/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8568/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008569static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008570buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8571 Expr *To, Expr *From,
8572 bool CopyingBaseSubobject, bool Copying,
8573 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008574 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008575 // Each subobject is assigned in the manner appropriate to its type:
8576 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008577 // - if the subobject is of class type, as if by a call to operator= with
8578 // the subobject as the object expression and the corresponding
8579 // subobject of x as a single function argument (as if by explicit
8580 // qualification; that is, ignoring any possible virtual overriding
8581 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008582 //
8583 // C++03 [class.copy]p13:
8584 // - if the subobject is of class type, the copy assignment operator for
8585 // the class is used (as if by explicit qualification; that is,
8586 // ignoring any possible virtual overriding functions in more derived
8587 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008588 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8589 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008590
Douglas Gregor06a9f362010-05-01 20:49:11 +00008591 // Look for operator=.
8592 DeclarationName Name
8593 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8594 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8595 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008596
Richard Smith044c8aa2012-11-13 00:54:12 +00008597 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8598 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008599 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008600 LookupResult::Filter F = OpLookup.makeFilter();
8601 while (F.hasNext()) {
8602 NamedDecl *D = F.next();
8603 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8604 if (Method->isCopyAssignmentOperator() ||
8605 (!Copying && Method->isMoveAssignmentOperator()))
8606 continue;
8607
8608 F.erase();
8609 }
8610 F.done();
John McCallb0207482010-03-16 06:11:48 +00008611 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008612
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008613 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008614 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008615 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008616 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008617 // ambiguities), we need to cast "this" to that subobject type; to
8618 // ensure that we don't go through the virtual call mechanism, we need
8619 // to qualify the operator= name with the base class (see below). However,
8620 // this means that if the base class has a protected copy assignment
8621 // operator, the protected member access check will fail. So, we
8622 // rewrite "protected" access to "public" access in this case, since we
8623 // know by construction that we're calling from a derived class.
8624 if (CopyingBaseSubobject) {
8625 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8626 L != LEnd; ++L) {
8627 if (L.getAccess() == AS_protected)
8628 L.setAccess(AS_public);
8629 }
8630 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008631
Douglas Gregor06a9f362010-05-01 20:49:11 +00008632 // Create the nested-name-specifier that will be used to qualify the
8633 // reference to operator=; this is required to suppress the virtual
8634 // call mechanism.
8635 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008636 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008637 SS.MakeTrivial(S.Context,
8638 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008639 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008640 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008641
Douglas Gregor06a9f362010-05-01 20:49:11 +00008642 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008643 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008644 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008645 /*TemplateKWLoc=*/SourceLocation(),
8646 /*FirstQualifierInScope=*/0,
8647 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008648 /*TemplateArgs=*/0,
8649 /*SuppressQualifierCheck=*/true);
8650 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008651 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008652
Douglas Gregor06a9f362010-05-01 20:49:11 +00008653 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008654
Richard Smith044c8aa2012-11-13 00:54:12 +00008655 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008656 OpEqualRef.takeAs<Expr>(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00008657 Loc, From, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008658 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008659 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008660
Richard Smith8c889532012-11-14 00:50:40 +00008661 // If we built a call to a trivial 'operator=' while copying an array,
8662 // bail out. We'll replace the whole shebang with a memcpy.
8663 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8664 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8665 return StmtResult((Stmt*)0);
8666
Richard Smith044c8aa2012-11-13 00:54:12 +00008667 // Convert to an expression-statement, and clean up any produced
8668 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008669 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008670 }
John McCallb0207482010-03-16 06:11:48 +00008671
Richard Smith044c8aa2012-11-13 00:54:12 +00008672 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008673 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008674 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008675 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008676 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008677 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008678 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008679 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008680 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008681
8682 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008683 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008684
Douglas Gregor06a9f362010-05-01 20:49:11 +00008685 // Construct a loop over the array bounds, e.g.,
8686 //
8687 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8688 //
8689 // that will copy each of the array elements.
8690 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008691
Douglas Gregor06a9f362010-05-01 20:49:11 +00008692 // Create the iteration variable.
8693 IdentifierInfo *IterationVarName = 0;
8694 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008695 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008696 llvm::raw_svector_ostream OS(Str);
8697 OS << "__i" << Depth;
8698 IterationVarName = &S.Context.Idents.get(OS.str());
8699 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008700 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008701 IterationVarName, SizeType,
8702 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008703 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008704
Douglas Gregor06a9f362010-05-01 20:49:11 +00008705 // Initialize the iteration variable to zero.
8706 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008707 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008708
8709 // Create a reference to the iteration variable; we'll use this several
8710 // times throughout.
8711 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008712 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008713 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008714 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8715 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8716
Douglas Gregor06a9f362010-05-01 20:49:11 +00008717 // Create the DeclStmt that holds the iteration variable.
8718 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008719
Douglas Gregor06a9f362010-05-01 20:49:11 +00008720 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008721 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008722 IterationVarRefRVal,
8723 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008724 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008725 IterationVarRefRVal,
8726 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008727 if (!Copying) // Cast to rvalue
8728 From = CastForMoving(S, From);
8729
8730 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008731 StmtResult Copy =
8732 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8733 To, From, CopyingBaseSubobject,
8734 Copying, Depth + 1);
8735 // Bail out if copying fails or if we determined that we should use memcpy.
8736 if (Copy.isInvalid() || !Copy.get())
8737 return Copy;
8738
8739 // Create the comparison against the array bound.
8740 llvm::APInt Upper
8741 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8742 Expr *Comparison
8743 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8744 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8745 BO_NE, S.Context.BoolTy,
8746 VK_RValue, OK_Ordinary, Loc, false);
8747
8748 // Create the pre-increment of the iteration variable.
8749 Expr *Increment
8750 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8751 VK_LValue, OK_Ordinary, Loc);
8752
Douglas Gregor06a9f362010-05-01 20:49:11 +00008753 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008754 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008755 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008756 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008757 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008758}
8759
Richard Smith8c889532012-11-14 00:50:40 +00008760static StmtResult
8761buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8762 Expr *To, Expr *From,
8763 bool CopyingBaseSubobject, bool Copying) {
8764 // Maybe we should use a memcpy?
8765 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8766 T.isTriviallyCopyableType(S.Context))
8767 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8768
8769 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8770 CopyingBaseSubobject,
8771 Copying, 0));
8772
8773 // If we ended up picking a trivial assignment operator for an array of a
8774 // non-trivially-copyable class type, just emit a memcpy.
8775 if (!Result.isInvalid() && !Result.get())
8776 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8777
8778 return Result;
8779}
8780
Richard Smithb9d0b762012-07-27 04:22:15 +00008781Sema::ImplicitExceptionSpecification
8782Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8783 CXXRecordDecl *ClassDecl = MD->getParent();
8784
8785 ImplicitExceptionSpecification ExceptSpec(*this);
8786 if (ClassDecl->isInvalidDecl())
8787 return ExceptSpec;
8788
8789 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8790 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8791 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8792
Douglas Gregorb87786f2010-07-01 17:48:08 +00008793 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008794 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008795 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008796
8797 // It is unspecified whether or not an implicit copy assignment operator
8798 // attempts to deduplicate calls to assignment operators of virtual bases are
8799 // made. As such, this exception specification is effectively unspecified.
8800 // Based on a similar decision made for constness in C++0x, we're erring on
8801 // the side of assuming such calls to be made regardless of whether they
8802 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008803 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8804 BaseEnd = ClassDecl->bases_end();
8805 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008806 if (Base->isVirtual())
8807 continue;
8808
Douglas Gregora376d102010-07-02 21:50:04 +00008809 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008810 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008811 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8812 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008813 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008814 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008815
8816 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8817 BaseEnd = ClassDecl->vbases_end();
8818 Base != BaseEnd; ++Base) {
8819 CXXRecordDecl *BaseClassDecl
8820 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8821 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8822 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008823 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008824 }
8825
Douglas Gregorb87786f2010-07-01 17:48:08 +00008826 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8827 FieldEnd = ClassDecl->field_end();
8828 Field != FieldEnd;
8829 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008830 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008831 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8832 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008833 LookupCopyingAssignment(FieldClassDecl,
8834 ArgQuals | FieldType.getCVRQualifiers(),
8835 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008836 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008837 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008838 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008839
Richard Smithb9d0b762012-07-27 04:22:15 +00008840 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008841}
8842
8843CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8844 // Note: The following rules are largely analoguous to the copy
8845 // constructor rules. Note that virtual bases are not taken into account
8846 // for determining the argument type of the operator. Note also that
8847 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008848 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008849
Richard Smithafb49182012-11-29 01:34:07 +00008850 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8851 if (DSM.isAlreadyBeingDeclared())
8852 return 0;
8853
Sean Hunt30de05c2011-05-14 05:23:20 +00008854 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8855 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00008856 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
8857 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00008858 ArgType = ArgType.withConst();
8859 ArgType = Context.getLValueReferenceType(ArgType);
8860
Richard Smitha8942d72013-05-07 03:19:20 +00008861 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8862 CXXCopyAssignment,
8863 Const);
8864
Douglas Gregord3c35902010-07-01 16:36:15 +00008865 // An implicitly-declared copy assignment operator is an inline public
8866 // member of its class.
8867 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008868 SourceLocation ClassLoc = ClassDecl->getLocation();
8869 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00008870 CXXMethodDecl *CopyAssignment =
8871 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8872 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
8873 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008874 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008875 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008876 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008877
8878 // Build an exception specification pointing back at this member.
8879 FunctionProtoType::ExtProtoInfo EPI;
8880 EPI.ExceptionSpecType = EST_Unevaluated;
8881 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008882 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008883
Douglas Gregord3c35902010-07-01 16:36:15 +00008884 // Add the parameter to the operator.
8885 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008886 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008887 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008888 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008889 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008890
Richard Smithbc2a35d2012-12-08 08:32:28 +00008891 AddOverriddenMethods(ClassDecl, CopyAssignment);
8892
8893 CopyAssignment->setTrivial(
8894 ClassDecl->needsOverloadResolutionForCopyAssignment()
8895 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8896 : ClassDecl->hasTrivialCopyAssignment());
8897
Richard Smitha8942d72013-05-07 03:19:20 +00008898 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00008899 // .... If the class definition does not explicitly declare a copy
8900 // assignment operator, there is no user-declared move constructor, and
8901 // there is no user-declared move assignment operator, a copy assignment
8902 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008903 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008904 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008905
Richard Smithbc2a35d2012-12-08 08:32:28 +00008906 // Note that we have added this copy-assignment operator.
8907 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8908
8909 if (Scope *S = getScopeForContext(ClassDecl))
8910 PushOnScopeChains(CopyAssignment, S, false);
8911 ClassDecl->addDecl(CopyAssignment);
8912
Douglas Gregord3c35902010-07-01 16:36:15 +00008913 return CopyAssignment;
8914}
8915
Richard Smith36155c12013-06-13 03:23:42 +00008916/// Diagnose an implicit copy operation for a class which is odr-used, but
8917/// which is deprecated because the class has a user-declared copy constructor,
8918/// copy assignment operator, or destructor.
8919static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
8920 SourceLocation UseLoc) {
8921 assert(CopyOp->isImplicit());
8922
8923 CXXRecordDecl *RD = CopyOp->getParent();
8924 CXXMethodDecl *UserDeclaredOperation = 0;
8925
8926 // In Microsoft mode, assignment operations don't affect constructors and
8927 // vice versa.
8928 if (RD->hasUserDeclaredDestructor()) {
8929 UserDeclaredOperation = RD->getDestructor();
8930 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
8931 RD->hasUserDeclaredCopyConstructor() &&
8932 !S.getLangOpts().MicrosoftMode) {
8933 // Find any user-declared copy constructor.
8934 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
8935 E = RD->ctor_end(); I != E; ++I) {
8936 if (I->isCopyConstructor()) {
8937 UserDeclaredOperation = *I;
8938 break;
8939 }
8940 }
8941 assert(UserDeclaredOperation);
8942 } else if (isa<CXXConstructorDecl>(CopyOp) &&
8943 RD->hasUserDeclaredCopyAssignment() &&
8944 !S.getLangOpts().MicrosoftMode) {
8945 // Find any user-declared move assignment operator.
8946 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
8947 E = RD->method_end(); I != E; ++I) {
8948 if (I->isCopyAssignmentOperator()) {
8949 UserDeclaredOperation = *I;
8950 break;
8951 }
8952 }
8953 assert(UserDeclaredOperation);
8954 }
8955
8956 if (UserDeclaredOperation) {
8957 S.Diag(UserDeclaredOperation->getLocation(),
8958 diag::warn_deprecated_copy_operation)
8959 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
8960 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
8961 S.Diag(UseLoc, diag::note_member_synthesized_at)
8962 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
8963 : Sema::CXXCopyAssignment)
8964 << RD;
8965 }
8966}
8967
Douglas Gregor06a9f362010-05-01 20:49:11 +00008968void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8969 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008970 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008971 CopyAssignOperator->isOverloadedOperator() &&
8972 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008973 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8974 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008975 "DefineImplicitCopyAssignment called for wrong function");
8976
8977 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8978
8979 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8980 CopyAssignOperator->setInvalidDecl();
8981 return;
8982 }
Richard Smith36155c12013-06-13 03:23:42 +00008983
8984 // C++11 [class.copy]p18:
8985 // The [definition of an implicitly declared copy assignment operator] is
8986 // deprecated if the class has a user-declared copy constructor or a
8987 // user-declared destructor.
8988 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
8989 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
8990
Douglas Gregor06a9f362010-05-01 20:49:11 +00008991 CopyAssignOperator->setUsed();
8992
Eli Friedman9a14db32012-10-18 20:14:08 +00008993 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008994 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008995
8996 // C++0x [class.copy]p30:
8997 // The implicitly-defined or explicitly-defaulted copy assignment operator
8998 // for a non-union class X performs memberwise copy assignment of its
8999 // subobjects. The direct base classes of X are assigned first, in the
9000 // order of their declaration in the base-specifier-list, and then the
9001 // immediate non-static data members of X are assigned, in the order in
9002 // which they were declared in the class definition.
9003
9004 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009005 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009006
9007 // The parameter for the "other" object, which we are copying from.
9008 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9009 Qualifiers OtherQuals = Other->getType().getQualifiers();
9010 QualType OtherRefType = Other->getType();
9011 if (const LValueReferenceType *OtherRef
9012 = OtherRefType->getAs<LValueReferenceType>()) {
9013 OtherRefType = OtherRef->getPointeeType();
9014 OtherQuals = OtherRefType.getQualifiers();
9015 }
9016
9017 // Our location for everything implicitly-generated.
9018 SourceLocation Loc = CopyAssignOperator->getLocation();
9019
9020 // Construct a reference to the "other" object. We'll be using this
9021 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00009022 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00009023 assert(OtherRef && "Reference to parameter cannot fail!");
9024
9025 // Construct the "this" pointer. We'll be using this throughout the generated
9026 // ASTs.
9027 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9028 assert(This && "Reference to this cannot fail!");
9029
9030 // Assign base classes.
9031 bool Invalid = false;
9032 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9033 E = ClassDecl->bases_end(); Base != E; ++Base) {
9034 // Form the assignment:
9035 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9036 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009037 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009038 Invalid = true;
9039 continue;
9040 }
9041
John McCallf871d0c2010-08-07 06:22:56 +00009042 CXXCastPath BasePath;
9043 BasePath.push_back(Base);
9044
Douglas Gregor06a9f362010-05-01 20:49:11 +00009045 // Construct the "from" expression, which is an implicit cast to the
9046 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00009047 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00009048 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
9049 CK_UncheckedDerivedToBase,
9050 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00009051
9052 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00009053 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009054
9055 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00009056 To = ImpCastExprToType(To.take(),
9057 Context.getCVRQualifiedType(BaseType,
9058 CopyAssignOperator->getTypeQualifiers()),
9059 CK_UncheckedDerivedToBase,
9060 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009061
9062 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00009063 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00009064 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009065 /*CopyingBaseSubobject=*/true,
9066 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009067 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009068 Diag(CurrentLocation, diag::note_member_synthesized_at)
9069 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9070 CopyAssignOperator->setInvalidDecl();
9071 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009072 }
9073
9074 // Success! Record the copy.
9075 Statements.push_back(Copy.takeAs<Expr>());
9076 }
9077
Douglas Gregor06a9f362010-05-01 20:49:11 +00009078 // Assign non-static members.
9079 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9080 FieldEnd = ClassDecl->field_end();
9081 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009082 if (Field->isUnnamedBitfield())
9083 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00009084
9085 if (Field->isInvalidDecl()) {
9086 Invalid = true;
9087 continue;
9088 }
9089
Douglas Gregor06a9f362010-05-01 20:49:11 +00009090 // Check for members of reference type; we can't copy those.
9091 if (Field->getType()->isReferenceType()) {
9092 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9093 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9094 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009095 Diag(CurrentLocation, diag::note_member_synthesized_at)
9096 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009097 Invalid = true;
9098 continue;
9099 }
9100
9101 // Check for members of const-qualified, non-class type.
9102 QualType BaseType = Context.getBaseElementType(Field->getType());
9103 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9104 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9105 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9106 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009107 Diag(CurrentLocation, diag::note_member_synthesized_at)
9108 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009109 Invalid = true;
9110 continue;
9111 }
John McCallb77115d2011-06-17 00:18:42 +00009112
9113 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009114 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9115 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009116
9117 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009118 if (FieldType->isIncompleteArrayType()) {
9119 assert(ClassDecl->hasFlexibleArrayMember() &&
9120 "Incomplete array type is not valid");
9121 continue;
9122 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009123
9124 // Build references to the field in the object we're copying from and to.
9125 CXXScopeSpec SS; // Intentionally empty
9126 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9127 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009128 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009129 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00009130 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00009131 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009132 SS, SourceLocation(), 0,
9133 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00009134 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00009135 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009136 SS, SourceLocation(), 0,
9137 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009138 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9139 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00009140
Douglas Gregor06a9f362010-05-01 20:49:11 +00009141 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009142 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009143 To.get(), From.get(),
9144 /*CopyingBaseSubobject=*/false,
9145 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009146 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009147 Diag(CurrentLocation, diag::note_member_synthesized_at)
9148 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9149 CopyAssignOperator->setInvalidDecl();
9150 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009151 }
9152
9153 // Success! Record the copy.
9154 Statements.push_back(Copy.takeAs<Stmt>());
9155 }
9156
9157 if (!Invalid) {
9158 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00009159 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009160
John McCall60d7b3a2010-08-24 06:29:42 +00009161 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009162 if (Return.isInvalid())
9163 Invalid = true;
9164 else {
9165 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009166
9167 if (Trap.hasErrorOccurred()) {
9168 Diag(CurrentLocation, diag::note_member_synthesized_at)
9169 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9170 Invalid = true;
9171 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009172 }
9173 }
9174
9175 if (Invalid) {
9176 CopyAssignOperator->setInvalidDecl();
9177 return;
9178 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009179
9180 StmtResult Body;
9181 {
9182 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009183 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009184 /*isStmtExpr=*/false);
9185 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9186 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009187 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009188
9189 if (ASTMutationListener *L = getASTMutationListener()) {
9190 L->CompletedImplicitDefinition(CopyAssignOperator);
9191 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009192}
9193
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009194Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009195Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9196 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009197
Richard Smithb9d0b762012-07-27 04:22:15 +00009198 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009199 if (ClassDecl->isInvalidDecl())
9200 return ExceptSpec;
9201
9202 // C++0x [except.spec]p14:
9203 // An implicitly declared special member function (Clause 12) shall have an
9204 // exception-specification. [...]
9205
9206 // It is unspecified whether or not an implicit move assignment operator
9207 // attempts to deduplicate calls to assignment operators of virtual bases are
9208 // made. As such, this exception specification is effectively unspecified.
9209 // Based on a similar decision made for constness in C++0x, we're erring on
9210 // the side of assuming such calls to be made regardless of whether they
9211 // actually happen.
9212 // Note that a move constructor is not implicitly declared when there are
9213 // virtual bases, but it can still be user-declared and explicitly defaulted.
9214 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9215 BaseEnd = ClassDecl->bases_end();
9216 Base != BaseEnd; ++Base) {
9217 if (Base->isVirtual())
9218 continue;
9219
9220 CXXRecordDecl *BaseClassDecl
9221 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9222 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009223 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009224 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009225 }
9226
9227 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9228 BaseEnd = ClassDecl->vbases_end();
9229 Base != BaseEnd; ++Base) {
9230 CXXRecordDecl *BaseClassDecl
9231 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9232 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009233 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009234 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009235 }
9236
9237 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9238 FieldEnd = ClassDecl->field_end();
9239 Field != FieldEnd;
9240 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009241 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009242 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009243 if (CXXMethodDecl *MoveAssign =
9244 LookupMovingAssignment(FieldClassDecl,
9245 FieldType.getCVRQualifiers(),
9246 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009247 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009248 }
9249 }
9250
9251 return ExceptSpec;
9252}
9253
Richard Smith1c931be2012-04-02 18:40:40 +00009254/// Determine whether the class type has any direct or indirect virtual base
9255/// classes which have a non-trivial move assignment operator.
9256static bool
9257hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9258 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9259 BaseEnd = ClassDecl->vbases_end();
9260 Base != BaseEnd; ++Base) {
9261 CXXRecordDecl *BaseClass =
9262 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9263
9264 // Try to declare the move assignment. If it would be deleted, then the
9265 // class does not have a non-trivial move assignment.
9266 if (BaseClass->needsImplicitMoveAssignment())
9267 S.DeclareImplicitMoveAssignment(BaseClass);
9268
Richard Smith426391c2012-11-16 00:53:38 +00009269 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009270 return true;
9271 }
9272
9273 return false;
9274}
9275
9276/// Determine whether the given type either has a move constructor or is
9277/// trivially copyable.
9278static bool
9279hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9280 Type = S.Context.getBaseElementType(Type);
9281
9282 // FIXME: Technically, non-trivially-copyable non-class types, such as
9283 // reference types, are supposed to return false here, but that appears
9284 // to be a standard defect.
9285 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009286 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009287 return true;
9288
9289 if (Type.isTriviallyCopyableType(S.Context))
9290 return true;
9291
9292 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009293 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9294 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009295 if (ClassDecl->needsImplicitMoveConstructor())
9296 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009297 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009298 }
9299
Richard Smithe5411b72012-12-01 02:35:44 +00009300 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9301 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009302 if (ClassDecl->needsImplicitMoveAssignment())
9303 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009304 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009305}
9306
9307/// Determine whether all non-static data members and direct or virtual bases
9308/// of class \p ClassDecl have either a move operation, or are trivially
9309/// copyable.
9310static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9311 bool IsConstructor) {
9312 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9313 BaseEnd = ClassDecl->bases_end();
9314 Base != BaseEnd; ++Base) {
9315 if (Base->isVirtual())
9316 continue;
9317
9318 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9319 return false;
9320 }
9321
9322 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9323 BaseEnd = ClassDecl->vbases_end();
9324 Base != BaseEnd; ++Base) {
9325 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9326 return false;
9327 }
9328
9329 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9330 FieldEnd = ClassDecl->field_end();
9331 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009332 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009333 return false;
9334 }
9335
9336 return true;
9337}
9338
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009339CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009340 // C++11 [class.copy]p20:
9341 // If the definition of a class X does not explicitly declare a move
9342 // assignment operator, one will be implicitly declared as defaulted
9343 // if and only if:
9344 //
9345 // - [first 4 bullets]
9346 assert(ClassDecl->needsImplicitMoveAssignment());
9347
Richard Smithafb49182012-11-29 01:34:07 +00009348 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9349 if (DSM.isAlreadyBeingDeclared())
9350 return 0;
9351
Richard Smith1c931be2012-04-02 18:40:40 +00009352 // [Checked after we build the declaration]
9353 // - the move assignment operator would not be implicitly defined as
9354 // deleted,
9355
9356 // [DR1402]:
9357 // - X has no direct or indirect virtual base class with a non-trivial
9358 // move assignment operator, and
9359 // - each of X's non-static data members and direct or virtual base classes
9360 // has a type that either has a move assignment operator or is trivially
9361 // copyable.
9362 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9363 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9364 ClassDecl->setFailedImplicitMoveAssignment();
9365 return 0;
9366 }
9367
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009368 // Note: The following rules are largely analoguous to the move
9369 // constructor rules.
9370
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009371 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9372 QualType RetType = Context.getLValueReferenceType(ArgType);
9373 ArgType = Context.getRValueReferenceType(ArgType);
9374
Richard Smitha8942d72013-05-07 03:19:20 +00009375 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9376 CXXMoveAssignment,
9377 false);
9378
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009379 // An implicitly-declared move assignment operator is an inline public
9380 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009381 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9382 SourceLocation ClassLoc = ClassDecl->getLocation();
9383 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009384 CXXMethodDecl *MoveAssignment =
9385 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9386 /*TInfo=*/0, /*StorageClass=*/SC_None,
9387 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009388 MoveAssignment->setAccess(AS_public);
9389 MoveAssignment->setDefaulted();
9390 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009391
Richard Smithb9d0b762012-07-27 04:22:15 +00009392 // Build an exception specification pointing back at this member.
9393 FunctionProtoType::ExtProtoInfo EPI;
9394 EPI.ExceptionSpecType = EST_Unevaluated;
9395 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009396 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009397
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009398 // Add the parameter to the operator.
9399 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9400 ClassLoc, ClassLoc, /*Id=*/0,
9401 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009402 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009403 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009404
Richard Smithbc2a35d2012-12-08 08:32:28 +00009405 AddOverriddenMethods(ClassDecl, MoveAssignment);
9406
9407 MoveAssignment->setTrivial(
9408 ClassDecl->needsOverloadResolutionForMoveAssignment()
9409 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9410 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009411
9412 // C++0x [class.copy]p9:
9413 // If the definition of a class X does not explicitly declare a move
9414 // assignment operator, one will be implicitly declared as defaulted if and
9415 // only if:
9416 // [...]
9417 // - the move assignment operator would not be implicitly defined as
9418 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009419 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009420 // Cache this result so that we don't try to generate this over and over
9421 // on every lookup, leaking memory and wasting time.
9422 ClassDecl->setFailedImplicitMoveAssignment();
9423 return 0;
9424 }
9425
Richard Smithbc2a35d2012-12-08 08:32:28 +00009426 // Note that we have added this copy-assignment operator.
9427 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9428
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009429 if (Scope *S = getScopeForContext(ClassDecl))
9430 PushOnScopeChains(MoveAssignment, S, false);
9431 ClassDecl->addDecl(MoveAssignment);
9432
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009433 return MoveAssignment;
9434}
9435
9436void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9437 CXXMethodDecl *MoveAssignOperator) {
9438 assert((MoveAssignOperator->isDefaulted() &&
9439 MoveAssignOperator->isOverloadedOperator() &&
9440 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009441 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9442 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009443 "DefineImplicitMoveAssignment called for wrong function");
9444
9445 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9446
9447 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9448 MoveAssignOperator->setInvalidDecl();
9449 return;
9450 }
9451
9452 MoveAssignOperator->setUsed();
9453
Eli Friedman9a14db32012-10-18 20:14:08 +00009454 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009455 DiagnosticErrorTrap Trap(Diags);
9456
9457 // C++0x [class.copy]p28:
9458 // The implicitly-defined or move assignment operator for a non-union class
9459 // X performs memberwise move assignment of its subobjects. The direct base
9460 // classes of X are assigned first, in the order of their declaration in the
9461 // base-specifier-list, and then the immediate non-static data members of X
9462 // are assigned, in the order in which they were declared in the class
9463 // definition.
9464
9465 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009466 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009467
9468 // The parameter for the "other" object, which we are move from.
9469 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9470 QualType OtherRefType = Other->getType()->
9471 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009472 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009473 "Bad argument type of defaulted move assignment");
9474
9475 // Our location for everything implicitly-generated.
9476 SourceLocation Loc = MoveAssignOperator->getLocation();
9477
9478 // Construct a reference to the "other" object. We'll be using this
9479 // throughout the generated ASTs.
9480 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9481 assert(OtherRef && "Reference to parameter cannot fail!");
9482 // Cast to rvalue.
9483 OtherRef = CastForMoving(*this, OtherRef);
9484
9485 // Construct the "this" pointer. We'll be using this throughout the generated
9486 // ASTs.
9487 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9488 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009489
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009490 // Assign base classes.
9491 bool Invalid = false;
9492 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9493 E = ClassDecl->bases_end(); Base != E; ++Base) {
9494 // Form the assignment:
9495 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9496 QualType BaseType = Base->getType().getUnqualifiedType();
9497 if (!BaseType->isRecordType()) {
9498 Invalid = true;
9499 continue;
9500 }
9501
9502 CXXCastPath BasePath;
9503 BasePath.push_back(Base);
9504
9505 // Construct the "from" expression, which is an implicit cast to the
9506 // appropriately-qualified base type.
9507 Expr *From = OtherRef;
9508 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009509 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009510
9511 // Dereference "this".
9512 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9513
9514 // Implicitly cast "this" to the appropriately-qualified base type.
9515 To = ImpCastExprToType(To.take(),
9516 Context.getCVRQualifiedType(BaseType,
9517 MoveAssignOperator->getTypeQualifiers()),
9518 CK_UncheckedDerivedToBase,
9519 VK_LValue, &BasePath);
9520
9521 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009522 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009523 To.get(), From,
9524 /*CopyingBaseSubobject=*/true,
9525 /*Copying=*/false);
9526 if (Move.isInvalid()) {
9527 Diag(CurrentLocation, diag::note_member_synthesized_at)
9528 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9529 MoveAssignOperator->setInvalidDecl();
9530 return;
9531 }
9532
9533 // Success! Record the move.
9534 Statements.push_back(Move.takeAs<Expr>());
9535 }
9536
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009537 // Assign non-static members.
9538 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9539 FieldEnd = ClassDecl->field_end();
9540 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009541 if (Field->isUnnamedBitfield())
9542 continue;
9543
Eli Friedman8150da32013-06-07 01:48:56 +00009544 if (Field->isInvalidDecl()) {
9545 Invalid = true;
9546 continue;
9547 }
9548
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009549 // Check for members of reference type; we can't move those.
9550 if (Field->getType()->isReferenceType()) {
9551 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9552 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9553 Diag(Field->getLocation(), diag::note_declared_at);
9554 Diag(CurrentLocation, diag::note_member_synthesized_at)
9555 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9556 Invalid = true;
9557 continue;
9558 }
9559
9560 // Check for members of const-qualified, non-class type.
9561 QualType BaseType = Context.getBaseElementType(Field->getType());
9562 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9563 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9564 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9565 Diag(Field->getLocation(), diag::note_declared_at);
9566 Diag(CurrentLocation, diag::note_member_synthesized_at)
9567 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9568 Invalid = true;
9569 continue;
9570 }
9571
9572 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009573 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9574 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009575
9576 QualType FieldType = Field->getType().getNonReferenceType();
9577 if (FieldType->isIncompleteArrayType()) {
9578 assert(ClassDecl->hasFlexibleArrayMember() &&
9579 "Incomplete array type is not valid");
9580 continue;
9581 }
9582
9583 // Build references to the field in the object we're copying from and to.
9584 CXXScopeSpec SS; // Intentionally empty
9585 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9586 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009587 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009588 MemberLookup.resolveKind();
9589 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9590 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009591 SS, SourceLocation(), 0,
9592 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009593 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9594 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009595 SS, SourceLocation(), 0,
9596 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009597 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9598 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9599
9600 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9601 "Member reference with rvalue base must be rvalue except for reference "
9602 "members, which aren't allowed for move assignment.");
9603
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009604 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009605 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009606 To.get(), From.get(),
9607 /*CopyingBaseSubobject=*/false,
9608 /*Copying=*/false);
9609 if (Move.isInvalid()) {
9610 Diag(CurrentLocation, diag::note_member_synthesized_at)
9611 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9612 MoveAssignOperator->setInvalidDecl();
9613 return;
9614 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009615
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009616 // Success! Record the copy.
9617 Statements.push_back(Move.takeAs<Stmt>());
9618 }
9619
9620 if (!Invalid) {
9621 // Add a "return *this;"
9622 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9623
9624 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9625 if (Return.isInvalid())
9626 Invalid = true;
9627 else {
9628 Statements.push_back(Return.takeAs<Stmt>());
9629
9630 if (Trap.hasErrorOccurred()) {
9631 Diag(CurrentLocation, diag::note_member_synthesized_at)
9632 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9633 Invalid = true;
9634 }
9635 }
9636 }
9637
9638 if (Invalid) {
9639 MoveAssignOperator->setInvalidDecl();
9640 return;
9641 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009642
9643 StmtResult Body;
9644 {
9645 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009646 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009647 /*isStmtExpr=*/false);
9648 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9649 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009650 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9651
9652 if (ASTMutationListener *L = getASTMutationListener()) {
9653 L->CompletedImplicitDefinition(MoveAssignOperator);
9654 }
9655}
9656
Richard Smithb9d0b762012-07-27 04:22:15 +00009657Sema::ImplicitExceptionSpecification
9658Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9659 CXXRecordDecl *ClassDecl = MD->getParent();
9660
9661 ImplicitExceptionSpecification ExceptSpec(*this);
9662 if (ClassDecl->isInvalidDecl())
9663 return ExceptSpec;
9664
9665 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9666 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9667 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9668
Douglas Gregor0d405db2010-07-01 20:59:04 +00009669 // C++ [except.spec]p14:
9670 // An implicitly declared special member function (Clause 12) shall have an
9671 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009672 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9673 BaseEnd = ClassDecl->bases_end();
9674 Base != BaseEnd;
9675 ++Base) {
9676 // Virtual bases are handled below.
9677 if (Base->isVirtual())
9678 continue;
9679
Douglas Gregor22584312010-07-02 23:41:54 +00009680 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009681 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009682 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009683 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009684 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009685 }
9686 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9687 BaseEnd = ClassDecl->vbases_end();
9688 Base != BaseEnd;
9689 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009690 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009691 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009692 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009693 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009694 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009695 }
9696 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9697 FieldEnd = ClassDecl->field_end();
9698 Field != FieldEnd;
9699 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009700 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009701 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9702 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009703 LookupCopyingConstructor(FieldClassDecl,
9704 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009705 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009706 }
9707 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009708
Richard Smithb9d0b762012-07-27 04:22:15 +00009709 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009710}
9711
9712CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9713 CXXRecordDecl *ClassDecl) {
9714 // C++ [class.copy]p4:
9715 // If the class definition does not explicitly declare a copy
9716 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009717 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009718
Richard Smithafb49182012-11-29 01:34:07 +00009719 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9720 if (DSM.isAlreadyBeingDeclared())
9721 return 0;
9722
Sean Hunt49634cf2011-05-13 06:10:58 +00009723 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9724 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009725 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009726 if (Const)
9727 ArgType = ArgType.withConst();
9728 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009729
Richard Smith7756afa2012-06-10 05:43:50 +00009730 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9731 CXXCopyConstructor,
9732 Const);
9733
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009734 DeclarationName Name
9735 = Context.DeclarationNames.getCXXConstructorName(
9736 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009737 SourceLocation ClassLoc = ClassDecl->getLocation();
9738 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009739
9740 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009741 // member of its class.
9742 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009743 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009744 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009745 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009746 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009747 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009748
Richard Smithb9d0b762012-07-27 04:22:15 +00009749 // Build an exception specification pointing back at this member.
9750 FunctionProtoType::ExtProtoInfo EPI;
9751 EPI.ExceptionSpecType = EST_Unevaluated;
9752 EPI.ExceptionSpecDecl = CopyConstructor;
9753 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009754 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009755
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009756 // Add the parameter to the constructor.
9757 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009758 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009759 /*IdentifierInfo=*/0,
9760 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009761 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009762 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009763
Richard Smithbc2a35d2012-12-08 08:32:28 +00009764 CopyConstructor->setTrivial(
9765 ClassDecl->needsOverloadResolutionForCopyConstructor()
9766 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9767 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009768
Nico Weberafcc96a2012-01-23 03:19:29 +00009769 // C++11 [class.copy]p8:
9770 // ... If the class definition does not explicitly declare a copy
9771 // constructor, there is no user-declared move constructor, and there is no
9772 // user-declared move assignment operator, a copy constructor is implicitly
9773 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009774 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009775 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009776
Richard Smithbc2a35d2012-12-08 08:32:28 +00009777 // Note that we have declared this constructor.
9778 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9779
9780 if (Scope *S = getScopeForContext(ClassDecl))
9781 PushOnScopeChains(CopyConstructor, S, false);
9782 ClassDecl->addDecl(CopyConstructor);
9783
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009784 return CopyConstructor;
9785}
9786
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009787void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009788 CXXConstructorDecl *CopyConstructor) {
9789 assert((CopyConstructor->isDefaulted() &&
9790 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009791 !CopyConstructor->doesThisDeclarationHaveABody() &&
9792 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009793 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009794
Anders Carlsson63010a72010-04-23 16:24:12 +00009795 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009796 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009797
Richard Smith36155c12013-06-13 03:23:42 +00009798 // C++11 [class.copy]p7:
9799 // The [definition of an implicitly declared copy constructro] is
9800 // deprecated if the class has a user-declared copy assignment operator
9801 // or a user-declared destructor.
9802 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
9803 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
9804
Eli Friedman9a14db32012-10-18 20:14:08 +00009805 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009806 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009807
David Blaikie93c86172013-01-17 05:26:25 +00009808 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009809 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009810 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009811 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009812 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009813 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009814 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009815 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9816 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009817 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009818 /*isStmtExpr=*/false)
9819 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009820 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009821 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009822
9823 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009824 if (ASTMutationListener *L = getASTMutationListener()) {
9825 L->CompletedImplicitDefinition(CopyConstructor);
9826 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009827}
9828
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009829Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009830Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9831 CXXRecordDecl *ClassDecl = MD->getParent();
9832
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009833 // C++ [except.spec]p14:
9834 // An implicitly declared special member function (Clause 12) shall have an
9835 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009836 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009837 if (ClassDecl->isInvalidDecl())
9838 return ExceptSpec;
9839
9840 // Direct base-class constructors.
9841 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9842 BEnd = ClassDecl->bases_end();
9843 B != BEnd; ++B) {
9844 if (B->isVirtual()) // Handled below.
9845 continue;
9846
9847 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9848 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009849 CXXConstructorDecl *Constructor =
9850 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009851 // If this is a deleted function, add it anyway. This might be conformant
9852 // with the standard. This might not. I'm not sure. It might not matter.
9853 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009854 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009855 }
9856 }
9857
9858 // Virtual base-class constructors.
9859 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9860 BEnd = ClassDecl->vbases_end();
9861 B != BEnd; ++B) {
9862 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9863 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009864 CXXConstructorDecl *Constructor =
9865 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009866 // If this is a deleted function, add it anyway. This might be conformant
9867 // with the standard. This might not. I'm not sure. It might not matter.
9868 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009869 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009870 }
9871 }
9872
9873 // Field constructors.
9874 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9875 FEnd = ClassDecl->field_end();
9876 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009877 QualType FieldType = Context.getBaseElementType(F->getType());
9878 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9879 CXXConstructorDecl *Constructor =
9880 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009881 // If this is a deleted function, add it anyway. This might be conformant
9882 // with the standard. This might not. I'm not sure. It might not matter.
9883 // In particular, the problem is that this function never gets called. It
9884 // might just be ill-formed because this function attempts to refer to
9885 // a deleted function here.
9886 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009887 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009888 }
9889 }
9890
9891 return ExceptSpec;
9892}
9893
9894CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9895 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009896 // C++11 [class.copy]p9:
9897 // If the definition of a class X does not explicitly declare a move
9898 // constructor, one will be implicitly declared as defaulted if and only if:
9899 //
9900 // - [first 4 bullets]
9901 assert(ClassDecl->needsImplicitMoveConstructor());
9902
Richard Smithafb49182012-11-29 01:34:07 +00009903 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9904 if (DSM.isAlreadyBeingDeclared())
9905 return 0;
9906
Richard Smith1c931be2012-04-02 18:40:40 +00009907 // [Checked after we build the declaration]
9908 // - the move assignment operator would not be implicitly defined as
9909 // deleted,
9910
9911 // [DR1402]:
9912 // - each of X's non-static data members and direct or virtual base classes
9913 // has a type that either has a move constructor or is trivially copyable.
9914 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9915 ClassDecl->setFailedImplicitMoveConstructor();
9916 return 0;
9917 }
9918
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009919 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9920 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009921
Richard Smith7756afa2012-06-10 05:43:50 +00009922 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9923 CXXMoveConstructor,
9924 false);
9925
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009926 DeclarationName Name
9927 = Context.DeclarationNames.getCXXConstructorName(
9928 Context.getCanonicalType(ClassType));
9929 SourceLocation ClassLoc = ClassDecl->getLocation();
9930 DeclarationNameInfo NameInfo(Name, ClassLoc);
9931
Richard Smitha8942d72013-05-07 03:19:20 +00009932 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009933 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009934 // member of its class.
9935 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009936 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009937 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009938 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009939 MoveConstructor->setAccess(AS_public);
9940 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009941
Richard Smithb9d0b762012-07-27 04:22:15 +00009942 // Build an exception specification pointing back at this member.
9943 FunctionProtoType::ExtProtoInfo EPI;
9944 EPI.ExceptionSpecType = EST_Unevaluated;
9945 EPI.ExceptionSpecDecl = MoveConstructor;
9946 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009947 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009948
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009949 // Add the parameter to the constructor.
9950 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9951 ClassLoc, ClassLoc,
9952 /*IdentifierInfo=*/0,
9953 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009954 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009955 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009956
Richard Smithbc2a35d2012-12-08 08:32:28 +00009957 MoveConstructor->setTrivial(
9958 ClassDecl->needsOverloadResolutionForMoveConstructor()
9959 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9960 : ClassDecl->hasTrivialMoveConstructor());
9961
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009962 // C++0x [class.copy]p9:
9963 // If the definition of a class X does not explicitly declare a move
9964 // constructor, one will be implicitly declared as defaulted if and only if:
9965 // [...]
9966 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009967 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009968 // Cache this result so that we don't try to generate this over and over
9969 // on every lookup, leaking memory and wasting time.
9970 ClassDecl->setFailedImplicitMoveConstructor();
9971 return 0;
9972 }
9973
9974 // Note that we have declared this constructor.
9975 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9976
9977 if (Scope *S = getScopeForContext(ClassDecl))
9978 PushOnScopeChains(MoveConstructor, S, false);
9979 ClassDecl->addDecl(MoveConstructor);
9980
9981 return MoveConstructor;
9982}
9983
9984void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9985 CXXConstructorDecl *MoveConstructor) {
9986 assert((MoveConstructor->isDefaulted() &&
9987 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009988 !MoveConstructor->doesThisDeclarationHaveABody() &&
9989 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009990 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9991
9992 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9993 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9994
Eli Friedman9a14db32012-10-18 20:14:08 +00009995 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009996 DiagnosticErrorTrap Trap(Diags);
9997
David Blaikie93c86172013-01-17 05:26:25 +00009998 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009999 Trap.hasErrorOccurred()) {
10000 Diag(CurrentLocation, diag::note_member_synthesized_at)
10001 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10002 MoveConstructor->setInvalidDecl();
10003 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010004 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010005 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
10006 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +000010007 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010008 /*isStmtExpr=*/false)
10009 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +000010010 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010011 }
10012
10013 MoveConstructor->setUsed();
10014
10015 if (ASTMutationListener *L = getASTMutationListener()) {
10016 L->CompletedImplicitDefinition(MoveConstructor);
10017 }
10018}
10019
Douglas Gregore4e68d42012-02-15 19:33:52 +000010020bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanc4ef9482013-07-18 23:29:14 +000010021 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010022}
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010023
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010024/// \brief Mark the call operator of the given lambda closure type as "used".
10025static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
10026 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +000010027 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +000010028 Lambda->lookup(
10029 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010030 CallOperator->setReferenced();
10031 CallOperator->setUsed();
10032}
10033
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010034void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10035 SourceLocation CurrentLocation,
10036 CXXConversionDecl *Conv)
10037{
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010038 CXXRecordDecl *Lambda = Conv->getParent();
10039
10040 // Make sure that the lambda call operator is marked used.
10041 markLambdaCallOperatorUsed(*this, Lambda);
10042
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010043 Conv->setUsed();
10044
Eli Friedman9a14db32012-10-18 20:14:08 +000010045 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010046 DiagnosticErrorTrap Trap(Diags);
10047
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010048 // Return the address of the __invoke function.
10049 DeclarationName InvokeName = &Context.Idents.get("__invoke");
10050 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +000010051 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010052 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
10053 VK_LValue, Conv->getLocation()).take();
10054 assert(FunctionRef && "Can't refer to __invoke function?");
10055 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +000010056 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010057 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010058 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010059
10060 // Fill in the __invoke function with a dummy implementation. IR generation
10061 // will fill in the actual details.
10062 Invoke->setUsed();
10063 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +000010064 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010065
10066 if (ASTMutationListener *L = getASTMutationListener()) {
10067 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010068 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010069 }
10070}
10071
10072void Sema::DefineImplicitLambdaToBlockPointerConversion(
10073 SourceLocation CurrentLocation,
10074 CXXConversionDecl *Conv)
10075{
10076 Conv->setUsed();
10077
Eli Friedman9a14db32012-10-18 20:14:08 +000010078 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010079 DiagnosticErrorTrap Trap(Diags);
10080
Douglas Gregorac1303e2012-02-22 05:02:47 +000010081 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010082 Expr *This = ActOnCXXThis(CurrentLocation).take();
10083 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010084
Eli Friedman23f02672012-03-01 04:01:32 +000010085 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10086 Conv->getLocation(),
10087 Conv, DerefThis);
10088
10089 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10090 // behavior. Note that only the general conversion function does this
10091 // (since it's unusable otherwise); in the case where we inline the
10092 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000010093 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000010094 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10095 CK_CopyAndAutoreleaseBlockObject,
10096 BuildBlock.get(), 0, VK_RValue);
10097
10098 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010099 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000010100 Conv->setInvalidDecl();
10101 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010102 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010103
Douglas Gregorac1303e2012-02-22 05:02:47 +000010104 // Create the return statement that returns the block from the conversion
10105 // function.
Eli Friedman23f02672012-03-01 04:01:32 +000010106 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010107 if (Return.isInvalid()) {
10108 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10109 Conv->setInvalidDecl();
10110 return;
10111 }
10112
10113 // Set the body of the conversion function.
10114 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010115 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010116 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010117 Conv->getLocation()));
10118
Douglas Gregorac1303e2012-02-22 05:02:47 +000010119 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010120 if (ASTMutationListener *L = getASTMutationListener()) {
10121 L->CompletedImplicitDefinition(Conv);
10122 }
10123}
10124
Douglas Gregorf52757d2012-03-10 06:53:13 +000010125/// \brief Determine whether the given list arguments contains exactly one
10126/// "real" (non-default) argument.
10127static bool hasOneRealArgument(MultiExprArg Args) {
10128 switch (Args.size()) {
10129 case 0:
10130 return false;
10131
10132 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010133 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010134 return false;
10135
10136 // fall through
10137 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010138 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010139 }
10140
10141 return false;
10142}
10143
John McCall60d7b3a2010-08-24 06:29:42 +000010144ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010145Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010146 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010147 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010148 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010149 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010150 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010151 unsigned ConstructKind,
10152 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010153 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010154
Douglas Gregor2f599792010-04-02 18:24:57 +000010155 // C++0x [class.copy]p34:
10156 // When certain criteria are met, an implementation is allowed to
10157 // omit the copy/move construction of a class object, even if the
10158 // copy/move constructor and/or destructor for the object have
10159 // side effects. [...]
10160 // - when a temporary class object that has not been bound to a
10161 // reference (12.2) would be copied/moved to a class object
10162 // with the same cv-unqualified type, the copy/move operation
10163 // can be omitted by constructing the temporary object
10164 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010165 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010166 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010167 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010168 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010169 }
Mike Stump1eb44332009-09-09 15:08:12 +000010170
10171 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010172 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010173 IsListInitialization, RequiresZeroInit,
10174 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010175}
10176
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010177/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10178/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010179ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010180Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10181 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010182 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010183 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010184 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010185 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010186 unsigned ConstructKind,
10187 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010188 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010189 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010190 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010191 HadMultipleCandidates,
10192 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010193 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10194 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010195}
10196
John McCall68c6c9a2010-02-02 09:10:11 +000010197void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010198 if (VD->isInvalidDecl()) return;
10199
John McCall68c6c9a2010-02-02 09:10:11 +000010200 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010201 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010202 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010203 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010204
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010205 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010206 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010207 CheckDestructorAccess(VD->getLocation(), Destructor,
10208 PDiag(diag::err_access_dtor_var)
10209 << VD->getDeclName()
10210 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010211 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010212
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010213 if (!VD->hasGlobalStorage()) return;
10214
10215 // Emit warning for non-trivial dtor in global scope (a real global,
10216 // class-static, function-static).
10217 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10218
10219 // TODO: this should be re-enabled for static locals by !CXAAtExit
10220 if (!VD->isStaticLocal())
10221 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010222}
10223
Douglas Gregor39da0b82009-09-09 23:08:42 +000010224/// \brief Given a constructor and the set of arguments provided for the
10225/// constructor, convert the arguments and add any required default arguments
10226/// to form a proper call to this constructor.
10227///
10228/// \returns true if an error occurred, false otherwise.
10229bool
10230Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10231 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010232 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010233 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010234 bool AllowExplicit,
10235 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010236 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10237 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010238 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010239
10240 const FunctionProtoType *Proto
10241 = Constructor->getType()->getAs<FunctionProtoType>();
10242 assert(Proto && "Constructor without a prototype?");
10243 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010244
10245 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010246 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010247 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010248 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010249 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010250
10251 VariadicCallType CallType =
10252 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010253 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010254 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010255 Proto, 0,
10256 llvm::makeArrayRef(Args, NumArgs),
10257 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010258 CallType, AllowExplicit,
10259 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010260 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010261
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010262 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010263
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010264 CheckConstructorCall(Constructor,
10265 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10266 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010267 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010268
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010269 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010270}
10271
Anders Carlsson20d45d22009-12-12 00:32:00 +000010272static inline bool
10273CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10274 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010275 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010276 if (isa<NamespaceDecl>(DC)) {
10277 return SemaRef.Diag(FnDecl->getLocation(),
10278 diag::err_operator_new_delete_declared_in_namespace)
10279 << FnDecl->getDeclName();
10280 }
10281
10282 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010283 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010284 return SemaRef.Diag(FnDecl->getLocation(),
10285 diag::err_operator_new_delete_declared_static)
10286 << FnDecl->getDeclName();
10287 }
10288
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010289 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010290}
10291
Anders Carlsson156c78e2009-12-13 17:53:43 +000010292static inline bool
10293CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10294 CanQualType ExpectedResultType,
10295 CanQualType ExpectedFirstParamType,
10296 unsigned DependentParamTypeDiag,
10297 unsigned InvalidParamTypeDiag) {
10298 QualType ResultType =
10299 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10300
10301 // Check that the result type is not dependent.
10302 if (ResultType->isDependentType())
10303 return SemaRef.Diag(FnDecl->getLocation(),
10304 diag::err_operator_new_delete_dependent_result_type)
10305 << FnDecl->getDeclName() << ExpectedResultType;
10306
10307 // Check that the result type is what we expect.
10308 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10309 return SemaRef.Diag(FnDecl->getLocation(),
10310 diag::err_operator_new_delete_invalid_result_type)
10311 << FnDecl->getDeclName() << ExpectedResultType;
10312
10313 // A function template must have at least 2 parameters.
10314 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10315 return SemaRef.Diag(FnDecl->getLocation(),
10316 diag::err_operator_new_delete_template_too_few_parameters)
10317 << FnDecl->getDeclName();
10318
10319 // The function decl must have at least 1 parameter.
10320 if (FnDecl->getNumParams() == 0)
10321 return SemaRef.Diag(FnDecl->getLocation(),
10322 diag::err_operator_new_delete_too_few_parameters)
10323 << FnDecl->getDeclName();
10324
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010325 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010326 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10327 if (FirstParamType->isDependentType())
10328 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10329 << FnDecl->getDeclName() << ExpectedFirstParamType;
10330
10331 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010332 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010333 ExpectedFirstParamType)
10334 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10335 << FnDecl->getDeclName() << ExpectedFirstParamType;
10336
10337 return false;
10338}
10339
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010340static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010341CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010342 // C++ [basic.stc.dynamic.allocation]p1:
10343 // A program is ill-formed if an allocation function is declared in a
10344 // namespace scope other than global scope or declared static in global
10345 // scope.
10346 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10347 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010348
10349 CanQualType SizeTy =
10350 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10351
10352 // C++ [basic.stc.dynamic.allocation]p1:
10353 // The return type shall be void*. The first parameter shall have type
10354 // std::size_t.
10355 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10356 SizeTy,
10357 diag::err_operator_new_dependent_param_type,
10358 diag::err_operator_new_param_type))
10359 return true;
10360
10361 // C++ [basic.stc.dynamic.allocation]p1:
10362 // The first parameter shall not have an associated default argument.
10363 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010364 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010365 diag::err_operator_new_default_arg)
10366 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10367
10368 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010369}
10370
10371static bool
Richard Smith444d3842012-10-20 08:26:51 +000010372CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010373 // C++ [basic.stc.dynamic.deallocation]p1:
10374 // A program is ill-formed if deallocation functions are declared in a
10375 // namespace scope other than global scope or declared static in global
10376 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010377 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10378 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010379
10380 // C++ [basic.stc.dynamic.deallocation]p2:
10381 // Each deallocation function shall return void and its first parameter
10382 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010383 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10384 SemaRef.Context.VoidPtrTy,
10385 diag::err_operator_delete_dependent_param_type,
10386 diag::err_operator_delete_param_type))
10387 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010388
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010389 return false;
10390}
10391
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010392/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10393/// of this overloaded operator is well-formed. If so, returns false;
10394/// otherwise, emits appropriate diagnostics and returns true.
10395bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010396 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010397 "Expected an overloaded operator declaration");
10398
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010399 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10400
Mike Stump1eb44332009-09-09 15:08:12 +000010401 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010402 // The allocation and deallocation functions, operator new,
10403 // operator new[], operator delete and operator delete[], are
10404 // described completely in 3.7.3. The attributes and restrictions
10405 // found in the rest of this subclause do not apply to them unless
10406 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010407 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010408 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010409
Anders Carlssona3ccda52009-12-12 00:26:23 +000010410 if (Op == OO_New || Op == OO_Array_New)
10411 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010412
10413 // C++ [over.oper]p6:
10414 // An operator function shall either be a non-static member
10415 // function or be a non-member function and have at least one
10416 // parameter whose type is a class, a reference to a class, an
10417 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010418 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10419 if (MethodDecl->isStatic())
10420 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010421 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010422 } else {
10423 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010424 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10425 ParamEnd = FnDecl->param_end();
10426 Param != ParamEnd; ++Param) {
10427 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010428 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10429 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010430 ClassOrEnumParam = true;
10431 break;
10432 }
10433 }
10434
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010435 if (!ClassOrEnumParam)
10436 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010437 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010438 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010439 }
10440
10441 // C++ [over.oper]p8:
10442 // An operator function cannot have default arguments (8.3.6),
10443 // except where explicitly stated below.
10444 //
Mike Stump1eb44332009-09-09 15:08:12 +000010445 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010446 // (C++ [over.call]p1).
10447 if (Op != OO_Call) {
10448 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10449 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010450 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010451 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010452 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010453 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010454 }
10455 }
10456
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010457 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10458 { false, false, false }
10459#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10460 , { Unary, Binary, MemberOnly }
10461#include "clang/Basic/OperatorKinds.def"
10462 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010463
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010464 bool CanBeUnaryOperator = OperatorUses[Op][0];
10465 bool CanBeBinaryOperator = OperatorUses[Op][1];
10466 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010467
10468 // C++ [over.oper]p8:
10469 // [...] Operator functions cannot have more or fewer parameters
10470 // than the number required for the corresponding operator, as
10471 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010472 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010473 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010474 if (Op != OO_Call &&
10475 ((NumParams == 1 && !CanBeUnaryOperator) ||
10476 (NumParams == 2 && !CanBeBinaryOperator) ||
10477 (NumParams < 1) || (NumParams > 2))) {
10478 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010479 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010480 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010481 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010482 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010483 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010484 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010485 assert(CanBeBinaryOperator &&
10486 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010487 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010488 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010489
Chris Lattner416e46f2008-11-21 07:57:12 +000010490 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010491 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010492 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010493
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010494 // Overloaded operators other than operator() cannot be variadic.
10495 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010496 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010497 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010498 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010499 }
10500
10501 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010502 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10503 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010504 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010505 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010506 }
10507
10508 // C++ [over.inc]p1:
10509 // The user-defined function called operator++ implements the
10510 // prefix and postfix ++ operator. If this function is a member
10511 // function with no parameters, or a non-member function with one
10512 // parameter of class or enumeration type, it defines the prefix
10513 // increment operator ++ for objects of that type. If the function
10514 // is a member function with one parameter (which shall be of type
10515 // int) or a non-member function with two parameters (the second
10516 // of which shall be of type int), it defines the postfix
10517 // increment operator ++ for objects of that type.
10518 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10519 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10520 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010521 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010522 ParamIsInt = BT->getKind() == BuiltinType::Int;
10523
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010524 if (!ParamIsInt)
10525 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010526 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010527 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010528 }
10529
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010530 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010531}
Chris Lattner5a003a42008-12-17 07:09:26 +000010532
Sean Hunta6c058d2010-01-13 09:01:02 +000010533/// CheckLiteralOperatorDeclaration - Check whether the declaration
10534/// of this literal operator function is well-formed. If so, returns
10535/// false; otherwise, emits appropriate diagnostics and returns true.
10536bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010537 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010538 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10539 << FnDecl->getDeclName();
10540 return true;
10541 }
10542
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010543 if (FnDecl->isExternC()) {
10544 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10545 return true;
10546 }
10547
Sean Hunta6c058d2010-01-13 09:01:02 +000010548 bool Valid = false;
10549
Richard Smith36f5cfe2012-03-09 08:00:36 +000010550 // This might be the definition of a literal operator template.
10551 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10552 // This might be a specialization of a literal operator template.
10553 if (!TpDecl)
10554 TpDecl = FnDecl->getPrimaryTemplate();
10555
Sean Hunt216c2782010-04-07 23:11:06 +000010556 // template <char...> type operator "" name() is the only valid template
10557 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010558 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010559 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010560 // Must have only one template parameter
10561 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10562 if (Params->size() == 1) {
10563 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010564 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010565
Sean Hunt216c2782010-04-07 23:11:06 +000010566 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010567 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10568 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10569 Valid = true;
10570 }
10571 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010572 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010573 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010574 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10575
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010576 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010577
Sean Hunt30019c02010-04-07 22:57:35 +000010578 // unsigned long long int, long double, and any character type are allowed
10579 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010580 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10581 Context.hasSameType(T, Context.LongDoubleTy) ||
10582 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010583 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010584 Context.hasSameType(T, Context.Char16Ty) ||
10585 Context.hasSameType(T, Context.Char32Ty)) {
10586 if (++Param == FnDecl->param_end())
10587 Valid = true;
10588 goto FinishedParams;
10589 }
10590
Sean Hunt30019c02010-04-07 22:57:35 +000010591 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010592 const PointerType *PT = T->getAs<PointerType>();
10593 if (!PT)
10594 goto FinishedParams;
10595 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010596 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010597 goto FinishedParams;
10598 T = T.getUnqualifiedType();
10599
10600 // Move on to the second parameter;
10601 ++Param;
10602
10603 // If there is no second parameter, the first must be a const char *
10604 if (Param == FnDecl->param_end()) {
10605 if (Context.hasSameType(T, Context.CharTy))
10606 Valid = true;
10607 goto FinishedParams;
10608 }
10609
10610 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10611 // are allowed as the first parameter to a two-parameter function
10612 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010613 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010614 Context.hasSameType(T, Context.Char16Ty) ||
10615 Context.hasSameType(T, Context.Char32Ty)))
10616 goto FinishedParams;
10617
10618 // The second and final parameter must be an std::size_t
10619 T = (*Param)->getType().getUnqualifiedType();
10620 if (Context.hasSameType(T, Context.getSizeType()) &&
10621 ++Param == FnDecl->param_end())
10622 Valid = true;
10623 }
10624
10625 // FIXME: This diagnostic is absolutely terrible.
10626FinishedParams:
10627 if (!Valid) {
10628 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10629 << FnDecl->getDeclName();
10630 return true;
10631 }
10632
Richard Smitha9e88b22012-03-09 08:16:22 +000010633 // A parameter-declaration-clause containing a default argument is not
10634 // equivalent to any of the permitted forms.
10635 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10636 ParamEnd = FnDecl->param_end();
10637 Param != ParamEnd; ++Param) {
10638 if ((*Param)->hasDefaultArg()) {
10639 Diag((*Param)->getDefaultArgRange().getBegin(),
10640 diag::err_literal_operator_default_argument)
10641 << (*Param)->getDefaultArgRange();
10642 break;
10643 }
10644 }
10645
Richard Smith2fb4ae32012-03-08 02:39:21 +000010646 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010647 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10648 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010649 // C++11 [usrlit.suffix]p1:
10650 // Literal suffix identifiers that do not start with an underscore
10651 // are reserved for future standardization.
Richard Smith4ac537b2013-07-23 08:14:48 +000010652 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10653 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor1155c422011-08-30 22:40:35 +000010654 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010655
Sean Hunta6c058d2010-01-13 09:01:02 +000010656 return false;
10657}
10658
Douglas Gregor074149e2009-01-05 19:45:36 +000010659/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10660/// linkage specification, including the language and (if present)
10661/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10662/// the location of the language string literal, which is provided
10663/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10664/// the '{' brace. Otherwise, this linkage specification does not
10665/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010666Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10667 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010668 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010669 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010670 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010671 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010672 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010673 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010674 Language = LinkageSpecDecl::lang_cxx;
10675 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010676 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010677 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010678 }
Mike Stump1eb44332009-09-09 15:08:12 +000010679
Chris Lattnercc98eac2008-12-17 07:13:27 +000010680 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010681
Douglas Gregor074149e2009-01-05 19:45:36 +000010682 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010683 ExternLoc, LangLoc, Language,
10684 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010685 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010686 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010687 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010688}
10689
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010690/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010691/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10692/// valid, it's the position of the closing '}' brace in a linkage
10693/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010694Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010695 Decl *LinkageSpec,
10696 SourceLocation RBraceLoc) {
10697 if (LinkageSpec) {
10698 if (RBraceLoc.isValid()) {
10699 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10700 LSDecl->setRBraceLoc(RBraceLoc);
10701 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010702 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010703 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010704 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010705}
10706
Michael Han684aa732013-02-22 17:15:32 +000010707Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10708 AttributeList *AttrList,
10709 SourceLocation SemiLoc) {
10710 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10711 // Attribute declarations appertain to empty declaration so we handle
10712 // them here.
10713 if (AttrList)
10714 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010715
Michael Han684aa732013-02-22 17:15:32 +000010716 CurContext->addDecl(ED);
10717 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010718}
10719
Douglas Gregord308e622009-05-18 20:51:54 +000010720/// \brief Perform semantic analysis for the variable declaration that
10721/// occurs within a C++ catch clause, returning the newly-created
10722/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010723VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010724 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010725 SourceLocation StartLoc,
10726 SourceLocation Loc,
10727 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010728 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010729 QualType ExDeclType = TInfo->getType();
10730
Sebastian Redl4b07b292008-12-22 19:15:10 +000010731 // Arrays and functions decay.
10732 if (ExDeclType->isArrayType())
10733 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10734 else if (ExDeclType->isFunctionType())
10735 ExDeclType = Context.getPointerType(ExDeclType);
10736
10737 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10738 // The exception-declaration shall not denote a pointer or reference to an
10739 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010740 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010741 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010742 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010743 Invalid = true;
10744 }
Douglas Gregord308e622009-05-18 20:51:54 +000010745
Sebastian Redl4b07b292008-12-22 19:15:10 +000010746 QualType BaseType = ExDeclType;
10747 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010748 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010749 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010750 BaseType = Ptr->getPointeeType();
10751 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010752 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010753 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010754 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010755 BaseType = Ref->getPointeeType();
10756 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010757 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010758 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010759 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010760 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010761 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010762
Mike Stump1eb44332009-09-09 15:08:12 +000010763 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010764 RequireNonAbstractType(Loc, ExDeclType,
10765 diag::err_abstract_type_in_decl,
10766 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010767 Invalid = true;
10768
John McCall5a180392010-07-24 00:37:23 +000010769 // Only the non-fragile NeXT runtime currently supports C++ catches
10770 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010771 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010772 QualType T = ExDeclType;
10773 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10774 T = RT->getPointeeType();
10775
10776 if (T->isObjCObjectType()) {
10777 Diag(Loc, diag::err_objc_object_catch);
10778 Invalid = true;
10779 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010780 // FIXME: should this be a test for macosx-fragile specifically?
10781 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010782 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010783 }
10784 }
10785
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010786 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010787 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010788 ExDecl->setExceptionVariable(true);
10789
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010790 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010791 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010792 Invalid = true;
10793
Douglas Gregorc41b8782011-07-06 18:14:43 +000010794 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010795 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010796 // Insulate this from anything else we might currently be parsing.
10797 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10798
Douglas Gregor6d182892010-03-05 23:38:39 +000010799 // C++ [except.handle]p16:
10800 // The object declared in an exception-declaration or, if the
10801 // exception-declaration does not specify a name, a temporary (12.2) is
10802 // copy-initialized (8.5) from the exception object. [...]
10803 // The object is destroyed when the handler exits, after the destruction
10804 // of any automatic objects initialized within the handler.
10805 //
10806 // We just pretend to initialize the object with itself, then make sure
10807 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010808 QualType initType = ExDeclType;
10809
10810 InitializedEntity entity =
10811 InitializedEntity::InitializeVariable(ExDecl);
10812 InitializationKind initKind =
10813 InitializationKind::CreateCopy(Loc, SourceLocation());
10814
10815 Expr *opaqueValue =
10816 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000010817 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10818 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000010819 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010820 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010821 else {
10822 // If the constructor used was non-trivial, set this as the
10823 // "initializer".
10824 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10825 if (!construct->getConstructor()->isTrivial()) {
10826 Expr *init = MaybeCreateExprWithCleanups(construct);
10827 ExDecl->setInit(init);
10828 }
10829
10830 // And make sure it's destructable.
10831 FinalizeVarWithDestructor(ExDecl, recordType);
10832 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010833 }
10834 }
10835
Douglas Gregord308e622009-05-18 20:51:54 +000010836 if (Invalid)
10837 ExDecl->setInvalidDecl();
10838
10839 return ExDecl;
10840}
10841
10842/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10843/// handler.
John McCalld226f652010-08-21 09:40:31 +000010844Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010845 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010846 bool Invalid = D.isInvalidType();
10847
10848 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010849 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10850 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010851 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10852 D.getIdentifierLoc());
10853 Invalid = true;
10854 }
10855
Sebastian Redl4b07b292008-12-22 19:15:10 +000010856 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010857 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010858 LookupOrdinaryName,
10859 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010860 // The scope should be freshly made just for us. There is just no way
10861 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010862 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010863 if (PrevDecl->isTemplateParameter()) {
10864 // Maybe we will complain about the shadowed template parameter.
10865 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010866 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010867 }
10868 }
10869
Chris Lattnereaaebc72009-04-25 08:06:05 +000010870 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010871 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10872 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010873 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010874 }
10875
Douglas Gregor83cb9422010-09-09 17:09:21 +000010876 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010877 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010878 D.getIdentifierLoc(),
10879 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010880 if (Invalid)
10881 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010882
Sebastian Redl4b07b292008-12-22 19:15:10 +000010883 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010884 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010885 PushOnScopeChains(ExDecl, S);
10886 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010887 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010888
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010889 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010890 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010891}
Anders Carlssonfb311762009-03-14 00:25:26 +000010892
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010893Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010894 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010895 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010896 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010897 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010898
Richard Smithe3f470a2012-07-11 22:37:56 +000010899 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10900 return 0;
10901
10902 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10903 AssertMessage, RParenLoc, false);
10904}
10905
10906Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10907 Expr *AssertExpr,
10908 StringLiteral *AssertMessage,
10909 SourceLocation RParenLoc,
10910 bool Failed) {
10911 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10912 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010913 // In a static_assert-declaration, the constant-expression shall be a
10914 // constant expression that can be contextually converted to bool.
10915 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10916 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010917 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010918
Richard Smithdaaefc52011-12-14 23:32:26 +000010919 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010920 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010921 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010922 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010923 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010924
Richard Smithe3f470a2012-07-11 22:37:56 +000010925 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010926 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010927 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010928 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010929 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010930 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010931 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010932 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010933 }
Mike Stump1eb44332009-09-09 15:08:12 +000010934
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010935 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010936 AssertExpr, AssertMessage, RParenLoc,
10937 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010938
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010939 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010940 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010941}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010942
Douglas Gregor1d869352010-04-07 16:53:43 +000010943/// \brief Perform semantic analysis of the given friend type declaration.
10944///
10945/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010946FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010947 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010948 TypeSourceInfo *TSInfo) {
10949 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10950
10951 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010952 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010953
Richard Smith6b130222011-10-18 21:39:00 +000010954 // C++03 [class.friend]p2:
10955 // An elaborated-type-specifier shall be used in a friend declaration
10956 // for a class.*
10957 //
10958 // * The class-key of the elaborated-type-specifier is required.
10959 if (!ActiveTemplateInstantiations.empty()) {
10960 // Do not complain about the form of friend template types during
10961 // template instantiation; we will already have complained when the
10962 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010963 } else {
10964 if (!T->isElaboratedTypeSpecifier()) {
10965 // If we evaluated the type to a record type, suggest putting
10966 // a tag in front.
10967 if (const RecordType *RT = T->getAs<RecordType>()) {
10968 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010969
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010970 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010971
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010972 Diag(TypeRange.getBegin(),
10973 getLangOpts().CPlusPlus11 ?
10974 diag::warn_cxx98_compat_unelaborated_friend_type :
10975 diag::ext_unelaborated_friend_type)
10976 << (unsigned) RD->getTagKind()
10977 << T
10978 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10979 InsertionText);
10980 } else {
10981 Diag(FriendLoc,
10982 getLangOpts().CPlusPlus11 ?
10983 diag::warn_cxx98_compat_nonclass_type_friend :
10984 diag::ext_nonclass_type_friend)
10985 << T
10986 << TypeRange;
10987 }
10988 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010989 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010990 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010991 diag::warn_cxx98_compat_enum_friend :
10992 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010993 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010994 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010995 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010996
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010997 // C++11 [class.friend]p3:
10998 // A friend declaration that does not declare a function shall have one
10999 // of the following forms:
11000 // friend elaborated-type-specifier ;
11001 // friend simple-type-specifier ;
11002 // friend typename-specifier ;
11003 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11004 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11005 }
Richard Smithd6f80da2012-09-20 01:31:00 +000011006
Douglas Gregor06245bf2010-04-07 17:57:12 +000011007 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000011008 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000011009 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000011010 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000011011}
11012
John McCall9a34edb2010-10-19 01:40:49 +000011013/// Handle a friend tag declaration where the scope specifier was
11014/// templated.
11015Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11016 unsigned TagSpec, SourceLocation TagLoc,
11017 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011018 IdentifierInfo *Name,
11019 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000011020 AttributeList *Attr,
11021 MultiTemplateParamsArg TempParamLists) {
11022 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11023
11024 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000011025 bool Invalid = false;
11026
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000011027 if (TemplateParameterList *TemplateParams =
11028 MatchTemplateParametersToScopeSpecifier(
11029 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11030 isExplicitSpecialization, Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000011031 if (TemplateParams->size() > 0) {
11032 // This is a declaration of a class template.
11033 if (Invalid)
11034 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000011035
Eric Christopher4110e132011-07-21 05:34:24 +000011036 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11037 SS, Name, NameLoc, Attr,
11038 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000011039 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000011040 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011041 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000011042 } else {
11043 // The "template<>" header is extraneous.
11044 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11045 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11046 isExplicitSpecialization = true;
11047 }
11048 }
11049
11050 if (Invalid) return 0;
11051
John McCall9a34edb2010-10-19 01:40:49 +000011052 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000011053 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011054 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000011055 isAllExplicitSpecializations = false;
11056 break;
11057 }
11058 }
11059
11060 // FIXME: don't ignore attributes.
11061
11062 // If it's explicit specializations all the way down, just forget
11063 // about the template header and build an appropriate non-templated
11064 // friend. TODO: for source fidelity, remember the headers.
11065 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011066 if (SS.isEmpty()) {
11067 bool Owned = false;
11068 bool IsDependent = false;
11069 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11070 Attr, AS_public,
11071 /*ModulePrivateLoc=*/SourceLocation(),
11072 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000011073 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011074 /*ScopedEnumUsesClassTag=*/false,
11075 /*UnderlyingType=*/TypeResult());
11076 }
11077
Douglas Gregor2494dd02011-03-01 01:34:45 +000011078 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000011079 ElaboratedTypeKeyword Keyword
11080 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011081 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000011082 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011083 if (T.isNull())
11084 return 0;
11085
11086 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11087 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000011088 DependentNameTypeLoc TL =
11089 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011090 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011091 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011092 TL.setNameLoc(NameLoc);
11093 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000011094 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011095 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000011096 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000011097 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011098 }
11099
11100 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011101 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011102 Friend->setAccess(AS_public);
11103 CurContext->addDecl(Friend);
11104 return Friend;
11105 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011106
11107 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11108
11109
John McCall9a34edb2010-10-19 01:40:49 +000011110
11111 // Handle the case of a templated-scope friend class. e.g.
11112 // template <class T> class A<T>::B;
11113 // FIXME: we don't support these right now.
11114 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11115 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11116 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011117 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011118 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011119 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011120 TL.setNameLoc(NameLoc);
11121
11122 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011123 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011124 Friend->setAccess(AS_public);
11125 Friend->setUnsupportedFriend(true);
11126 CurContext->addDecl(Friend);
11127 return Friend;
11128}
11129
11130
John McCalldd4a3b02009-09-16 22:47:08 +000011131/// Handle a friend type declaration. This works in tandem with
11132/// ActOnTag.
11133///
11134/// Notes on friend class templates:
11135///
11136/// We generally treat friend class declarations as if they were
11137/// declaring a class. So, for example, the elaborated type specifier
11138/// in a friend declaration is required to obey the restrictions of a
11139/// class-head (i.e. no typedefs in the scope chain), template
11140/// parameters are required to match up with simple template-ids, &c.
11141/// However, unlike when declaring a template specialization, it's
11142/// okay to refer to a template specialization without an empty
11143/// template parameter declaration, e.g.
11144/// friend class A<T>::B<unsigned>;
11145/// We permit this as a special case; if there are any template
11146/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011147/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011148Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011149 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011150 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011151
11152 assert(DS.isFriendSpecified());
11153 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11154
John McCalldd4a3b02009-09-16 22:47:08 +000011155 // Try to convert the decl specifier to a type. This works for
11156 // friend templates because ActOnTag never produces a ClassTemplateDecl
11157 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011158 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011159 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11160 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011161 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011162 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011163
Douglas Gregor6ccab972010-12-16 01:14:37 +000011164 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11165 return 0;
11166
John McCalldd4a3b02009-09-16 22:47:08 +000011167 // This is definitely an error in C++98. It's probably meant to
11168 // be forbidden in C++0x, too, but the specification is just
11169 // poorly written.
11170 //
11171 // The problem is with declarations like the following:
11172 // template <T> friend A<T>::foo;
11173 // where deciding whether a class C is a friend or not now hinges
11174 // on whether there exists an instantiation of A that causes
11175 // 'foo' to equal C. There are restrictions on class-heads
11176 // (which we declare (by fiat) elaborated friend declarations to
11177 // be) that makes this tractable.
11178 //
11179 // FIXME: handle "template <> friend class A<T>;", which
11180 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011181 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011182 Diag(Loc, diag::err_tagless_friend_type_template)
11183 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011184 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011185 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011186
John McCall02cace72009-08-28 07:59:38 +000011187 // C++98 [class.friend]p1: A friend of a class is a function
11188 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011189 // This is fixed in DR77, which just barely didn't make the C++03
11190 // deadline. It's also a very silly restriction that seriously
11191 // affects inner classes and which nobody else seems to implement;
11192 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011193 //
11194 // But note that we could warn about it: it's always useless to
11195 // friend one of your own members (it's not, however, worthless to
11196 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011197
John McCalldd4a3b02009-09-16 22:47:08 +000011198 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011199 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011200 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011201 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011202 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011203 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011204 DS.getFriendSpecLoc());
11205 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011206 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011207
11208 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011209 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011210
John McCalldd4a3b02009-09-16 22:47:08 +000011211 D->setAccess(AS_public);
11212 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011213
John McCalld226f652010-08-21 09:40:31 +000011214 return D;
John McCall02cace72009-08-28 07:59:38 +000011215}
11216
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011217NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11218 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011219 const DeclSpec &DS = D.getDeclSpec();
11220
11221 assert(DS.isFriendSpecified());
11222 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11223
11224 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011225 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011226
11227 // C++ [class.friend]p1
11228 // A friend of a class is a function or class....
11229 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011230 // It *doesn't* see through dependent types, which is correct
11231 // according to [temp.arg.type]p3:
11232 // If a declaration acquires a function type through a
11233 // type dependent on a template-parameter and this causes
11234 // a declaration that does not use the syntactic form of a
11235 // function declarator to have a function type, the program
11236 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011237 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011238 Diag(Loc, diag::err_unexpected_friend);
11239
11240 // It might be worthwhile to try to recover by creating an
11241 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011242 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011243 }
11244
11245 // C++ [namespace.memdef]p3
11246 // - If a friend declaration in a non-local class first declares a
11247 // class or function, the friend class or function is a member
11248 // of the innermost enclosing namespace.
11249 // - The name of the friend is not found by simple name lookup
11250 // until a matching declaration is provided in that namespace
11251 // scope (either before or after the class declaration granting
11252 // friendship).
11253 // - If a friend function is called, its name may be found by the
11254 // name lookup that considers functions from namespaces and
11255 // classes associated with the types of the function arguments.
11256 // - When looking for a prior declaration of a class or a function
11257 // declared as a friend, scopes outside the innermost enclosing
11258 // namespace scope are not considered.
11259
John McCall337ec3d2010-10-12 23:13:28 +000011260 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011261 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11262 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011263 assert(Name);
11264
Douglas Gregor6ccab972010-12-16 01:14:37 +000011265 // Check for unexpanded parameter packs.
11266 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11267 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11268 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11269 return 0;
11270
John McCall67d1a672009-08-06 02:15:43 +000011271 // The context we found the declaration in, or in which we should
11272 // create the declaration.
11273 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011274 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011275 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011276 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011277
John McCall337ec3d2010-10-12 23:13:28 +000011278 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000011279
John McCall337ec3d2010-10-12 23:13:28 +000011280 // There are four cases here.
11281 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000011282 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000011283 // there as appropriate.
11284 // Recover from invalid scope qualifiers as if they just weren't there.
11285 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000011286 // C++0x [namespace.memdef]p3:
11287 // If the name in a friend declaration is neither qualified nor
11288 // a template-id and the declaration is a function or an
11289 // elaborated-type-specifier, the lookup to determine whether
11290 // the entity has been previously declared shall not consider
11291 // any scopes outside the innermost enclosing namespace.
11292 // C++0x [class.friend]p11:
11293 // If a friend declaration appears in a local class and the name
11294 // specified is an unqualified name, a prior declaration is
11295 // looked up without considering scopes that are outside the
11296 // innermost enclosing non-class scope. For a friend function
11297 // declaration, if there is no prior declaration, the program is
11298 // ill-formed.
11299 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000011300 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011301
John McCall29ae6e52010-10-13 05:45:15 +000011302 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011303 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011304
Rafael Espindola11dc6342013-04-25 20:12:36 +000011305 // Skip class contexts. If someone can cite chapter and verse
11306 // for this behavior, that would be nice --- it's what GCC and
11307 // EDG do, and it seems like a reasonable intent, but the spec
11308 // really only says that checks for unqualified existing
11309 // declarations should stop at the nearest enclosing namespace,
11310 // not that they should only consider the nearest enclosing
11311 // namespace.
11312 while (DC->isRecord())
11313 DC = DC->getParent();
11314
11315 DeclContext *LookupDC = DC;
11316 while (LookupDC->isTransparentContext())
11317 LookupDC = LookupDC->getParent();
11318
11319 while (true) {
11320 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011321
11322 // TODO: decide what we think about using declarations.
Rafael Espindola11dc6342013-04-25 20:12:36 +000011323 if (isLocal)
John McCall67d1a672009-08-06 02:15:43 +000011324 break;
John McCall29ae6e52010-10-13 05:45:15 +000011325
Rafael Espindola11dc6342013-04-25 20:12:36 +000011326 if (!Previous.empty()) {
11327 DC = LookupDC;
11328 break;
John McCall8a407372010-10-14 22:22:28 +000011329 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011330
11331 if (isTemplateId) {
11332 if (isa<TranslationUnitDecl>(LookupDC)) break;
11333 } else {
11334 if (LookupDC->isFileContext()) break;
11335 }
11336 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011337 }
11338
John McCall380aaa42010-10-13 06:22:15 +000011339 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011340
Douglas Gregor883af832011-10-10 01:11:59 +000011341 // C++ [class.friend]p6:
11342 // A function can be defined in a friend declaration of a class if and
11343 // only if the class is a non-local class (9.8), the function name is
11344 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011345 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011346 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11347 }
11348
John McCall337ec3d2010-10-12 23:13:28 +000011349 // - There's a non-dependent scope specifier, in which case we
11350 // compute it and do a previous lookup there for a function
11351 // or function template.
11352 } else if (!SS.getScopeRep()->isDependent()) {
11353 DC = computeDeclContext(SS);
11354 if (!DC) return 0;
11355
11356 if (RequireCompleteDeclContext(SS, DC)) return 0;
11357
11358 LookupQualifiedName(Previous, DC);
11359
11360 // Ignore things found implicitly in the wrong scope.
11361 // TODO: better diagnostics for this case. Suggesting the right
11362 // qualified scope would be nice...
11363 LookupResult::Filter F = Previous.makeFilter();
11364 while (F.hasNext()) {
11365 NamedDecl *D = F.next();
11366 if (!DC->InEnclosingNamespaceSetOf(
11367 D->getDeclContext()->getRedeclContext()))
11368 F.erase();
11369 }
11370 F.done();
11371
11372 if (Previous.empty()) {
11373 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011374 Diag(Loc, diag::err_qualified_friend_not_found)
11375 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011376 return 0;
11377 }
11378
11379 // C++ [class.friend]p1: A friend of a class is a function or
11380 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011381 if (DC->Equals(CurContext))
11382 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011383 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011384 diag::warn_cxx98_compat_friend_is_member :
11385 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011386
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011387 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011388 // C++ [class.friend]p6:
11389 // A function can be defined in a friend declaration of a class if and
11390 // only if the class is a non-local class (9.8), the function name is
11391 // unqualified, and the function has namespace scope.
11392 SemaDiagnosticBuilder DB
11393 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11394
11395 DB << SS.getScopeRep();
11396 if (DC->isFileContext())
11397 DB << FixItHint::CreateRemoval(SS.getRange());
11398 SS.clear();
11399 }
John McCall337ec3d2010-10-12 23:13:28 +000011400
11401 // - There's a scope specifier that does not match any template
11402 // parameter lists, in which case we use some arbitrary context,
11403 // create a method or method template, and wait for instantiation.
11404 // - There's a scope specifier that does match some template
11405 // parameter lists, which we don't handle right now.
11406 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011407 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011408 // C++ [class.friend]p6:
11409 // A function can be defined in a friend declaration of a class if and
11410 // only if the class is a non-local class (9.8), the function name is
11411 // unqualified, and the function has namespace scope.
11412 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11413 << SS.getScopeRep();
11414 }
11415
John McCall337ec3d2010-10-12 23:13:28 +000011416 DC = CurContext;
11417 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011418 }
Douglas Gregor883af832011-10-10 01:11:59 +000011419
John McCall29ae6e52010-10-13 05:45:15 +000011420 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011421 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011422 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11423 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11424 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011425 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011426 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11427 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011428 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011429 }
John McCall67d1a672009-08-06 02:15:43 +000011430 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011431
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011432 // FIXME: This is an egregious hack to cope with cases where the scope stack
11433 // does not contain the declaration context, i.e., in an out-of-line
11434 // definition of a class.
11435 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11436 if (!DCScope) {
11437 FakeDCScope.setEntity(DC);
11438 DCScope = &FakeDCScope;
11439 }
11440
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011441 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011442 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011443 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011444 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011445
Douglas Gregor182ddf02009-09-28 00:08:27 +000011446 assert(ND->getDeclContext() == DC);
11447 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011448
John McCallab88d972009-08-31 22:39:49 +000011449 // Add the function declaration to the appropriate lookup tables,
11450 // adjusting the redeclarations list as necessary. We don't
11451 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011452 //
John McCallab88d972009-08-31 22:39:49 +000011453 // Also update the scope-based lookup if the target context's
11454 // lookup context is in lexical scope.
11455 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011456 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011457 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011458 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011459 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011460 }
John McCall02cace72009-08-28 07:59:38 +000011461
11462 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011463 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011464 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011465 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011466 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011467
John McCall1f2e1a92012-08-10 03:15:35 +000011468 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011469 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011470 } else {
11471 if (DC->isRecord()) CheckFriendAccess(ND);
11472
John McCall6102ca12010-10-16 06:59:13 +000011473 FunctionDecl *FD;
11474 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11475 FD = FTD->getTemplatedDecl();
11476 else
11477 FD = cast<FunctionDecl>(ND);
11478
David Majnemerf6a144f2013-06-25 23:09:30 +000011479 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11480 // default argument expression, that declaration shall be a definition
11481 // and shall be the only declaration of the function or function
11482 // template in the translation unit.
11483 if (functionDeclHasDefaultArgument(FD)) {
11484 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11485 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11486 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11487 } else if (!D.isFunctionDefinition())
11488 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11489 }
11490
John McCall6102ca12010-10-16 06:59:13 +000011491 // Mark templated-scope function declarations as unsupported.
11492 if (FD->getNumTemplateParameterLists())
11493 FrD->setUnsupportedFriend(true);
11494 }
John McCall337ec3d2010-10-12 23:13:28 +000011495
John McCalld226f652010-08-21 09:40:31 +000011496 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011497}
11498
John McCalld226f652010-08-21 09:40:31 +000011499void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11500 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011501
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011502 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011503 if (!Fn) {
11504 Diag(DelLoc, diag::err_deleted_non_function);
11505 return;
11506 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011507
Douglas Gregoref96ee02012-01-14 16:38:05 +000011508 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011509 // Don't consider the implicit declaration we generate for explicit
11510 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011511 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11512 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011513 Diag(DelLoc, diag::err_deleted_decl_not_first);
11514 Diag(Prev->getLocation(), diag::note_previous_declaration);
11515 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011516 // If the declaration wasn't the first, we delete the function anyway for
11517 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011518 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011519 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011520
11521 if (Fn->isDeleted())
11522 return;
11523
11524 // See if we're deleting a function which is already known to override a
11525 // non-deleted virtual function.
11526 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11527 bool IssuedDiagnostic = false;
11528 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11529 E = MD->end_overridden_methods();
11530 I != E; ++I) {
11531 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11532 if (!IssuedDiagnostic) {
11533 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11534 IssuedDiagnostic = true;
11535 }
11536 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11537 }
11538 }
11539 }
11540
Sean Hunt10620eb2011-05-06 20:44:56 +000011541 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011542}
Sebastian Redl13e88542009-04-27 21:33:24 +000011543
Sean Hunte4246a62011-05-12 06:15:49 +000011544void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011545 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011546
11547 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011548 if (MD->getParent()->isDependentType()) {
11549 MD->setDefaulted();
11550 MD->setExplicitlyDefaulted();
11551 return;
11552 }
11553
Sean Hunte4246a62011-05-12 06:15:49 +000011554 CXXSpecialMember Member = getSpecialMember(MD);
11555 if (Member == CXXInvalid) {
Eli Friedmanfcb5a252013-07-11 23:55:07 +000011556 if (!MD->isInvalidDecl())
11557 Diag(DefaultLoc, diag::err_default_special_members);
Sean Hunte4246a62011-05-12 06:15:49 +000011558 return;
11559 }
11560
11561 MD->setDefaulted();
11562 MD->setExplicitlyDefaulted();
11563
Sean Huntcd10dec2011-05-23 23:14:04 +000011564 // If this definition appears within the record, do the checking when
11565 // the record is complete.
11566 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011567 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011568 // Find the uninstantiated declaration that actually had the '= default'
11569 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011570 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011571
Richard Smith12fef492013-03-27 00:22:47 +000011572 // If the method was defaulted on its first declaration, we will have
11573 // already performed the checking in CheckCompletedCXXClass. Such a
11574 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011575 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011576 return;
11577
Richard Smithb9d0b762012-07-27 04:22:15 +000011578 CheckExplicitlyDefaultedSpecialMember(MD);
11579
Richard Smith1d28caf2012-12-11 01:14:52 +000011580 // The exception specification is needed because we are defining the
11581 // function.
11582 ResolveExceptionSpec(DefaultLoc,
11583 MD->getType()->castAs<FunctionProtoType>());
11584
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011585 if (MD->isInvalidDecl())
11586 return;
11587
Sean Hunte4246a62011-05-12 06:15:49 +000011588 switch (Member) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011589 case CXXDefaultConstructor:
11590 DefineImplicitDefaultConstructor(DefaultLoc,
11591 cast<CXXConstructorDecl>(MD));
Sean Hunt49634cf2011-05-13 06:10:58 +000011592 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011593 case CXXCopyConstructor:
11594 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunte4246a62011-05-12 06:15:49 +000011595 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011596 case CXXCopyAssignment:
11597 DefineImplicitCopyAssignment(DefaultLoc, MD);
Sean Hunt2b188082011-05-14 05:23:28 +000011598 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011599 case CXXDestructor:
11600 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Sean Huntcb45a0f2011-05-12 22:46:25 +000011601 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011602 case CXXMoveConstructor:
11603 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunt82713172011-05-25 23:16:36 +000011604 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011605 case CXXMoveAssignment:
11606 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011607 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011608 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011609 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011610 }
11611 } else {
11612 Diag(DefaultLoc, diag::err_default_special_members);
11613 }
11614}
11615
Sebastian Redl13e88542009-04-27 21:33:24 +000011616static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011617 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011618 Stmt *SubStmt = *CI;
11619 if (!SubStmt)
11620 continue;
11621 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011622 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011623 diag::err_return_in_constructor_handler);
11624 if (!isa<Expr>(SubStmt))
11625 SearchForReturnInStmt(Self, SubStmt);
11626 }
11627}
11628
11629void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11630 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11631 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11632 SearchForReturnInStmt(*this, Handler);
11633 }
11634}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011635
David Blaikie299adab2013-01-18 23:03:15 +000011636bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011637 const CXXMethodDecl *Old) {
11638 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11639 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11640
11641 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11642
11643 // If the calling conventions match, everything is fine
11644 if (NewCC == OldCC)
11645 return false;
11646
11647 // If either of the calling conventions are set to "default", we need to pick
11648 // something more sensible based on the target. This supports code where the
11649 // one method explicitly sets thiscall, and another has no explicit calling
11650 // convention.
11651 CallingConv Default =
11652 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11653 if (NewCC == CC_Default)
11654 NewCC = Default;
11655 if (OldCC == CC_Default)
11656 OldCC = Default;
11657
11658 // If the calling conventions still don't match, then report the error
11659 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011660 Diag(New->getLocation(),
11661 diag::err_conflicting_overriding_cc_attributes)
11662 << New->getDeclName() << New->getType() << Old->getType();
11663 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11664 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011665 }
11666
11667 return false;
11668}
11669
Mike Stump1eb44332009-09-09 15:08:12 +000011670bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011671 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011672 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11673 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011674
Chandler Carruth73857792010-02-15 11:53:20 +000011675 if (Context.hasSameType(NewTy, OldTy) ||
11676 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011677 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011678
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011679 // Check if the return types are covariant
11680 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011681
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011682 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011683 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11684 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011685 NewClassTy = NewPT->getPointeeType();
11686 OldClassTy = OldPT->getPointeeType();
11687 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011688 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11689 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11690 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11691 NewClassTy = NewRT->getPointeeType();
11692 OldClassTy = OldRT->getPointeeType();
11693 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011694 }
11695 }
Mike Stump1eb44332009-09-09 15:08:12 +000011696
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011697 // The return types aren't either both pointers or references to a class type.
11698 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011699 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011700 diag::err_different_return_type_for_overriding_virtual_function)
11701 << New->getDeclName() << NewTy << OldTy;
11702 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011703
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011704 return true;
11705 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011706
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011707 // C++ [class.virtual]p6:
11708 // If the return type of D::f differs from the return type of B::f, the
11709 // class type in the return type of D::f shall be complete at the point of
11710 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011711 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11712 if (!RT->isBeingDefined() &&
11713 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011714 diag::err_covariant_return_incomplete,
11715 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011716 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011717 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011718
Douglas Gregora4923eb2009-11-16 21:35:15 +000011719 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011720 // Check if the new class derives from the old class.
11721 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11722 Diag(New->getLocation(),
11723 diag::err_covariant_return_not_derived)
11724 << New->getDeclName() << NewTy << OldTy;
11725 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11726 return true;
11727 }
Mike Stump1eb44332009-09-09 15:08:12 +000011728
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011729 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011730 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011731 diag::err_covariant_return_inaccessible_base,
11732 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11733 // FIXME: Should this point to the return type?
11734 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011735 // FIXME: this note won't trigger for delayed access control
11736 // diagnostics, and it's impossible to get an undelayed error
11737 // here from access control during the original parse because
11738 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011739 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11740 return true;
11741 }
11742 }
Mike Stump1eb44332009-09-09 15:08:12 +000011743
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011744 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011745 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011746 Diag(New->getLocation(),
11747 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011748 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011749 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11750 return true;
11751 };
Mike Stump1eb44332009-09-09 15:08:12 +000011752
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011753
11754 // The new class type must have the same or less qualifiers as the old type.
11755 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11756 Diag(New->getLocation(),
11757 diag::err_covariant_return_type_class_type_more_qualified)
11758 << New->getDeclName() << NewTy << OldTy;
11759 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11760 return true;
11761 };
Mike Stump1eb44332009-09-09 15:08:12 +000011762
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011763 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011764}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011765
Douglas Gregor4ba31362009-12-01 17:24:26 +000011766/// \brief Mark the given method pure.
11767///
11768/// \param Method the method to be marked pure.
11769///
11770/// \param InitRange the source range that covers the "0" initializer.
11771bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011772 SourceLocation EndLoc = InitRange.getEnd();
11773 if (EndLoc.isValid())
11774 Method->setRangeEnd(EndLoc);
11775
Douglas Gregor4ba31362009-12-01 17:24:26 +000011776 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11777 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011778 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011779 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011780
11781 if (!Method->isInvalidDecl())
11782 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11783 << Method->getDeclName() << InitRange;
11784 return true;
11785}
11786
Douglas Gregor552e2992012-02-21 02:22:07 +000011787/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011788static bool isStaticDataMember(const Decl *D) {
11789 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
11790 return Var->isStaticDataMember();
11791
11792 return false;
Douglas Gregor552e2992012-02-21 02:22:07 +000011793}
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011794
John McCall731ad842009-12-19 09:28:58 +000011795/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11796/// an initializer for the out-of-line declaration 'Dcl'. The scope
11797/// is a fresh scope pushed for just this purpose.
11798///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011799/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11800/// static data member of class X, names should be looked up in the scope of
11801/// class X.
John McCalld226f652010-08-21 09:40:31 +000011802void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011803 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011804 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011805
John McCall731ad842009-12-19 09:28:58 +000011806 // We should only get called for declarations with scope specifiers, like:
11807 // int foo::bar;
11808 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011809 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011810
11811 // If we are parsing the initializer for a static data member, push a
11812 // new expression evaluation context that is associated with this static
11813 // data member.
11814 if (isStaticDataMember(D))
11815 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011816}
11817
11818/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011819/// initializer for the out-of-line declaration 'D'.
11820void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011821 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011822 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011823
Douglas Gregor552e2992012-02-21 02:22:07 +000011824 if (isStaticDataMember(D))
11825 PopExpressionEvaluationContext();
11826
John McCall731ad842009-12-19 09:28:58 +000011827 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011828 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011829}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011830
11831/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11832/// C++ if/switch/while/for statement.
11833/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011834DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011835 // C++ 6.4p2:
11836 // The declarator shall not specify a function or an array.
11837 // The type-specifier-seq shall not contain typedef and shall not declare a
11838 // new class or enumeration.
11839 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11840 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011841
11842 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011843 if (!Dcl)
11844 return true;
11845
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011846 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11847 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011848 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011849 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011850 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011851
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011852 return Dcl;
11853}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011854
Douglas Gregordfe65432011-07-28 19:11:31 +000011855void Sema::LoadExternalVTableUses() {
11856 if (!ExternalSource)
11857 return;
11858
11859 SmallVector<ExternalVTableUse, 4> VTables;
11860 ExternalSource->ReadUsedVTables(VTables);
11861 SmallVector<VTableUse, 4> NewUses;
11862 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11863 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11864 = VTablesUsed.find(VTables[I].Record);
11865 // Even if a definition wasn't required before, it may be required now.
11866 if (Pos != VTablesUsed.end()) {
11867 if (!Pos->second && VTables[I].DefinitionRequired)
11868 Pos->second = true;
11869 continue;
11870 }
11871
11872 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11873 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11874 }
11875
11876 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11877}
11878
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011879void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11880 bool DefinitionRequired) {
11881 // Ignore any vtable uses in unevaluated operands or for classes that do
11882 // not have a vtable.
11883 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000011884 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011885 return;
11886
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011887 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011888 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011889 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11890 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11891 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11892 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011893 // If we already had an entry, check to see if we are promoting this vtable
11894 // to required a definition. If so, we need to reappend to the VTableUses
11895 // list, since we may have already processed the first entry.
11896 if (DefinitionRequired && !Pos.first->second) {
11897 Pos.first->second = true;
11898 } else {
11899 // Otherwise, we can early exit.
11900 return;
11901 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011902 }
11903
11904 // Local classes need to have their virtual members marked
11905 // immediately. For all other classes, we mark their virtual members
11906 // at the end of the translation unit.
11907 if (Class->isLocalClass())
11908 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011909 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011910 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011911}
11912
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011913bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011914 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011915 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011916 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011917
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011918 // Note: The VTableUses vector could grow as a result of marking
11919 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011920 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011921 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011922 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011923 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011924 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011925 if (!Class)
11926 continue;
11927
11928 SourceLocation Loc = VTableUses[I].second;
11929
Richard Smithb9d0b762012-07-27 04:22:15 +000011930 bool DefineVTable = true;
11931
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011932 // If this class has a key function, but that key function is
11933 // defined in another translation unit, we don't need to emit the
11934 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011935 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011936 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011937 switch (KeyFunction->getTemplateSpecializationKind()) {
11938 case TSK_Undeclared:
11939 case TSK_ExplicitSpecialization:
11940 case TSK_ExplicitInstantiationDeclaration:
11941 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011942 DefineVTable = false;
11943 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011944
11945 case TSK_ExplicitInstantiationDefinition:
11946 case TSK_ImplicitInstantiation:
11947 // We will be instantiating the key function.
11948 break;
11949 }
11950 } else if (!KeyFunction) {
11951 // If we have a class with no key function that is the subject
11952 // of an explicit instantiation declaration, suppress the
11953 // vtable; it will live with the explicit instantiation
11954 // definition.
11955 bool IsExplicitInstantiationDeclaration
11956 = Class->getTemplateSpecializationKind()
11957 == TSK_ExplicitInstantiationDeclaration;
11958 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11959 REnd = Class->redecls_end();
11960 R != REnd; ++R) {
11961 TemplateSpecializationKind TSK
11962 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11963 if (TSK == TSK_ExplicitInstantiationDeclaration)
11964 IsExplicitInstantiationDeclaration = true;
11965 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11966 IsExplicitInstantiationDeclaration = false;
11967 break;
11968 }
11969 }
11970
11971 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011972 DefineVTable = false;
11973 }
11974
11975 // The exception specifications for all virtual members may be needed even
11976 // if we are not providing an authoritative form of the vtable in this TU.
11977 // We may choose to emit it available_externally anyway.
11978 if (!DefineVTable) {
11979 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11980 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011981 }
11982
11983 // Mark all of the virtual members of this class as referenced, so
11984 // that we can build a vtable. Then, tell the AST consumer that a
11985 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011986 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011987 MarkVirtualMembersReferenced(Loc, Class);
11988 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11989 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11990
11991 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000011992 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011993 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011994 const FunctionDecl *KeyFunctionDef = 0;
11995 if (!KeyFunction ||
11996 (KeyFunction->hasBody(KeyFunctionDef) &&
11997 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011998 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11999 TSK_ExplicitInstantiationDefinition
12000 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12001 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012002 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012003 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012004 VTableUses.clear();
12005
Douglas Gregor78844032011-04-22 22:25:37 +000012006 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012007}
Anders Carlssond6a637f2009-12-07 08:24:59 +000012008
Richard Smithb9d0b762012-07-27 04:22:15 +000012009void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12010 const CXXRecordDecl *RD) {
12011 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12012 E = RD->method_end(); I != E; ++I)
12013 if ((*I)->isVirtual() && !(*I)->isPure())
12014 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12015}
12016
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012017void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12018 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000012019 // Mark all functions which will appear in RD's vtable as used.
12020 CXXFinalOverriderMap FinalOverriders;
12021 RD->getFinalOverriders(FinalOverriders);
12022 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12023 E = FinalOverriders.end();
12024 I != E; ++I) {
12025 for (OverridingMethods::const_iterator OI = I->second.begin(),
12026 OE = I->second.end();
12027 OI != OE; ++OI) {
12028 assert(OI->second.size() > 0 && "no final overrider");
12029 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000012030
Richard Smithff817f72012-07-07 06:59:51 +000012031 // C++ [basic.def.odr]p2:
12032 // [...] A virtual member function is used if it is not pure. [...]
12033 if (!Overrider->isPure())
12034 MarkFunctionReferenced(Loc, Overrider);
12035 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012036 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012037
12038 // Only classes that have virtual bases need a VTT.
12039 if (RD->getNumVBases() == 0)
12040 return;
12041
12042 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12043 e = RD->bases_end(); i != e; ++i) {
12044 const CXXRecordDecl *Base =
12045 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012046 if (Base->getNumVBases() == 0)
12047 continue;
12048 MarkVirtualMembersReferenced(Loc, Base);
12049 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012050}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012051
12052/// SetIvarInitializers - This routine builds initialization ASTs for the
12053/// Objective-C implementation whose ivars need be initialized.
12054void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012055 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012056 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000012057 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000012058 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012059 CollectIvarsToConstructOrDestruct(OID, ivars);
12060 if (ivars.empty())
12061 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000012062 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012063 for (unsigned i = 0; i < ivars.size(); i++) {
12064 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012065 if (Field->isInvalidDecl())
12066 continue;
12067
Sean Huntcbb67482011-01-08 20:30:50 +000012068 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012069 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12070 InitializationKind InitKind =
12071 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000012072
12073 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12074 ExprResult MemberInit =
12075 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000012076 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012077 // Note, MemberInit could actually come back empty if no initialization
12078 // is required (e.g., because it would call a trivial default constructor)
12079 if (!MemberInit.get() || MemberInit.isInvalid())
12080 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000012081
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012082 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000012083 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12084 SourceLocation(),
12085 MemberInit.takeAs<Expr>(),
12086 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012087 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012088
12089 // Be sure that the destructor is accessible and is marked as referenced.
12090 if (const RecordType *RecordTy
12091 = Context.getBaseElementType(Field->getType())
12092 ->getAs<RecordType>()) {
12093 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000012094 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012095 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012096 CheckDestructorAccess(Field->getLocation(), Destructor,
12097 PDiag(diag::err_access_dtor_ivar)
12098 << Context.getBaseElementType(Field->getType()));
12099 }
12100 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012101 }
12102 ObjCImplementation->setIvarInitializers(Context,
12103 AllToInit.data(), AllToInit.size());
12104 }
12105}
Sean Huntfe57eef2011-05-04 05:57:24 +000012106
Sean Huntebcbe1d2011-05-04 23:29:54 +000012107static
12108void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12109 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12110 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12111 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12112 Sema &S) {
Sean Huntebcbe1d2011-05-04 23:29:54 +000012113 if (Ctor->isInvalidDecl())
12114 return;
12115
Richard Smitha8eaf002012-08-23 06:16:52 +000012116 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12117
12118 // Target may not be determinable yet, for instance if this is a dependent
12119 // call in an uninstantiated template.
12120 if (Target) {
12121 const FunctionDecl *FNTarget = 0;
12122 (void)Target->hasBody(FNTarget);
12123 Target = const_cast<CXXConstructorDecl*>(
12124 cast_or_null<CXXConstructorDecl>(FNTarget));
12125 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012126
12127 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12128 // Avoid dereferencing a null pointer here.
12129 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12130
12131 if (!Current.insert(Canonical))
12132 return;
12133
12134 // We know that beyond here, we aren't chaining into a cycle.
12135 if (!Target || !Target->isDelegatingConstructor() ||
12136 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012137 Valid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012138 Current.clear();
12139 // We've hit a cycle.
12140 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12141 Current.count(TCanonical)) {
12142 // If we haven't diagnosed this cycle yet, do so now.
12143 if (!Invalid.count(TCanonical)) {
12144 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012145 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012146 << Ctor;
12147
Richard Smitha8eaf002012-08-23 06:16:52 +000012148 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012149 if (TCanonical != Canonical)
12150 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12151
12152 CXXConstructorDecl *C = Target;
12153 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012154 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012155 (void)C->getTargetConstructor()->hasBody(FNTarget);
12156 assert(FNTarget && "Ctor cycle through bodiless function");
12157
Richard Smitha8eaf002012-08-23 06:16:52 +000012158 C = const_cast<CXXConstructorDecl*>(
12159 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012160 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12161 }
12162 }
12163
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012164 Invalid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012165 Current.clear();
12166 } else {
12167 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12168 }
12169}
12170
12171
Sean Huntfe57eef2011-05-04 05:57:24 +000012172void Sema::CheckDelegatingCtorCycles() {
12173 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12174
Douglas Gregor0129b562011-07-27 21:57:17 +000012175 for (DelegatingCtorDeclsType::iterator
12176 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012177 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012178 I != E; ++I)
12179 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012180
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012181 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12182 CE = Invalid.end();
12183 CI != CE; ++CI)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012184 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012185}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012186
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012187namespace {
12188 /// \brief AST visitor that finds references to the 'this' expression.
12189 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12190 Sema &S;
12191
12192 public:
12193 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12194
12195 bool VisitCXXThisExpr(CXXThisExpr *E) {
12196 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12197 << E->isImplicit();
12198 return false;
12199 }
12200 };
12201}
12202
12203bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12204 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12205 if (!TSInfo)
12206 return false;
12207
12208 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012209 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012210 if (!ProtoTL)
12211 return false;
12212
12213 // C++11 [expr.prim.general]p3:
12214 // [The expression this] shall not appear before the optional
12215 // cv-qualifier-seq and it shall not appear within the declaration of a
12216 // static member function (although its type and value category are defined
12217 // within a static member function as they are within a non-static member
12218 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012219 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012220 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012221 FindCXXThisExpr Finder(*this);
12222
12223 // If the return type came after the cv-qualifier-seq, check it now.
12224 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012225 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012226 return true;
12227
12228 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012229 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12230 return true;
12231
12232 return checkThisInStaticMemberFunctionAttributes(Method);
12233}
12234
12235bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12236 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12237 if (!TSInfo)
12238 return false;
12239
12240 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012241 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012242 if (!ProtoTL)
12243 return false;
12244
David Blaikie39e6ab42013-02-18 22:06:02 +000012245 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012246 FindCXXThisExpr Finder(*this);
12247
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012248 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012249 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012250 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012251 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012252 case EST_DynamicNone:
12253 case EST_MSAny:
12254 case EST_None:
12255 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012256
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012257 case EST_ComputedNoexcept:
12258 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12259 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012260
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012261 case EST_Dynamic:
12262 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012263 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012264 E != EEnd; ++E) {
12265 if (!Finder.TraverseType(*E))
12266 return true;
12267 }
12268 break;
12269 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012270
12271 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012272}
12273
12274bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12275 FindCXXThisExpr Finder(*this);
12276
12277 // Check attributes.
12278 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12279 A != AEnd; ++A) {
12280 // FIXME: This should be emitted by tblgen.
12281 Expr *Arg = 0;
12282 ArrayRef<Expr *> Args;
12283 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12284 Arg = G->getArg();
12285 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12286 Arg = G->getArg();
12287 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12288 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12289 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12290 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12291 else if (ExclusiveLockFunctionAttr *ELF
12292 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12293 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12294 else if (SharedLockFunctionAttr *SLF
12295 = dyn_cast<SharedLockFunctionAttr>(*A))
12296 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12297 else if (ExclusiveTrylockFunctionAttr *ETLF
12298 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12299 Arg = ETLF->getSuccessValue();
12300 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12301 } else if (SharedTrylockFunctionAttr *STLF
12302 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12303 Arg = STLF->getSuccessValue();
12304 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12305 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12306 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12307 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12308 Arg = LR->getArg();
12309 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12310 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12311 else if (ExclusiveLocksRequiredAttr *ELR
12312 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12313 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12314 else if (SharedLocksRequiredAttr *SLR
12315 = dyn_cast<SharedLocksRequiredAttr>(*A))
12316 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12317
12318 if (Arg && !Finder.TraverseStmt(Arg))
12319 return true;
12320
12321 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12322 if (!Finder.TraverseStmt(Args[I]))
12323 return true;
12324 }
12325 }
12326
12327 return false;
12328}
12329
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012330void
12331Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12332 ArrayRef<ParsedType> DynamicExceptions,
12333 ArrayRef<SourceRange> DynamicExceptionRanges,
12334 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012335 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012336 FunctionProtoType::ExtProtoInfo &EPI) {
12337 Exceptions.clear();
12338 EPI.ExceptionSpecType = EST;
12339 if (EST == EST_Dynamic) {
12340 Exceptions.reserve(DynamicExceptions.size());
12341 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12342 // FIXME: Preserve type source info.
12343 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12344
12345 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12346 collectUnexpandedParameterPacks(ET, Unexpanded);
12347 if (!Unexpanded.empty()) {
12348 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12349 UPPC_ExceptionType,
12350 Unexpanded);
12351 continue;
12352 }
12353
12354 // Check that the type is valid for an exception spec, and
12355 // drop it if not.
12356 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12357 Exceptions.push_back(ET);
12358 }
12359 EPI.NumExceptions = Exceptions.size();
12360 EPI.Exceptions = Exceptions.data();
12361 return;
12362 }
12363
12364 if (EST == EST_ComputedNoexcept) {
12365 // If an error occurred, there's no expression here.
12366 if (NoexceptExpr) {
12367 assert((NoexceptExpr->isTypeDependent() ||
12368 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12369 Context.BoolTy) &&
12370 "Parser should have made sure that the expression is boolean");
12371 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12372 EPI.ExceptionSpecType = EST_BasicNoexcept;
12373 return;
12374 }
12375
12376 if (!NoexceptExpr->isValueDependent())
12377 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012378 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012379 /*AllowFold*/ false).take();
12380 EPI.NoexceptExpr = NoexceptExpr;
12381 }
12382 return;
12383 }
12384}
12385
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012386/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12387Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12388 // Implicitly declared functions (e.g. copy constructors) are
12389 // __host__ __device__
12390 if (D->isImplicit())
12391 return CFT_HostDevice;
12392
12393 if (D->hasAttr<CUDAGlobalAttr>())
12394 return CFT_Global;
12395
12396 if (D->hasAttr<CUDADeviceAttr>()) {
12397 if (D->hasAttr<CUDAHostAttr>())
12398 return CFT_HostDevice;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012399 return CFT_Device;
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012400 }
12401
12402 return CFT_Host;
12403}
12404
12405bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12406 CUDAFunctionTarget CalleeTarget) {
12407 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12408 // Callable from the device only."
12409 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12410 return true;
12411
12412 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12413 // Callable from the host only."
12414 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12415 // Callable from the host only."
12416 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12417 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12418 return true;
12419
12420 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12421 return true;
12422
12423 return false;
12424}
John McCall76da55d2013-04-16 07:28:30 +000012425
12426/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12427///
12428MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12429 SourceLocation DeclStart,
12430 Declarator &D, Expr *BitWidth,
12431 InClassInitStyle InitStyle,
12432 AccessSpecifier AS,
12433 AttributeList *MSPropertyAttr) {
12434 IdentifierInfo *II = D.getIdentifier();
12435 if (!II) {
12436 Diag(DeclStart, diag::err_anonymous_property);
12437 return NULL;
12438 }
12439 SourceLocation Loc = D.getIdentifierLoc();
12440
12441 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12442 QualType T = TInfo->getType();
12443 if (getLangOpts().CPlusPlus) {
12444 CheckExtraCXXDefaultArguments(D);
12445
12446 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12447 UPPC_DataMemberType)) {
12448 D.setInvalidType();
12449 T = Context.IntTy;
12450 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12451 }
12452 }
12453
12454 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12455
12456 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12457 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12458 diag::err_invalid_thread)
12459 << DeclSpec::getSpecifierName(TSCS);
12460
12461 // Check to see if this name was declared as a member previously
12462 NamedDecl *PrevDecl = 0;
12463 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12464 LookupName(Previous, S);
12465 switch (Previous.getResultKind()) {
12466 case LookupResult::Found:
12467 case LookupResult::FoundUnresolvedValue:
12468 PrevDecl = Previous.getAsSingle<NamedDecl>();
12469 break;
12470
12471 case LookupResult::FoundOverloaded:
12472 PrevDecl = Previous.getRepresentativeDecl();
12473 break;
12474
12475 case LookupResult::NotFound:
12476 case LookupResult::NotFoundInCurrentInstantiation:
12477 case LookupResult::Ambiguous:
12478 break;
12479 }
12480
12481 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12482 // Maybe we will complain about the shadowed template parameter.
12483 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12484 // Just pretend that we didn't see the previous declaration.
12485 PrevDecl = 0;
12486 }
12487
12488 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12489 PrevDecl = 0;
12490
12491 SourceLocation TSSL = D.getLocStart();
12492 MSPropertyDecl *NewPD;
12493 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12494 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12495 II, T, TInfo, TSSL,
12496 Data.GetterId, Data.SetterId);
12497 ProcessDeclAttributes(TUScope, NewPD, D);
12498 NewPD->setAccess(AS);
12499
12500 if (NewPD->isInvalidDecl())
12501 Record->setInvalidDecl();
12502
12503 if (D.getDeclSpec().isModulePrivateSpecified())
12504 NewPD->setModulePrivate();
12505
12506 if (NewPD->isInvalidDecl() && PrevDecl) {
12507 // Don't introduce NewFD into scope; there's already something
12508 // with the same name in the same scope.
12509 } else if (II) {
12510 PushOnScopeChains(NewPD, S);
12511 } else
12512 Record->addDecl(NewPD);
12513
12514 return NewPD;
12515}